forked from GreyMatters-Tech/url-auto-delete-shortener-bot
-
Notifications
You must be signed in to change notification settings - Fork 1
/
commands.py
526 lines (487 loc) · 22.2 KB
/
commands.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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
import os
import logging
import random
import asyncio
from Script import script
from pyrogram import Client, filters, enums
from pyrogram.errors import ChatAdminRequired, FloodWait
from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup
from database.ia_filterdb import Media, get_file_details, unpack_new_file_id
from database.users_chats_db import db
from info import *
from utils import get_settings, get_size, is_subscribed, save_group_settings, temp
from database.connections_mdb import active_connection
import re
import json
import base64
logger = logging.getLogger(__name__)
BATCH_FILES = {}
@Client.on_message(filters.command("start") & filters.incoming)
async def start(client, message):
if message.chat.type in [enums.ChatType.GROUP, enums.ChatType.SUPERGROUP]:
buttons = [
[
InlineKeyboardButton('⚡ UᎮDΛTΞS ⚡', url='https://t.me/greymatter_bots')
],
[
InlineKeyboardButton('⚡ SUBSCᏒIBΞ ⚡', url=f"https://youtube.com/c/GreyMattersBot"),
],
[
InlineKeyboardButton(text=DOWNLOAD_TEXT_NAME,url=DOWNLOAD_TEXT_URL)
]
]
reply_markup = InlineKeyboardMarkup(buttons)
await message.reply(script.START_TXT.format(message.from_user.mention if message.from_user else message.chat.title, temp.U_NAME, temp.B_NAME), reply_markup=reply_markup)
await asyncio.sleep(2) # 😢 https://github.com/EvamariaTG/EvaMaria/blob/master/plugins/p_ttishow.py#L17 😬 wait a bit, before checking.
if not await db.get_chat(message.chat.id):
total=await client.get_chat_members_count(message.chat.id)
await client.send_message(LOG_CHANNEL, script.LOG_TEXT_G.format(message.chat.title, message.chat.id, total, "Unknown"))
await db.add_chat(message.chat.id, message.chat.title)
return
if not await db.is_user_exist(message.from_user.id):
await db.add_user(message.from_user.id, message.from_user.first_name)
await client.send_message(LOG_CHANNEL, script.LOG_TEXT_P.format(message.from_user.id, message.from_user.mention))
if len(message.command) != 2:
buttons = [[
InlineKeyboardButton('⚚ ΛᎠᎠ MΞ ϮԾ YԾUᏒ GᏒԾUᎮ ⚚', url=f'http://t.me/{temp.U_NAME}?startgroup=true')
],[
InlineKeyboardButton('⚡ SUBSCᏒIBΞ ⚡', url='https://youtube.com/c/GreyMattersBot'),
InlineKeyboardButton('🤖 UᎮDΛTΞS 🤖', url='https://t.me/greymatter_bots')
],[
InlineKeyboardButton('♻️ HΞLᎮ ♻️', callback_data='help'),
InlineKeyboardButton('♻️ ΛBOUT ♻️', callback_data='about')
]]
reply_markup = InlineKeyboardMarkup(buttons)
await message.reply_photo(
photo=random.choice(PICS),
caption=script.START_TXT.format(message.from_user.mention, temp.U_NAME, temp.B_NAME),
reply_markup=reply_markup,
parse_mode=enums.ParseMode.HTML
)
return
if AUTH_CHANNEL and not await is_subscribed(client, message):
try:
invite_link = await client.create_chat_invite_link(int(AUTH_CHANNEL))
except ChatAdminRequired:
logger.error("Make sure Bot is admin in Forcesub channel")
return
btn = [
[
InlineKeyboardButton(
"🔥 JOIИ UᎮDΛTΞS CHΛИИΞL 🔥", url=invite_link.invite_link
)
]
]
if message.command[1] != "subscribe":
try:
kk, file_id = message.command[1].split("_", 1)
pre = 'checksubp' if kk == 'filep' else 'checksub'
btn.append([InlineKeyboardButton(" 🔄 Try Again", callback_data=f"{pre}#{file_id}")])
except (IndexError, ValueError):
btn.append([InlineKeyboardButton(" 🔄 Try Again", url=f"https://t.me/{temp.U_NAME}?start={message.command[1]}")])
await client.send_message(
chat_id=message.from_user.id,
text="**𝑱𝒐𝒊𝒏 𝑶𝒖𝒓 𝑴𝒐𝒗𝒊𝒆 𝑼𝒑𝒅𝒂𝒕𝒆𝒔 𝑪𝒉𝒂𝒏𝒏𝒆𝒍 𝑻𝒐 𝑼𝒔𝒆 𝑻𝒉𝒊𝒔 𝑩𝒐𝒕!**",
reply_markup=InlineKeyboardMarkup(btn),
parse_mode=enums.ParseMode.MARKDOWN
)
return
if len(message.command) == 2 and message.command[1] in ["subscribe", "error", "okay", "help"]:
buttons = [[
InlineKeyboardButton('⚚ ΛᎠᎠ MΞ ϮԾ YԾUᏒ GᏒԾUᎮ ⚚', url=f'http://t.me/{temp.U_NAME}?startgroup=true')
],[
InlineKeyboardButton('⚡ SUBSCᏒIBΞ ⚡', url='https://youtube.com/c/GreyMattersBot'),
InlineKeyboardButton('🤖 UᎮDΛTΞS 🤖', url='https://t.me/greymatter_bots')
],[
InlineKeyboardButton('♻️ HΞLᎮ ♻️', callback_data='help'),
InlineKeyboardButton('♻️ ΛBOUT ♻️', callback_data='about')
]]
reply_markup = InlineKeyboardMarkup(buttons)
await message.reply_photo(
photo=random.choice(PICS),
caption=script.START_TXT.format(message.from_user.mention, temp.U_NAME, temp.B_NAME),
reply_markup=reply_markup,
parse_mode=enums.ParseMode.HTML
)
return
data = message.command[1]
try:
pre, file_id = data.split('_', 1)
except:
file_id = data
pre = ""
if data.split("-", 1)[0] == "BATCH":
sts = await message.reply("<b>𝙰𝙲𝙲𝙴𝚂𝚂𝙸𝙽𝙶 𝙵𝙸𝙻𝙴𝚂.../</b>")
file_id = data.split("-", 1)[1]
msgs = BATCH_FILES.get(file_id)
if not msgs:
file = await client.download_media(file_id)
try:
with open(file) as file_data:
msgs=json.loads(file_data.read())
except:
await sts.edit("FAILED")
return await client.send_message(LOG_CHANNEL, "UNABLE TO OPEN FILE.")
os.remove(file)
BATCH_FILES[file_id] = msgs
for msg in msgs:
title = msg.get("title")
size=get_size(int(msg.get("size", 0)))
f_caption=msg.get("caption", "")
if BATCH_FILE_CAPTION:
try:
f_caption=BATCH_FILE_CAPTION.format(file_name= '' if title is None else title, file_size='' if size is None else size, file_caption='' if f_caption is None else f_caption)
except Exception as e:
logger.exception(e)
f_caption=f_caption
if f_caption is None:
f_caption = f"{title}"
try:
await client.send_cached_media(
chat_id=message.from_user.id,
file_id=msg.get("file_id"),
caption=f_caption,
protect_content=msg.get('protect', False),
)
except FloodWait as e:
await asyncio.sleep(e.x)
logger.warning(f"Floodwait of {e.x} sec.")
await client.send_cached_media(
chat_id=message.from_user.id,
file_id=msg.get("file_id"),
caption=f_caption,
protect_content=msg.get('protect', False),
)
except Exception as e:
logger.warning(e, exc_info=True)
continue
await asyncio.sleep(1)
await sts.delete()
return
elif data.split("-", 1)[0] == "DSTORE":
sts = await message.reply("<b>𝙰𝙲𝙲𝙴𝚂𝚂𝙸𝙽𝙶 𝙵𝙸𝙻𝙴𝚂.../</b>")
b_string = data.split("-", 1)[1]
decoded = (base64.urlsafe_b64decode(b_string + "=" * (-len(b_string) % 4))).decode("ascii")
try:
f_msg_id, l_msg_id, f_chat_id, protect = decoded.split("_", 3)
except:
f_msg_id, l_msg_id, f_chat_id = decoded.split("_", 2)
protect = "/pbatch" if PROTECT_CONTENT else "batch"
diff = int(l_msg_id) - int(f_msg_id)
async for msg in client.iter_messages(int(f_chat_id), int(l_msg_id), int(f_msg_id)):
if msg.media:
media = getattr(msg, msg.media.value)
if BATCH_FILE_CAPTION:
try:
f_caption=BATCH_FILE_CAPTION.format(file_name=getattr(media, 'file_name', ''), file_size=getattr(media, 'file_size', ''), file_caption=getattr(msg, 'caption', ''))
except Exception as e:
logger.exception(e)
f_caption = getattr(msg, 'caption', '')
else:
media = getattr(msg, msg.media.value)
file_name = getattr(media, 'file_name', '')
f_caption = getattr(msg, 'caption', file_name)
try:
await msg.copy(message.chat.id, caption=f_caption, protect_content=True if protect == "/pbatch" else False)
except FloodWait as e:
await asyncio.sleep(e.x)
await msg.copy(message.chat.id, caption=f_caption, protect_content=True if protect == "/pbatch" else False)
except Exception as e:
logger.exception(e)
continue
elif msg.empty:
continue
else:
try:
await msg.copy(message.chat.id, protect_content=True if protect == "/pbatch" else False)
except FloodWait as e:
await asyncio.sleep(e.x)
await msg.copy(message.chat.id, protect_content=True if protect == "/pbatch" else False)
except Exception as e:
logger.exception(e)
continue
await asyncio.sleep(1)
return await sts.delete()
files_ = await get_file_details(file_id)
if not files_:
pre, file_id = ((base64.urlsafe_b64decode(data + "=" * (-len(data) % 4))).decode("ascii")).split("_", 1)
try:
msg = await client.send_cached_media(
chat_id=message.from_user.id,
file_id=file_id,
protect_content=True if pre == 'filep' else False,
)
filetype = msg.media
file = getattr(msg, filetype.value)
title = file.file_name
size=get_size(file.file_size)
f_caption = f"<code>{title}</code>"
if CUSTOM_FILE_CAPTION:
try:
f_caption=CUSTOM_FILE_CAPTION.format(file_name= '' if title is None else title, file_size='' if size is None else size, file_caption='')
except:
return
await msg.edit_caption(f_caption)
return
except:
pass
return await message.reply('No such file exist.')
files = files_[0]
title = files.file_name
size=get_size(files.file_size)
f_caption=files.caption
if CUSTOM_FILE_CAPTION:
try:
f_caption=CUSTOM_FILE_CAPTION.format(file_name= '' if title is None else title, file_size='' if size is None else size, file_caption='' if f_caption is None else f_caption)
except Exception as e:
logger.exception(e)
f_caption=f_caption
if f_caption is None:
f_caption = f"{files.file_name}"
await client.send_cached_media(
chat_id=message.from_user.id,
file_id=file_id,
caption=f_caption,
reply_markup=InlineKeyboardMarkup( [ [ InlineKeyboardButton('sᴜʙsᴄʀɪʙᴇ', url='https://youtube.com/c/GreyMattersBot') ] ] ),
protect_content=True if pre == 'filep' else False,
)
@Client.on_message(filters.command('channel') & filters.user(ADMINS))
async def channel_info(bot, message):
"""Send basic information of channel"""
if isinstance(CHANNELS, (int, str)):
channels = [CHANNELS]
elif isinstance(CHANNELS, list):
channels = CHANNELS
else:
raise ValueError("Unexpected type of CHANNELS")
text = '📑 **Indexed channels/groups**\n'
for channel in channels:
chat = await bot.get_chat(channel)
if chat.username:
text += '\n@' + chat.username
else:
text += '\n' + chat.title or chat.first_name
text += f'\n\n**Total:** {len(CHANNELS)}'
if len(text) < 4096:
await message.reply(text)
else:
file = 'Indexed channels.txt'
with open(file, 'w') as f:
f.write(text)
await message.reply_document(file)
os.remove(file)
@Client.on_message(filters.command('logs') & filters.user(ADMINS))
async def log_file(bot, message):
"""Send log file"""
try:
await message.reply_document('TelegramBot.log')
except Exception as e:
await message.reply(str(e))
@Client.on_message(filters.command('delete') & filters.user(ADMINS))
async def delete(bot, message):
"""Delete file from database"""
reply = message.reply_to_message
if reply and reply.media:
msg = await message.reply("𝐃𝐞𝐥𝐞𝐭𝐢𝐧𝐠....🗑️", quote=True)
else:
await message.reply('Reply to file with /delete which you want to delete', quote=True)
return
for file_type in ("document", "video", "audio"):
media = getattr(reply, file_type, None)
if media is not None:
break
else:
await msg.edit('This is not supported file format')
return
file_id, file_ref = unpack_new_file_id(media.file_id)
result = await Media.collection.delete_one({
'_id': file_id,
})
if result.deleted_count:
await msg.edit('**𝙵𝙸𝙻𝙴 𝚂𝚄𝙲𝙲𝙴𝚂𝚂𝙵𝚄𝙻𝙻𝚈 𝙳𝙴𝙻𝙴𝚃𝙴𝙳**')
else:
file_name = re.sub(r"(_|\-|\.|\+)", " ", str(media.file_name))
result = await Media.collection.delete_many({
'file_name': file_name,
'file_size': media.file_size,
'mime_type': media.mime_type
})
if result.deleted_count:
await msg.edit('**𝙵𝙸𝙻𝙴 𝚂𝚄𝙲𝙲𝙴𝚂𝚂𝙵𝚄𝙻𝙻𝚈 𝙳𝙴𝙻𝙴𝚃𝙴𝙳**')
else:
# files indexed before https://github.com/EvamariaTG/EvaMaria/commit/f3d2a1bcb155faf44178e5d7a685a1b533e714bf#diff-86b613edf1748372103e94cacff3b578b36b698ef9c16817bb98fe9ef22fb669R39
# have original file name.
result = await Media.collection.delete_many({
'file_name': media.file_name,
'file_size': media.file_size,
'mime_type': media.mime_type
})
if result.deleted_count:
await msg.edit('**𝙵𝙸𝙻𝙴 𝚂𝚄𝙲𝙲𝙴𝚂𝚂𝙵𝚄𝙻𝙻𝚈 𝙳𝙴𝙻𝙴𝚃𝙴𝙳**')
else:
await msg.edit('File not found in database')
@Client.on_message(filters.command('deleteall') & filters.user(ADMINS))
async def delete_all_index(bot, message):
await message.reply_text(
'**𝚃𝙷𝙸𝚂 𝙿𝚁𝙾𝙲𝙴𝚂𝚂 𝚆𝙸𝙻𝙻 𝙳𝙴𝙻𝙴𝚃𝙴 𝙰𝙻𝙻 𝚃𝙷𝙴 𝙵𝙸𝙻𝙴𝚂 𝙵𝚁𝙾𝙼 𝚈𝙾𝚄𝚁 𝙳𝙰𝚃𝙰𝙱𝙰𝚂𝙴.\n𝙳𝙾 𝚈𝙾𝚄 𝚆𝙰𝙽𝚃 𝚃𝙾 𝙲𝙾𝙽𝚃𝙸𝙽𝚄𝙴 𝚃𝙷𝙸𝚂..??**',
reply_markup=InlineKeyboardMarkup(
[
[
InlineKeyboardButton(
text="⚡ 𝐘𝐞𝐬 ⚡", callback_data="autofilter_delete"
)
],
[
InlineKeyboardButton(
text="❄ 𝐂𝐚𝐧𝐜𝐞𝐥 ❄", callback_data="close_data"
)
],
]
),
quote=True,
)
@Client.on_callback_query(filters.regex(r'^autofilter_delete'))
async def delete_all_index_confirm(bot, message):
await Media.collection.drop()
await message.answer('𝙿𝙻𝙴𝙰𝚂𝙴 𝚂𝙷𝙰𝚁𝙴 𝙰𝙽𝙳 𝚂𝚄𝙿𝙿𝙾𝚁𝚃')
await message.message.edit('Succesfully Deleted All The Indexed Files.')
@Client.on_message(filters.command('settings'))
async def settings(client, message):
userid = message.from_user.id if message.from_user else None
if not userid:
return await message.reply(f"You are anonymous admin. Use /connect {message.chat.id} in PM")
chat_type = message.chat.type
if chat_type == enums.ChatType.PRIVATE:
grpid = await active_connection(str(userid))
if grpid is not None:
grp_id = grpid
try:
chat = await client.get_chat(grpid)
title = chat.title
except:
await message.reply_text("Make sure I'm present in your group!!", quote=True)
return
else:
await message.reply_text("I'm not connected to any groups!", quote=True)
return
elif chat_type in [enums.ChatType.GROUP, enums.ChatType.SUPERGROUP]:
grp_id = message.chat.id
title = message.chat.title
else:
return
st = await client.get_chat_member(grp_id, userid)
if (
st.status != enums.ChatMemberStatus.ADMINISTRATOR
and st.status != enums.ChatMemberStatus.OWNER
and str(userid) not in ADMINS
):
return
settings = await get_settings(grp_id)
if settings is not None:
buttons = [
[
InlineKeyboardButton(
'𝐅𝐈𝐋𝐓𝐄𝐑 𝐁𝐔𝐓𝐓𝐎𝐍',
callback_data=f'setgs#button#{settings["button"]}#{grp_id}',
),
InlineKeyboardButton(
'𝐒𝐈𝐍𝐆𝐋𝐄' if settings["button"] else '𝐃𝐎𝐔𝐁𝐋𝐄',
callback_data=f'setgs#button#{settings["button"]}#{grp_id}',
),
],
[
InlineKeyboardButton(
'𝐁𝐎𝐓 𝐏𝐌',
callback_data=f'setgs#botpm#{settings["botpm"]}#{grp_id}',
),
InlineKeyboardButton(
'✅ 𝐘𝐄𝐒' if settings["botpm"] else '❌ 𝐍𝐎',
callback_data=f'setgs#botpm#{settings["botpm"]}#{grp_id}',
),
],
[
InlineKeyboardButton(
'𝐅𝐈𝐋𝐄 𝐒𝐄𝐂𝐔𝐑𝐄',
callback_data=f'setgs#file_secure#{settings["file_secure"]}#{grp_id}',
),
InlineKeyboardButton(
'✅ 𝐘𝐄𝐒' if settings["file_secure"] else '❌ 𝐍𝐎',
callback_data=f'setgs#file_secure#{settings["file_secure"]}#{grp_id}',
),
],
[
InlineKeyboardButton(
'𝐈𝐌𝐃𝐁',
callback_data=f'setgs#imdb#{settings["imdb"]}#{grp_id}',
),
InlineKeyboardButton(
'✅ 𝐘𝐄𝐒' if settings["imdb"] else '❌ 𝐍𝐎',
callback_data=f'setgs#imdb#{settings["imdb"]}#{grp_id}',
),
],
[
InlineKeyboardButton(
'𝐒𝐏𝐄𝐋𝐋 𝐂𝐇𝐄𝐂𝐊',
callback_data=f'setgs#spell_check#{settings["spell_check"]}#{grp_id}',
),
InlineKeyboardButton(
'✅ 𝐘𝐄𝐒' if settings["spell_check"] else '❌ 𝐍𝐎',
callback_data=f'setgs#spell_check#{settings["spell_check"]}#{grp_id}',
),
],
[
InlineKeyboardButton(
'𝐖𝐄𝐋𝐂𝐎𝐌𝐄',
callback_data=f'setgs#welcome#{settings["welcome"]}#{grp_id}',
),
InlineKeyboardButton(
'✅ 𝐘𝐄𝐒' if settings["welcome"] else '❌ 𝐍𝐎',
callback_data=f'setgs#welcome#{settings["welcome"]}#{grp_id}',
),
],
]
reply_markup = InlineKeyboardMarkup(buttons)
await message.reply_text(
text=f"<b>𝙲𝙷𝙰𝙽𝙶𝙴 𝚃𝙷𝙴 𝙱𝙾𝚃 𝚂𝙴𝚃𝚃𝙸𝙽𝙶𝚂 𝙵𝙾𝚁 {title}..⚙</b>",
reply_markup=reply_markup,
disable_web_page_preview=True,
parse_mode=enums.ParseMode.HTML,
reply_to_message_id=message.id
)
@Client.on_message(filters.command('set_template'))
async def save_template(client, message):
sts = await message.reply("**𝙲𝙷𝙴𝙲𝙺𝙸𝙽𝙶 𝙽𝙴𝚆 𝚃𝙴𝙼𝙿𝙻𝙰𝚃𝙴**")
userid = message.from_user.id if message.from_user else None
if not userid:
return await message.reply(f"You are anonymous admin. Use /connect {message.chat.id} in PM")
chat_type = message.chat.type
if chat_type == enums.ChatType.PRIVATE:
grpid = await active_connection(str(userid))
if grpid is not None:
grp_id = grpid
try:
chat = await client.get_chat(grpid)
title = chat.title
except:
await message.reply_text("Make sure I'm present in your group!!", quote=True)
return
else:
await message.reply_text("I'm not connected to any groups!", quote=True)
return
elif chat_type in [enums.ChatType.GROUP, enums.ChatType.SUPERGROUP]:
grp_id = message.chat.id
title = message.chat.title
else:
return
st = await client.get_chat_member(grp_id, userid)
if (
st.status != enums.ChatMemberStatus.ADMINISTRATOR
and st.status != enums.ChatMemberStatus.OWNER
and str(userid) not in ADMINS
):
return
if len(message.command) < 2:
return await sts.edit("No Input!!")
template = message.text.split(" ", 1)[1]
await save_group_settings(grp_id, 'template', template)
await sts.edit(f"𝚂𝚄𝙲𝙲𝙴𝚂𝚂𝙵𝚄𝙻𝙻𝚈 𝚄𝙿𝙶𝚁𝙰𝙳𝙴𝙳 𝚈𝙾𝚄𝚁 𝚃𝙴𝙼𝙿𝙻𝙰𝚃𝙴 𝙵𝙾𝚁 {title} to\n\n{template}")