-
Notifications
You must be signed in to change notification settings - Fork 1
/
convert.py
333 lines (314 loc) · 12 KB
/
convert.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
import asyncio
import os
import time
from datetime import datetime
from io import BytesIO
from pathlib import Path
from telethon import functions, types
from telethon.errors import PhotoInvalidDimensionsError
from telethon.errors.rpcerrorlist import YouBlockedUserError
from telethon.tl.functions.messages import SendMediaRequest
from . import *
if not os.path.isdir("./temp"):
os.makedirs("./temp")
@bot.on(d3vil_cmd(pattern="stoi$"))
@bot.on(sudo_cmd(pattern="stoi$", allow_sudo=True))
async def _(d3vil):
if d3vil.fwd_from:
return
reply_to_id = d3vil.message.id
if d3vil.reply_to_msg_id:
reply_to_id = d3vil.reply_to_msg_id
event = await eor(d3vil, "Converting.....")
if not os.path.isdir(Config.TMP_DOWNLOAD_DIRECTORY):
os.makedirs(Config.TMP_DOWNLOAD_DIRECTORY)
if event.reply_to_msg_id:
filename = "hi.jpg"
file_name = filename
reply_message = await event.get_reply_message()
to_download_directory = Config.TMP_DOWNLOAD_DIRECTORY
downloaded_file_name = os.path.join(to_download_directory, file_name)
downloaded_file_name = await d3vil.client.download_media(
reply_message, downloaded_file_name
)
if os.path.exists(downloaded_file_name):
caat = await d3vil.client.send_file(
event.chat_id,
downloaded_file_name,
force_document=False,
reply_to=reply_to_id,
)
os.remove(downloaded_file_name)
await event.delete()
else:
await eod(event, "Can't Convert")
else:
await event.edit(f"Syntax : `{hl}stoi` reply to a Telegram normal sticker")
@bot.on(d3vil_cmd(pattern="itos$"))
@bot.on(sudo_cmd(pattern="itos$", allow_sudo=True))
async def _(d3vil):
if d3vil.fwd_from:
return
reply_to_id = d3vil.message.id
if d3vil.reply_to_msg_id:
reply_to_id = d3vil.reply_to_msg_id
event = await eor(d3vil, "Converting.....")
if not os.path.isdir(Config.TMP_DOWNLOAD_DIRECTORY):
os.makedirs(Config.TMP_DOWNLOAD_DIRECTORY)
if event.reply_to_msg_id:
filename = "hi.webp"
file_name = filename
reply_message = await event.get_reply_message()
to_download_directory = Config.TMP_DOWNLOAD_DIRECTORY
downloaded_file_name = os.path.join(to_download_directory, file_name)
downloaded_file_name = await d3vil.client.download_media(
reply_message, downloaded_file_name
)
if os.path.exists(downloaded_file_name):
caat = await d3vil.client.send_file(
event.chat_id,
downloaded_file_name,
force_document=False,
reply_to=reply_to_id,
)
os.remove(downloaded_file_name)
await event.delete()
else:
await eod(event, "Can't Convert")
else:
await event.edit(f"Syntax : `{hl}itos` reply to a Telegram normal sticker")
async def silently_send_message(conv, text):
await conv.send_message(text)
response = await conv.get_response()
await conv.mark_read(message=response)
return response
@bot.on(d3vil_cmd(pattern="ttf ?(.*)"))
@bot.on(sudo_cmd(pattern="ttf ?(.*)", allow_sudo=True))
async def get(event):
if event.fwd_from:
return
name = event.text[5:]
if name is None:
await eod(event, f"reply to text message as `{hl}ttf <file name>`")
return
m = await event.get_reply_message()
if m.text:
with open(name, "w") as f:
f.write(m.message)
await event.delete()
await event.client.send_file(event.chat_id, name, force_document=True)
os.remove(name)
else:
await eod(event, f"Reply to text message as `{hl}ttf <file name>`")
@bot.on(d3vil_cmd(pattern="ftoi$"))
@bot.on(sudo_cmd(pattern="ftoi$", allow_sudo=True))
async def on_file_to_photo(event):
if event.fwd_from:
return
target = await event.get_reply_message()
hbot = await eor(event, "Converting.....")
try:
image = target.media.document
except AttributeError:
return
if not image.mime_type.startswith("image/"):
return # This isn't an image
if image.mime_type == "image/webp":
return # Telegram doesn't let you directly send stickers as photos
if image.size > 10 * 1024 * 1024:
return # We'd get PhotoSaveFileInvalidError otherwise
file = await event.client.download_media(target, file=BytesIO())
file.seek(0)
img = await event.client.upload_file(file)
img.name = "image.png"
try:
await event.client(
SendMediaRequest(
peer=await event.get_input_chat(),
media=types.InputMediaUploadedPhoto(img),
message=target.message,
entities=target.entities,
reply_to_msg_id=target.id,
)
)
except PhotoInvalidDimensionsError:
return
await hbot.delete()
@bot.on(d3vil_cmd(pattern="gif$"))
@bot.on(sudo_cmd(pattern="gif$", allow_sudo=True))
async def _(event):
if event.fwd_from:
return
d3vilreply = await event.get_reply_message()
if not d3vilreply or not d3vilreply.media or not d3vilreply.media.document:
return await edit_or_reply(event, "`Stupid!, This is not animated sticker.`")
if d3vilreply.media.document.mime_type != "application/x-tgsticker":
return await edit_or_reply(event, "`Stupid!, This is not animated sticker.`")
reply_to_id = event.message
if event.reply_to_msg_id:
reply_to_id = await event.get_reply_message()
chat = "@tgstogifbot"
d3vilevent = await edit_or_reply(event, "`Converting to gif ...`")
async with bot.conversation(chat) as conv:
try:
await silently_send_message(conv, "/start")
await bot.send_file(chat, d3vilreply.media)
response = await conv.get_response()
await bot.send_read_acknowledge(conv.chat_id)
if response.text.startswith("Send me an animated sticker!"):
return await d3vilevent.edit("`This file is not supported`")
d3vilresponse = response if response.media else await conv.get_response()
await bot.send_read_acknowledge(conv.chat_id)
d3vilfile = Path(await event.client.download_media(d3vilresponse, "./temp/"))
d3vilgif = Path(await unzip(d3vilfile))
d3vilkrish = await bot.send_file(
event.chat_id,
d3vilgif,
support_streaming=True,
force_document=False,
reply_to=reply_to_id,
)
await bot(
functions.messages.SaveGifRequest(
id=types.InputDocument(
id=d3vilkrish.media.document.id,
access_hash=d3vilkrish.media.document.access_hash,
file_reference=d3vilkrish.media.document.file_reference,
),
unsave=True,
)
)
await d3vilevent.delete()
for files in (d3vilgif, d3vilfile):
if files and os.path.exists(files):
os.remove(files)
except YouBlockedUserError:
await d3vilevent.edit("Unblock @tgstogifbot")
return
@bot.on(d3vil_cmd(pattern="nfc ?(.*)"))
@bot.on(sudo_cmd(pattern="nfc ?(.*)", allow_sudo=True))
async def _(event):
if event.fwd_from:
return
if not event.reply_to_msg_id:
await eod(event, "```Reply to any media file.```")
return
reply_message = await event.get_reply_message()
if not reply_message.media:
await eod(event, "reply to media file")
return
input_str = event.pattern_match.group(1)
if input_str is None:
await eod(event, f"Try `{hl}nfc voice` or`{hl}nfc mp3`")
return
if input_str in ["mp3", "voice"]:
event = await eor(event, "converting...")
else:
await eod(event, f"Try `{hl}nfc voice` or`{hl}nfc mp3`")
return
try:
start = datetime.datetime.now()
c_time = time.time()
downloaded_file_name = await event.client.download_media(
reply_message,
Config.TMP_DOWNLOAD_DIRECTORY,
progress_callback=lambda d, t: asyncio.get_event_loop().create_task(
progress(d, t, event, c_time, "trying to download")
),
)
except Exception as e: # pylint:disable=C0103,W0703
await event.edit(str(e))
else:
end = datetime.datetime.now()
ms = (end - start).seconds
await event.edit(
"Downloaded to `{}` in {} seconds.".format(downloaded_file_name, ms)
)
new_required_file_name = ""
new_required_file_caption = ""
command_to_run = []
voice_note = False
supports_streaming = False
if input_str == "voice":
new_required_file_caption = "voice_" + str(round(time.time())) + ".opus"
new_required_file_name = (
Config.TMP_DOWNLOAD_DIRECTORY + "/" + new_required_file_caption
)
command_to_run = [
"ffmpeg",
"-i",
downloaded_file_name,
"-map",
"0:a",
"-codec:a",
"libopus",
"-b:a",
"100k",
"-vbr",
"on",
new_required_file_name,
]
voice_note = True
supports_streaming = True
elif input_str == "mp3":
new_required_file_caption = "mp3_" + str(round(time.time())) + ".mp3"
new_required_file_name = (
Config.TMP_DOWNLOAD_DIRECTORY + "/" + new_required_file_caption
)
command_to_run = [
"ffmpeg",
"-i",
downloaded_file_name,
"-vn",
new_required_file_name,
]
voice_note = False
supports_streaming = True
else:
await event.edit("not supported")
os.remove(downloaded_file_name)
return
logger.info(command_to_run)
# TODO: re-write create_subprocess_exec 😉
process = await asyncio.create_subprocess_exec(
*command_to_run,
# stdout must a pipe to be accessible as process.stdout
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
# Wait for the subprocess to finish
stdout, stderr = await process.communicate()
stderr.decode().strip()
stdout.decode().strip()
os.remove(downloaded_file_name)
if os.path.exists(new_required_file_name):
force_document = False
await event.client.send_file(
entity=event.chat_id,
file=new_required_file_name,
allow_cache=False,
silent=True,
force_document=force_document,
voice_note=voice_note,
supports_streaming=supports_streaming,
progress_callback=lambda d, t: asyncio.get_event_loop().create_task(
progress(d, t, event, c_time, "trying to upload")
),
)
os.remove(new_required_file_name)
await event.delete()
CmdHelp("convert").add_command(
"stoi", "<reply to a sticker", "Converts the replied sticker into an image"
).add_command(
"itos", "<reply to a image>", "Converts the replied image to sticker"
).add_command(
"ftoi", "<reply to a image file", "Converts the replied file image to normal image"
).add_command(
"gif", "<reply to a animated sticker", "Converts the replied animated sticker into gif"
).add_command(
"ttf", "<reply to text>", "Converts the given text message to required file(given file name)"
).add_command(
"nfc voice", "<reply to media to extract voice>", "Converts the replied media file to voice"
).add_command(
"nfc mp3", "<reply to media to extract mp3>", "Converts the replied media file to mp3"
).add()