-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path__main__.py
295 lines (227 loc) · 8.19 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
"""
Main Bot Code
"""
# TODO: Better Stub's
from collections.abc import Callable
from typing import Any, Optional
import importlib.util
import importlib
import os.path
import logging
import asyncio
import json
import uvloop
import click
from pyrogram.client import Client
from pyrogram.sync import idle
from pytgcalls import PyTgCalls
from dotenv import load_dotenv
from stub import (
MetaClient, MetaModule, MainException,
SettingsCollision, InvalidSettings
)
class MainClient(MetaClient):
userbot: Client
api: PyTgCalls
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.modules: dict[str, MetaModule] = {}
self.config: dict[str, Any] = {}
self.defby: dict[str, MetaModule] = {}
def require_configuration(
self, module: MetaModule | MetaClient,
config: str
) -> None:
if config not in self.config:
raise InvalidSettings(
f'Settings key `{config}` is not defined ' +
f'(and it\'s required by {module.identifier})')
def register_configuration(
self, module: MetaModule | MetaClient,
config: dict[str, dict[str, str]],
check_collisions: bool = True
) -> None:
for k, v in config.items():
if k not in self.config:
self.config[k] = v
self.defby[k] = module
elif check_collisions:
if k in self.defby and self.defby[k] != module:
raise SettingsCollision(
f'Configuration `{k}` is already used by module ' +
f'`{self.defby[k].identifier}` ' +
f'(requested by module `{module.identifier}`)'
)
self.defby[k] = module
def require_modules(
self, modules: tuple[str]
) -> tuple[MetaModule]:
output: list[MetaModule] = []
for module in modules:
if module not in self.modules:
raise MainException(
'There is no module with the '
f'identifier `{module}` installed'
)
output.append(self.modules[module])
return tuple(output)
async def _setup() -> MainClient:
load_dotenv()
envars: dict[str, str] = {}
for var in ['CLIENT_NAME', 'TG_API_ID', 'TG_API_HASH']:
if var not in os.environ:
raise MainException(
f'Unset `{var}` environmental variable'
' is required for startup (it is not in .env)'
)
envars[var] = os.environ[var]
if os.getenv('DEBUG', ''):
logging.basicConfig(level=logging.DEBUG)
config: dict[str, Any] = {}
if os.path.isfile('settings.json'):
with open('settings.json', encoding='utf-8') as cfg:
config.update(json.load(cfg))
bot: MainClient = MainClient(
api_id=envars['TG_API_ID'],
api_hash=envars['TG_API_HASH'],
name=envars['CLIENT_NAME'])
bot.userbot = Client(
api_id=envars['TG_API_ID'],
api_hash=envars['TG_API_HASH'],
name=envars['CLIENT_NAME'] + '_userbot')
bot.api = PyTgCalls(bot.userbot)
bot.api.mainbot = bot
bot.config.update(config)
bot.require_configuration(bot, 'BaseModules')
for mod in bot.config['BaseModules']:
module: MetaModule = importlib \
.import_module(mod) \
.Module(bot)
if module.identifier in bot.modules:
raise MainException(
f'Module `{module.identifier}` has two options ' +
f'({type(bot.modules[module.identifier]).__module__}' +
f' and {mod})'
)
bot.modules[module.identifier] = module
return bot
@click.group()
def cli():
pass
async def async_run(
setup_mode: bool = False,
debug_mode: bool = False
) -> None:
bot: MainClient = await _setup()
bot.debug = debug_mode
for v in bot.modules.values():
logging.debug(
'Installing `%s` module', v.identifier)
await v.install()
logging.info('Installed modules!')
if setup_mode:
for v in bot.modules.values():
logging.debug('Setting up `%s` module', v.identifier)
await v.setup()
logging.info('Setted up all modules!')
return
for v in bot.modules.values():
logging.debug(
'Running post-install of module `%s`', v.identifier)
await v.post_install()
logging.info('Ran `post-install` method of every module')
logging.info('Starting bot')
await bot.start()
logging.info('Starting userbot')
await bot.api.start()
logging.info('Idling')
await idle()
@cli.command()
@click.option(
'--setup', '-s', 'setup_mode',
is_flag=True)
@click.option(
'--debug', '-d', 'debug_mode',
is_flag=True)
def run(setup_mode: bool, debug_mode: bool):
asyncio.run(async_run(setup_mode, debug_mode))
async def async_test() -> None:
bot: MainClient = await _setup()
bot.require_configuration(bot, 'tests')
for v in bot.modules.values():
logging.debug('Installing `%s` module', v.identifier)
await v.install()
tests: dict[str, dict[str, list[Callable]]] = {}
for k in bot.modules.keys():
tests[k] = {}
for testmod in bot.config['tests']:
spec: Any = importlib.util.spec_from_file_location(
os.path.normpath(testmod).replace('/', '.'),
testmod)
mod: Any = spec.loader.load_module()
tmod: str = mod.test_module
if tmod not in tests:
continue
steps: dict[str, Callable] = mod.steps
for step, cbl in steps.items():
if step not in tests[tmod]:
tests[tmod][step] = [cbl]
else:
tests[tmod][step].append(cbl)
for mod, tdata in tests.items():
if 'install' in tdata:
module: MetaModule = bot.modules[mod]
identifier: str = module.identifier
logging.info('Running test_install of `%s` module (0/%d)',
identifier, len(tdata['install']))
no: int = 1
for cbl in tdata['install']:
resp: Optional[Exception] = await cbl(module)
if resp:
logging.debug('Raising exception from test_install of `%s`',
identifier)
raise resp
logging.info('Running test_install of `%s` module (%d/%d)',
identifier, no, len(tdata['install']))
no += 1
for v in bot.modules.values():
logging.debug('Running post-install of `%s` module', v.identifier)
await v.post_install()
for mod, tdata in tests.items():
if 'post_install' in tdata:
module: MetaModule = bot.modules[mod]
identifier: str = module.identifier
logging.info('Running test_post_install of `%s` module (0/%d)',
identifier, len(tdata['post_install']))
no: int = 1
for cbl in tdata['post_install']:
resp: Optional[Exception] = await cbl(module)
if resp:
logging.debug('Raising exception from test_post_install of `%s`',
identifier)
raise resp
logging.info('Running test_post_install of `%s` module (%d/%d)',
identifier, no, len(tdata['post_install']))
no += 1
@cli.command()
def test() -> None:
asyncio.run(async_test())
async def async_stub():
bot: MainClient = await _setup()
logging.info('Starting to generate stub\'s')
root: dict[str, Any] = {}
for mod in bot.config['BaseModules']:
module: MetaModule = importlib.import_module(mod).Module(bot)
if hasattr(module, 'stub'):
logging.info('Generating stub for module `%s`', mod)
module.stub(root)
stubpy: str = importlib.import_module('stubgen').generate(root)
with open('stub.py', 'w', encoding='utf-8') as st:
st.write(stubpy + '\n')
logging.info('`stub.py` generated correctly')
@cli.command()
def stub():
asyncio.run(async_stub())
if __name__ == '__main__':
uvloop.install()
cli()