-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path__main__.py
549 lines (449 loc) · 21.9 KB
/
__main__.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
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
import importlib
import re
import json
import requests
from typing import Optional, List
from parsel import Selector
from urllib.request import urlopen
from telegram import Message, Chat, Update, Bot, User
from telegram import ParseMode, InlineKeyboardMarkup, InlineKeyboardButton
from telegram.error import Unauthorized, BadRequest, TimedOut, NetworkError, ChatMigrated, TelegramError
from telegram.ext import CommandHandler, MessageHandler, CallbackQueryHandler, Filters
from telegram.ext.dispatcher import run_async, DispatcherHandlerStop
from telegram.utils.helpers import escape_markdown
from tg_bot import dispatcher, updater, TOKEN, WEBHOOK, OWNER_ID, CERT_PATH, PORT, URL, LOGGER, \
ALLOW_EXCL
# needed to dynamically load modules
# NOTE: Module order is not guaranteed, specify that in the config file!
from tg_bot.modules import ALL_MODULES
from tg_bot import dispatcher
from tg_bot.modules.disable import DisableAbleCommandHandler
from tg_bot.modules.helper_funcs.chat_status import is_user_admin
from tg_bot.modules.helper_funcs.misc import paginate_modules
PM_START_TEXT = """
𝐈 𝐚𝐦 𝐚 𝐏𝐨𝐰𝐞𝐫𝐟𝐮𝐥 𝐓𝐞𝐥𝐞𝐠𝐫𝐚𝐦 𝐆𝐫𝐨𝐮𝐩 𝐌𝐚𝐧𝐚𝐠𝐞𝐦𝐞𝐧𝐭 𝐛𝐨𝐭 𝐰𝐢𝐭𝐡 𝐒𝐨𝐦𝐞 𝐀𝐧𝐢𝐦𝐞 𝐅𝐮𝐧.
𝐀𝐝𝐝 𝐦𝐞 𝐭𝐨 𝐲𝐨𝐮𝐫 𝐠𝐫𝐨𝐮𝐩 𝐟𝐨𝐫 𝐬𝐩𝐚𝐦 𝐟𝐫𝐞𝐞 𝐫𝐮𝐧𝐧𝐢𝐧𝐠.
================================
>> 𝐓𝐨 𝐬𝐞𝐞 𝐥𝐢𝐬𝐭 𝐨𝐟 𝐚𝐯𝐚𝐢𝐥𝐚𝐛𝐥𝐞 𝐜𝐨𝐦𝐦𝐚𝐧𝐝𝐬 𝐡𝐢𝐭 /help.
================================
"""
HELP_STRINGS = """
Hello! my name *{}*.
*Main* commands available:
- ▪/start: start the bot
- ▪/help: PM's you this message.
- ▪/help <module name>: PM's you info about that module.
- ▪/settings:
- ♡in PM: will send you your settings for all supported modules.
- ♡in a group: will redirect you to pm, with all that chat's settings.
{}
*And* the following:
""".format(dispatcher.bot.first_name, "" if not ALLOW_EXCL else "\nAll commands can either be used with / or !.\n")
MEIKO_IMG = "https://telegra.ph/file/48d2e685a74ffb2273397.jpg"
DONATE_STRING = """No need to donate for hitomi"""
IMPORTED = {}
MIGRATEABLE = []
HELPABLE = {}
STATS = []
USER_INFO = []
DATA_IMPORT = []
DATA_EXPORT = []
CHAT_SETTINGS = {}
USER_SETTINGS = {}
for module_name in ALL_MODULES:
imported_module = importlib.import_module("tg_bot.modules." + module_name)
if not hasattr(imported_module, "__mod_name__"):
imported_module.__mod_name__ = imported_module.__name__
if not imported_module.__mod_name__.lower() in IMPORTED:
IMPORTED[imported_module.__mod_name__.lower()] = imported_module
else:
raise Exception("Can't have two modules with the same name! Please change one")
if hasattr(imported_module, "__help__") and imported_module.__help__:
HELPABLE[imported_module.__mod_name__.lower()] = imported_module
# Chats to migrate on chat_migrated events
if hasattr(imported_module, "__migrate__"):
MIGRATEABLE.append(imported_module)
if hasattr(imported_module, "__stats__"):
STATS.append(imported_module)
if hasattr(imported_module, "__user_info__"):
USER_INFO.append(imported_module)
if hasattr(imported_module, "__import_data__"):
DATA_IMPORT.append(imported_module)
if hasattr(imported_module, "__export_data__"):
DATA_EXPORT.append(imported_module)
if hasattr(imported_module, "__chat_settings__"):
CHAT_SETTINGS[imported_module.__mod_name__.lower()] = imported_module
if hasattr(imported_module, "__user_settings__"):
USER_SETTINGS[imported_module.__mod_name__.lower()] = imported_module
# do not async
def send_help(chat_id, text, keyboard=None):
if not keyboard:
keyboard = InlineKeyboardMarkup(paginate_modules(0, HELPABLE, "help"))
dispatcher.bot.send_message(chat_id=chat_id,
text=text,
parse_mode=ParseMode.MARKDOWN,
reply_markup=keyboard)
@run_async
def test(bot: Bot, update: Update):
# pprint(eval(str(update)))
# update.effective_message.reply_text("Hola tester! _I_ *have* `markdown`", parse_mode=ParseMode.MARKDOWN)
update.effective_message.reply_text("This person edited a message")
print(update.effective_message)
@run_async
def start(bot: Bot, update: Update, args: List[str]):
if update.effective_chat.type == "private":
if len(args) >= 1:
if args[0].lower() == "help":
send_help(update.effective_chat.id, HELP_STRINGS)
elif args[0].lower() == "disasters":
IMPORTED["disasters"].send_disasters(update)
elif args[0].lower().startswith("stngs_"):
match = re.match("stngs_(.*)", args[0].lower())
chat = dispatcher.bot.getChat(match.group(1))
if is_user_admin(chat, update.effective_user.id):
send_settings(match.group(1), update.effective_user.id, False)
else:
send_settings(match.group(1), update.effective_user.id, True)
elif args[0][1:].isdigit() and "rules" in IMPORTED:
IMPORTED["rules"].send_rules(update, args[0], from_pm=True)
else:
first_name = update.effective_user.first_name
buttons = InlineKeyboardMarkup(
[[InlineKeyboardButton(text="Add Hitomi To Your Group", url="https://t.me/hitomi_robot?startgroup=new")],
[InlineKeyboardButton(text="Support Group 👥", url="https://t.me/Dark_cobra_support")],
[InlineKeyboardButton(text="Help And Commands ❔", callback_data="help_back")]])
update.effective_message.reply_photo(MEIKO_IMG,
PM_START_TEXT.format(escape_markdown(first_name), escape_markdown(bot.first_name), OWNER_ID),
parse_mode=ParseMode.MARKDOWN, reply_markup=buttons)
else:
update.effective_message.reply_text("Heya! Am Awake 😁")
def send_start(bot, update):
#Try to remove old message
try:
query = update.callback_query
query.message.delete()
except:
Pass
# for test purposes
def error_callback(bot, update, error):
try:
raise error
except Unauthorized:
print("no nono1")
print(error)
# remove update.message.chat_id from conversation list
except BadRequest:
print("no nono2")
print("BadRequest caught")
print(error)
# handle malformed requests - read more below!
except TimedOut:
print("no nono3")
# handle slow connection problems
except NetworkError:
print("no nono4")
# handle other connection problems
except ChatMigrated as err:
print("no nono5")
print(err)
# the chat_id of a group has changed, use e.new_chat_id instead
except TelegramError:
print(error)
# handle all other telegram related errors
@run_async
def help_button(bot: Bot, update: Update):
query = update.callback_query
mod_match = re.match(r"help_module\((.+?)\)", query.data)
prev_match = re.match(r"help_prev\((.+?)\)", query.data)
next_match = re.match(r"help_next\((.+?)\)", query.data)
back_match = re.match(r"help_back", query.data)
try:
if mod_match:
module = mod_match.group(1)
text = "Here is the help for the *{}* module:\n".format(HELPABLE[module].__mod_name__) \
+ HELPABLE[module].__help__
query.message.reply_text(text=text,
parse_mode=ParseMode.MARKDOWN,
reply_markup=InlineKeyboardMarkup(
[[InlineKeyboardButton(text="Back", callback_data="help_back")]]))
elif prev_match:
curr_page = int(prev_match.group(1))
query.message.reply_text(HELP_STRINGS,
parse_mode=ParseMode.MARKDOWN,
reply_markup=InlineKeyboardMarkup(
paginate_modules(curr_page - 1, HELPABLE, "help")))
elif next_match:
next_page = int(next_match.group(1))
query.message.reply_text(HELP_STRINGS,
parse_mode=ParseMode.MARKDOWN,
reply_markup=InlineKeyboardMarkup(
paginate_modules(next_page + 1, HELPABLE, "help")))
elif back_match:
query.message.reply_text(text=HELP_STRINGS,
parse_mode=ParseMode.MARKDOWN,
reply_markup=InlineKeyboardMarkup(paginate_modules(0, HELPABLE, "help")))
# ensure no spinny white circle
bot.answer_callback_query(query.id)
query.message.delete()
except BadRequest as excp:
if excp.message == "Message is not modified":
pass
elif excp.message == "Query_id_invalid":
pass
elif excp.message == "Message can't be deleted":
pass
else:
LOGGER.exception("Exception in help buttons. %s", str(query.data))
@run_async
def get_help(bot: Bot, update: Update):
chat = update.effective_chat # type: Optional[Chat]
args = update.effective_message.text.split(None, 1)
# ONLY send help in PM
if chat.type != chat.PRIVATE:
update.effective_message.reply_text("Contact me in PM to get the list of possible commands.",
reply_markup=InlineKeyboardMarkup(
[[InlineKeyboardButton(text="Help",
url="t.me/{}?start=help".format(
bot.username))]]))
return
elif len(args) >= 2 and any(args[1].lower() == x for x in HELPABLE):
module = args[1].lower()
text = "Here is the available help for the *{}* module:\n".format(HELPABLE[module].__mod_name__) \
+ HELPABLE[module].__help__
send_help(chat.id, text, InlineKeyboardMarkup([[InlineKeyboardButton(text="Back", callback_data="help_back")]]))
else:
send_help(chat.id, HELP_STRINGS)
def imdb_searchdata(bot: Bot, update: Update):
query_raw = update.callback_query
query = query_raw.data.split('$')
print(query)
if query[1] != query_raw.from_user.username:
return
title = ''
rating = ''
date = ''
synopsis = ''
url_sel = 'https://www.imdb.com/title/%s/' % (query[0])
text_sel = requests.get(url_sel).text
selector_global = Selector(text = text_sel)
title = selector_global.xpath('//div[@class="title_wrapper"]/h1/text()').get().strip()
try:
rating = selector_global.xpath('//div[@class="ratingValue"]/strong/span/text()').get().strip()
except:
rating = '-'
try:
date = '(' + selector_global.xpath('//div[@class="title_wrapper"]/h1/span/a/text()').getall()[-1].strip() + ')'
except:
date = selector_global.xpath('//div[@class="subtext"]/a/text()').getall()[-1].strip()
try:
synopsis_list = selector_global.xpath('//div[@class="summary_text"]/text()').getall()
synopsis = re.sub(' +',' ', re.sub(r'\([^)]*\)', '', ''.join(sentence.strip() for sentence in synopsis_list)))
except:
synopsis = '_No synopsis available._'
movie_data = '*%s*, _%s_\n★ *%s*\n\n%s' % (title, date, rating, synopsis)
query_raw.edit_message_text(
movie_data,
parse_mode=ParseMode.MARKDOWN
)
@run_async
def imdb(bot: Bot, update: Update, args):
message = update.effective_message
query = ''.join([arg + '_' for arg in args]).lower()
if not query:
bot.send_message(
message.chat.id,
'You need to specify a movie/show name!'
)
return
url_suggs = 'https://v2.sg.media-imdb.com/suggests/%s/%s.json' % (query[0], query)
json_url = urlopen(url_suggs)
suggs_raw = ''
for line in json_url:
suggs_raw = line
skip_chars = 6 + len(query)
suggs_dict = json.loads(suggs_raw[skip_chars:][:-1])
if suggs_dict:
button_list = [[
InlineKeyboardButton(
text = str(sugg['l'] + ' (' + str(sugg['y']) + ')'),
callback_data = str(sugg['id']) + '$' + str(message.from_user.username)
)] for sugg in suggs_dict['d'] if 'y' in sugg
]
reply_markup = InlineKeyboardMarkup(button_list)
bot.send_message(
message.chat.id,
'Which one? ',
reply_markup = reply_markup
)
else:
pass
def send_settings(chat_id, user_id, user=False):
if user:
if USER_SETTINGS:
settings = "\n\n".join(
"*{}*:\n{}".format(mod.__mod_name__, mod.__user_settings__(user_id)) for mod in USER_SETTINGS.values())
dispatcher.bot.send_message(user_id, "These are your current settings:" + "\n\n" + settings,
parse_mode=ParseMode.MARKDOWN)
else:
dispatcher.bot.send_message(user_id, "Seems like there aren't any user specific settings available :'(",
parse_mode=ParseMode.MARKDOWN)
else:
if CHAT_SETTINGS:
chat_name = dispatcher.bot.getChat(chat_id).title
dispatcher.bot.send_message(user_id,
text="Which module would you like to check {}'s settings for?".format(
chat_name),
reply_markup=InlineKeyboardMarkup(
paginate_modules(0, CHAT_SETTINGS, "stngs", chat=chat_id)))
else:
dispatcher.bot.send_message(user_id, "Seems like there aren't any chat settings available :'(\nSend this "
"in a group chat you're admin in to find its current settings!",
parse_mode=ParseMode.MARKDOWN)
@run_async
def settings_button(bot: Bot, update: Update):
query = update.callback_query
user = update.effective_user
mod_match = re.match(r"stngs_module\((.+?),(.+?)\)", query.data)
prev_match = re.match(r"stngs_prev\((.+?),(.+?)\)", query.data)
next_match = re.match(r"stngs_next\((.+?),(.+?)\)", query.data)
back_match = re.match(r"stngs_back\((.+?)\)", query.data)
try:
if mod_match:
chat_id = mod_match.group(1)
module = mod_match.group(2)
chat = bot.get_chat(chat_id)
text = "*{}* has the following settings for the *{}* module:\n\n".format(escape_markdown(chat.title),
CHAT_SETTINGS[module].__mod_name__) + \
CHAT_SETTINGS[module].__chat_settings__(chat_id, user.id)
query.message.reply_text(text=text,
parse_mode=ParseMode.MARKDOWN,
reply_markup=InlineKeyboardMarkup(
[[InlineKeyboardButton(text="Back",
callback_data="stngs_back({})".format(chat_id))]]))
elif prev_match:
chat_id = prev_match.group(1)
curr_page = int(prev_match.group(2))
chat = bot.get_chat(chat_id)
query.message.reply_text("Hi there! There are quite a few settings for {} - go ahead and pick what "
"you're interested in.".format(chat.title),
reply_markup=InlineKeyboardMarkup(
paginate_modules(curr_page - 1, CHAT_SETTINGS, "stngs",
chat=chat_id)))
elif next_match:
chat_id = next_match.group(1)
next_page = int(next_match.group(2))
chat = bot.get_chat(chat_id)
query.message.reply_text("Hi there! There are quite a few settings for {} - go ahead and pick what "
"you're interested in.".format(chat.title),
reply_markup=InlineKeyboardMarkup(
paginate_modules(next_page + 1, CHAT_SETTINGS, "stngs",
chat=chat_id)))
elif back_match:
chat_id = back_match.group(1)
chat = bot.get_chat(chat_id)
query.message.reply_text(text="Hi there! There are quite a few settings for {} - go ahead and pick what "
"you're interested in.".format(escape_markdown(chat.title)),
parse_mode=ParseMode.MARKDOWN,
reply_markup=InlineKeyboardMarkup(paginate_modules(0, CHAT_SETTINGS, "stngs",
chat=chat_id)))
# ensure no spinny white circle
bot.answer_callback_query(query.id)
query.message.delete()
except BadRequest as excp:
if excp.message == "Message is not modified":
pass
elif excp.message == "Query_id_invalid":
pass
elif excp.message == "Message can't be deleted":
pass
else:
LOGGER.exception("Exception in settings buttons. %s", str(query.data))
@run_async
def get_settings(bot: Bot, update: Update):
chat = update.effective_chat # type: Optional[Chat]
user = update.effective_user # type: Optional[User]
msg = update.effective_message # type: Optional[Message]
args = msg.text.split(None, 1)
# ONLY send settings in PM
if chat.type != chat.PRIVATE:
if is_user_admin(chat, user.id):
text = "Click here to get this chat's settings, as well as yours."
msg.reply_text(text,
reply_markup=InlineKeyboardMarkup(
[[InlineKeyboardButton(text="Settings",
url="t.me/{}?start=stngs_{}".format(
bot.username, chat.id))]]))
else:
text = "Click here to check your settings."
else:
send_settings(chat.id, user.id, True)
def migrate_chats(bot: Bot, update: Update):
msg = update.effective_message # type: Optional[Message]
if msg.migrate_to_chat_id:
old_chat = update.effective_chat.id
new_chat = msg.migrate_to_chat_id
elif msg.migrate_from_chat_id:
old_chat = msg.migrate_from_chat_id
new_chat = update.effective_chat.id
else:
return
LOGGER.info("Migrating from %s, to %s", str(old_chat), str(new_chat))
for mod in MIGRATEABLE:
mod.__migrate__(old_chat, new_chat)
LOGGER.info("Successfully migrated!")
raise DispatcherHandlerStop
@run_async
def donate(bot: Bot, update: Update):
user = update.effective_message.from_user
chat = update.effective_chat # type: Optional[Chat]
if chat.type == "private":
keyboard = [[InlineKeyboardButton(text="Paytm",url="https://paytm.me/d-tXs3H"),InlineKeyboardButton(text="PayPal",url="http://Paypal.me/MrSammy07")]]
keyboard += [[InlineKeyboardButton(text="For Other modes",url="https://t.me/MrSemmy")]]
update.effective_message.reply_text(DONATE_STRING, reply_markup=InlineKeyboardMarkup(keyboard),parse_mode=ParseMode.MARKDOWN)
else:
try:
bot.send_message(user.id, DONATE_STRING, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True)
update.effective_message.reply_text("I've PM'ed you about donating to my creator!")
except Unauthorized:
update.effective_message.reply_text("Contact me in PM first to get donation information.")
def main():
test_handler = CommandHandler("test", test)
start_handler = CommandHandler("start", start, pass_args=True)
start_callback_handler = CallbackQueryHandler(send_start, pattern=r"bot_start")
help_handler = CommandHandler("help", get_help)
help_callback_handler = CallbackQueryHandler(help_button, pattern=r"help_")
IMDB_HANDLER = CommandHandler("imdb", imdb, pass_args=True)
IMDB_SEARCHDATA_HANDLER = CallbackQueryHandler(imdb_searchdata)
settings_handler = CommandHandler("settings", get_settings)
settings_callback_handler = CallbackQueryHandler(settings_button, pattern=r"stngs_")
donate_handler = CommandHandler("donate", donate)
migrate_handler = MessageHandler(Filters.status_update.migrate, migrate_chats)
# dispatcher.add_handler(test_handler)
dispatcher.add_handler(start_handler)
dispatcher.add_handler(help_handler)
dispatcher.add_handler(settings_handler)
dispatcher.add_handler(help_callback_handler)
dispatcher.add_handler(settings_callback_handler)
dispatcher.add_handler(migrate_handler)
dispatcher.add_handler(start_callback_handler)
dispatcher.add_handler(IMDB_HANDLER)
dispatcher.add_handler(IMDB_SEARCHDATA_HANDLER)
dispatcher.add_handler(donate_handler)
# dispatcher.add_error_handler(error_callback)
if WEBHOOK:
LOGGER.info("Using webhooks.")
updater.start_webhook(listen="127.0.0.1",
port=PORT,
url_path=TOKEN)
if CERT_PATH:
updater.bot.set_webhook(url=URL + TOKEN,
certificate=open(CERT_PATH, 'rb'))
else:
updater.bot.set_webhook(url=URL + TOKEN)
else:
LOGGER.info("Using long polling.")
updater.start_polling(timeout=15, read_latency=4)
updater.idle()
if __name__ == '__main__':
LOGGER.info("Successfully loaded modules: " + str(ALL_MODULES))
main()