-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbotutils.py
More file actions
61 lines (49 loc) · 1.71 KB
/
botutils.py
File metadata and controls
61 lines (49 loc) · 1.71 KB
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
import logging
from functools import wraps
from telegram.ext import Updater
from telegram.ext import CallbackContext
from telegram.ext import CommandHandler
from telegram.ext import MessageHandler, Filters
from telegram import Update
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',level=logging.INFO)
msg_handlers = {}
cmd_handlers = {}
def MSG(func):
name = func.__name__
if name in msg_handlers.keys():
raise Exception(f'function {name} alreay exists.')
else:
msg_handlers[name] = func
@wraps(func)
def decorated(*args, **kwargs):
return func(*args, **kwargs)
return decorated
def CMD(func):
name = func.__name__
if name in cmd_handlers.keys():
raise Exception(f'function {name} alreay exists.')
else:
cmd_handlers[name] = func
@wraps(func)
def decorated(*args, **kwargs):
return func(*args, **kwargs)
return decorated
@CMD
def help(update: Update, context: CallbackContext):
msg = 'all cmds:\n'
for key in cmd_handlers.keys():
msg = msg + '/' + key + '\n'
context.bot.send_message(chat_id=update.effective_chat.id, text=msg)
def text_dispatcher(update:Update, context:CallbackContext):
for key in msg_handlers.keys():
msg_handlers[key](update, context)
def start_bot(token:str):
updater = Updater(token=token, use_context=True)
dispatcher = updater.dispatcher
text_handler = MessageHandler(Filters.text & (~Filters.command), text_dispatcher)
dispatcher.add_handler(text_handler)
for key in cmd_handlers.keys():
handler = CommandHandler(key, cmd_handlers[key])
dispatcher.add_handler(handler)
updater.start_polling()
updater.idle()