-
Notifications
You must be signed in to change notification settings - Fork 0
/
bot.py
221 lines (191 loc) · 6.86 KB
/
bot.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
import importlib
import multiprocessing
import os
import shutil
import sys
import traceback
from datetime import datetime
from time import sleep
from loguru import logger as loggerFallback
ascii_art = r'''
_ _ ____ _
/\ | | (_) | _ \ | |
/ \ | | ____ _ _ __ _ | |_) | ___ | |_
/ /\ \ | |/ / _` | '__| | | _ < / _ \| __|
/ ____ \| < (_| | | | | | |_) | (_) | |_
/_/ \_\_|\_\__,_|_| |_| |____/ \___/ \__|
'''
encode = 'UTF-8'
bots_and_required_configs = {
'aiocqhttp': [
'qq_host',
'qq_account'],
'discord': ['discord_token'],
'aiogram': ['telegram_token'],
'kook': ['kook_token'],
'matrix': [
'matrix_homeserver',
'matrix_user',
'matrix_device_id',
'matrix_token'],
'qqbot': [
'qq_bot_appid',
'qq_bot_secret'],
}
class RestartBot(Exception):
pass
failed_to_start_attempts = {}
disabled_bots = []
processes = []
def init_bot():
import core.scripts.config_generate # noqa
from core.config import Config, CFGManager # noqa
from core.constants.default import base_superuser_default # noqa
from core.database import BotDBUtil, session, DBVersion # noqa
from core.logger import Logger # noqa
query_dbver = session.query(DBVersion).first()
if not query_dbver:
session.add_all([DBVersion(value=str(BotDBUtil.database_version))])
session.commit()
query_dbver = session.query(DBVersion).first()
if (current_ver := int(query_dbver.value)) < (target_ver := BotDBUtil.database_version):
Logger.info(f'Updating database from {current_ver} to {target_ver}...')
from core.database.update import update_database
update_database()
Logger.info('Database updated successfully!')
print(ascii_art)
base_superuser = Config('base_superuser', base_superuser_default, cfg_type=(str, list))
if base_superuser:
if isinstance(base_superuser, str):
base_superuser = [base_superuser]
for bu in base_superuser:
BotDBUtil.SenderInfo(bu).init()
BotDBUtil.SenderInfo(bu).edit('isSuperUser', True)
else:
Logger.warning("The base superuser was not found, please setup it in the config file.")
disabled_bots.clear()
for t in CFGManager.values:
if t.startswith('bot_') and not t.endswith('_secret'):
if 'enable' in CFGManager.values[t][t]:
if not CFGManager.values[t][t]['enable']:
disabled_bots.append(t[4:])
def multiprocess_run_until_complete(func):
p = multiprocessing.Process(
target=func,)
p.start()
while True:
if not p.is_alive():
break
sleep(1)
p.terminate()
p.join()
p.close()
def go(bot_name: str = None, subprocess: bool = False, binary_mode: bool = False):
from core.logger import Logger # noqa
from core.utils.info import Info # noqa
Logger.info(f"[{bot_name}] Here we go!")
Info.subprocess = subprocess
Info.binary_mode = binary_mode
Logger.rename(bot_name)
try:
importlib.import_module(f"bots.{bot_name}.bot")
except ModuleNotFoundError:
Logger.error(f"[{bot_name}] ???, entry not found.")
sys.exit(1)
def run_bot():
from core.constants.path import cache_path # noqa
from core.config import Config # noqa
from core.logger import Logger # noqa
def restart_process(bot_name: str):
if bot_name not in failed_to_start_attempts or datetime.now(
).timestamp() - failed_to_start_attempts[bot_name]['timestamp'] > 60:
failed_to_start_attempts[bot_name] = {}
failed_to_start_attempts[bot_name]['count'] = 0
failed_to_start_attempts[bot_name]['timestamp'] = datetime.now().timestamp()
failed_to_start_attempts[bot_name]['count'] += 1
failed_to_start_attempts[bot_name]['timestamp'] = datetime.now().timestamp()
if failed_to_start_attempts[bot_name]['count'] >= 3:
Logger.error(f'Bot {bot_name} failed to start 3 times, abort to restart, please check the log.')
return
Logger.warning(f'Restarting bot {bot_name}...')
p = multiprocessing.Process(
target=go,
args=(
bot_name,
True,
bool(not sys.argv[0].endswith('.py'))),
name=bot_name)
p.start()
processes.append(p)
if os.path.exists(cache_path):
shutil.rmtree(cache_path)
os.makedirs(cache_path, exist_ok=True)
envs = os.environ.copy()
envs['PYTHONIOENCODING'] = 'UTF-8'
envs['PYTHONPATH'] = os.path.abspath('.')
lst = bots_and_required_configs.keys()
for bl in lst:
if bl in disabled_bots:
continue
if bl in bots_and_required_configs:
abort = False
for c in bots_and_required_configs[bl]:
if not Config(c, _global=True):
Logger.error(f'Bot {bl} requires config {c} but not found, abort to launch.')
abort = True
break
if abort:
continue
p = multiprocessing.Process(
target=go,
args=(
bl,
True,
bool(not sys.argv[0].endswith('.py'))),
name=bl)
p.start()
processes.append(p)
while True:
for p in processes:
if p.is_alive():
continue
else:
if p.exitcode == 233:
Logger.warning(f'{p.pid} ({p.name}) exited with code 233, restart all bots.')
raise RestartBot
else:
Logger.critical(f'Process {p.pid} ({p.name}) exited with code {p.exitcode}, please check the log.')
processes.remove(p)
p.terminate()
p.join()
p.close()
restart_process(p.name)
break
if not processes:
break
sleep(1)
Logger.critical('All bots exited unexpectedly, please check the output.')
if __name__ == '__main__':
try:
while True:
try:
multiprocess_run_until_complete(init_bot)
run_bot() # Process will block here so
break
except RestartBot:
for ps in processes:
ps.terminate()
ps.join()
ps.close()
processes.clear()
continue
except Exception:
loggerFallback.critical('An error occurred, please check the output.')
traceback.print_exc()
break
except (KeyboardInterrupt, SystemExit):
for ps in processes:
ps.terminate()
ps.join()
ps.close()
processes.clear()