-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathheinz_bot.py
More file actions
151 lines (114 loc) · 4.7 KB
/
heinz_bot.py
File metadata and controls
151 lines (114 loc) · 4.7 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
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
import inspect
import logging
import os
import time
from _thread import start_new_thread
from logging.handlers import TimedRotatingFileHandler
from pathlib import Path
from repository.database import Database
import schedule
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, InlineQueryHandler, Dispatcher, \
CallbackQueryHandler
from modules.job_register_bot import register_methods_in_file, send_awake_to_subscriber
from modules.remind_me_bot import schedule_remind_me_jobs_from_db
from utils.api_key_reader import read_key
BOT_LOGGER = 'BotLogger'
def load_modules(dp):
modules = os.listdir(os.path.dirname("modules/"))
modules = list(filter(lambda x: x[-3:] == ".py", modules))
for module in modules:
load_module(module, dp)
def load_module(name, dp: Dispatcher):
# [:-3] in order to remove the .py ending
name = name[:-3]
path = "modules." + name
imported = __import__(name=path)
module = getattr(imported, name)
# Load all classes inside a module
classes = inspect.getmembers(module, inspect.isclass)
clazz_name = None
# pick the class that is inside the module and not imported
for (name, clazz) in classes:
if clazz.__module__ == path:
clazz_name = name
break
if clazz_name is None:
return
# create class instance
clazz = getattr(module, clazz_name)
if hasattr(clazz, "_active"):
if clazz._active is not True:
return
else:
return
inst = clazz()
methods = inspect.getmembers(inst, predicate=inspect.ismethod)
run_daily_methods = list(filter(lambda x: hasattr(x[1], "_daily_run_time_decorator") and
hasattr(x[1], "_daily_run_name_decorator"), methods))
if len(run_daily_methods) > 0:
register_methods_in_file(run_daily_methods, dp)
for (key, method) in methods:
if hasattr(method, "_command") and hasattr(method, "_short_desc") and \
hasattr(method, "_long_desc") and hasattr(method, "_usage"):
register_command_handler(dp, method, inst)
if hasattr(method, "_filter"):
register_message_watcher(dp, method)
if hasattr(method, "_isInline"):
register_inline_cap(dp, method)
if hasattr(method, "_forCommand"):
register_callback_query(dp, method)
if hasattr(method, "_forScheduler"):
method()
def register_command_handler(dp: Dispatcher, method, inst):
dp.add_handler(CommandHandler(method._command, method), group=1)
help_text_func = getattr(inst, "add_help_text")
help_text_func(method._command, method._short_desc, method._long_desc, method._usage)
def register_message_watcher(dp: Dispatcher, method):
dp.add_handler(MessageHandler(Filters.command, method), group=0)
def register_message_watcher(dp: Dispatcher, method):
dp.add_handler(MessageHandler(Filters.command, method), group=0)
def register_inline_cap(dp: Dispatcher, method):
dp.add_handler(InlineQueryHandler(method), group=0)
def register_callback_query(dp: Dispatcher, method):
if method._isMaster:
dp.add_handler(CallbackQueryHandler(method), group=2)
else:
dp.add_handler(CallbackQueryHandler(method, pattern=method._forCommand), group=3)
def enable_logging():
Path("./log").mkdir(parents=True, exist_ok=True)
log_name = './log/heinz.log'
bot_logger = logging.getLogger(BOT_LOGGER)
bot_logger.setLevel(logging.INFO)
handler = TimedRotatingFileHandler(log_name, when="midnight", interval=1)
formatter = logging.Formatter('%(asctime)s - %(levelname)5s - %(message)s')
handler.setFormatter(formatter)
handler.suffix = "%Y%m%d"
bot_logger.addHandler(handler)
bot_logger.log(msg="Started logging", level=logging.INFO)
# root = logging.getLogger()
# root.setLevel(logging.DEBUG)
#
# handler = logging.StreamHandler(sys.stdout)
# handler.setLevel(logging.DEBUG)
# formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
# handler.setFormatter(formatter)
# root.addHandler(handler)
# Runs schedules besides from the telegram bot
def run_schedules():
while True:
schedule.run_pending()
time.sleep(3)
def main():
enable_logging()
start_new_thread(run_schedules, ())
updater = Updater(read_key("telegram"), use_context=True)
dp = updater.dispatcher
load_modules(dp)
send_awake_to_subscriber(dp)
schedule_remind_me_jobs_from_db(dp)
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
updater.start_polling()
if __name__ == '__main__':
Database.instance()
main()