loader.py 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504
  1. """Registers modules"""
  2. # █ █ ▀ █▄▀ ▄▀█ █▀█ ▀
  3. # █▀█ █ █ █ █▀█ █▀▄ █
  4. # © Copyright 2022
  5. # https://t.me/hikariatama
  6. #
  7. # 🔒 Licensed under the GNU AGPLv3
  8. # 🌐 https://www.gnu.org/licenses/agpl-3.0.html
  9. import asyncio
  10. import contextlib
  11. import inspect
  12. import logging
  13. import os
  14. import re
  15. import sys
  16. import requests
  17. import copy
  18. import importlib
  19. import importlib.util
  20. import importlib.machinery
  21. from functools import partial, wraps
  22. from telethon.tl.types import Message, InputPeerNotifySettings, Channel
  23. from telethon.tl.functions.account import UpdateNotifySettingsRequest
  24. from telethon.hints import EntityLike
  25. from types import FunctionType
  26. import typing
  27. from . import security, utils, validators, version
  28. from .types import (
  29. ConfigValue, # skipcq
  30. LoadError,
  31. Module,
  32. Library,
  33. ModuleConfig, # skipcq
  34. LibraryConfig,
  35. SelfUnload,
  36. SelfSuspend,
  37. StopLoop,
  38. InlineMessage,
  39. CoreOverwriteError,
  40. CoreUnloadError,
  41. StringLoader,
  42. get_commands,
  43. get_inline_handlers,
  44. JSONSerializable,
  45. )
  46. from .inline.core import InlineManager
  47. from .inline.types import InlineCall
  48. from .translations import Strings, Translator
  49. from .database import Database
  50. import gc as _gc
  51. import types as _types
  52. logger = logging.getLogger(__name__)
  53. owner = security.owner
  54. sudo = security.sudo
  55. support = security.support
  56. group_owner = security.group_owner
  57. group_admin_add_admins = security.group_admin_add_admins
  58. group_admin_change_info = security.group_admin_change_info
  59. group_admin_ban_users = security.group_admin_ban_users
  60. group_admin_delete_messages = security.group_admin_delete_messages
  61. group_admin_pin_messages = security.group_admin_pin_messages
  62. group_admin_invite_users = security.group_admin_invite_users
  63. group_admin = security.group_admin
  64. group_member = security.group_member
  65. pm = security.pm
  66. unrestricted = security.unrestricted
  67. inline_everyone = security.inline_everyone
  68. def proxy0(data):
  69. def proxy1():
  70. return data
  71. return proxy1
  72. _CELLTYPE = type(proxy0(None).__closure__[0])
  73. def replace_all_refs(replace_from: typing.Any, replace_to: typing.Any) -> typing.Any:
  74. """
  75. :summary: Uses the :mod:`gc` module to replace all references to obj
  76. :attr:`replace_from` with :attr:`replace_to` (it tries it's best,
  77. anyway).
  78. :param replace_from: The obj you want to replace.
  79. :param replace_to: The new objject you want in place of the old one.
  80. :returns: The replace_from
  81. """
  82. # https://github.com/cart0113/pyjack/blob/dd1f9b70b71f48335d72f53ee0264cf70dbf4e28/pyjack.py
  83. _gc.collect()
  84. hit = False
  85. for referrer in _gc.get_referrers(replace_from):
  86. # FRAMES -- PASS THEM UP
  87. if isinstance(referrer, _types.FrameType):
  88. continue
  89. # DICTS
  90. if isinstance(referrer, dict):
  91. cls = None
  92. # THIS CODE HERE IS TO DEAL WITH DICTPROXY TYPES
  93. if "__dict__" in referrer and "__weakref__" in referrer:
  94. for cls in _gc.get_referrers(referrer):
  95. if inspect.isclass(cls) and cls.__dict__ == referrer:
  96. break
  97. for key, value in referrer.items():
  98. # REMEMBER TO REPLACE VALUES ...
  99. if value is replace_from:
  100. hit = True
  101. value = replace_to
  102. referrer[key] = value
  103. if cls: # AGAIN, CLEANUP DICTPROXY PROBLEM
  104. setattr(cls, key, replace_to)
  105. # AND KEYS.
  106. if key is replace_from:
  107. hit = True
  108. del referrer[key]
  109. referrer[replace_to] = value
  110. elif isinstance(referrer, list):
  111. for i, value in enumerate(referrer):
  112. if value is replace_from:
  113. hit = True
  114. referrer[i] = replace_to
  115. elif isinstance(referrer, set):
  116. referrer.remove(replace_from)
  117. referrer.add(replace_to)
  118. hit = True
  119. elif isinstance(
  120. referrer,
  121. (
  122. tuple,
  123. frozenset,
  124. ),
  125. ):
  126. new_tuple = []
  127. for obj in referrer:
  128. if obj is replace_from:
  129. new_tuple.append(replace_to)
  130. else:
  131. new_tuple.append(obj)
  132. replace_all_refs(referrer, type(referrer)(new_tuple))
  133. elif isinstance(referrer, _CELLTYPE):
  134. def _proxy0(data):
  135. def proxy1():
  136. return data
  137. return proxy1
  138. proxy = _proxy0(replace_to)
  139. newcell = proxy.__closure__[0]
  140. replace_all_refs(referrer, newcell)
  141. elif isinstance(referrer, _types.FunctionType):
  142. localsmap = {}
  143. for key in ["code", "globals", "name", "defaults", "closure"]:
  144. orgattr = getattr(referrer, f"__{key}__")
  145. localsmap[key] = replace_to if orgattr is replace_from else orgattr
  146. localsmap["argdefs"] = localsmap["defaults"]
  147. del localsmap["defaults"]
  148. newfn = _types.FunctionType(**localsmap)
  149. replace_all_refs(referrer, newfn)
  150. else:
  151. logger.debug("%s is not supported.", referrer)
  152. if hit is False:
  153. raise AttributeError(f"Object '{replace_from}' not found")
  154. return replace_from
  155. async def stop_placeholder() -> bool:
  156. return True
  157. class Placeholder:
  158. """Placeholder"""
  159. VALID_PIP_PACKAGES = re.compile(
  160. r"^\s*# ?requires:(?: ?)((?:{url} )*(?:{url}))\s*$".format(
  161. url=r"[-[\]_.~:/?#@!$&'()*+,;%<=>a-zA-Z0-9]+"
  162. ),
  163. re.MULTILINE,
  164. )
  165. USER_INSTALL = "PIP_TARGET" not in os.environ and "VIRTUAL_ENV" not in os.environ
  166. class InfiniteLoop:
  167. _task = None
  168. status = False
  169. module_instance = None # Will be passed later
  170. def __init__(
  171. self,
  172. func: FunctionType,
  173. interval: int,
  174. autostart: bool,
  175. wait_before: bool,
  176. stop_clause: typing.Union[str, None],
  177. ):
  178. self.func = func
  179. self.interval = interval
  180. self._wait_before = wait_before
  181. self._stop_clause = stop_clause
  182. self.autostart = autostart
  183. def _stop(self, *args, **kwargs):
  184. self._wait_for_stop.set()
  185. def stop(self, *args, **kwargs):
  186. with contextlib.suppress(AttributeError):
  187. _hikka_client_id_logging_tag = copy.copy(
  188. self.module_instance.allmodules.client.tg_id
  189. )
  190. if self._task:
  191. logger.debug("Stopped loop for method %s", self.func)
  192. self._wait_for_stop = asyncio.Event()
  193. self.status = False
  194. self._task.add_done_callback(self._stop)
  195. self._task.cancel()
  196. return asyncio.ensure_future(self._wait_for_stop.wait())
  197. logger.debug("Loop is not running")
  198. return asyncio.ensure_future(stop_placeholder())
  199. def start(self, *args, **kwargs):
  200. with contextlib.suppress(AttributeError):
  201. _hikka_client_id_logging_tag = copy.copy(
  202. self.module_instance.allmodules.client.tg_id
  203. )
  204. if not self._task:
  205. logger.debug("Started loop for method %s", self.func)
  206. self._task = asyncio.ensure_future(self.actual_loop(*args, **kwargs))
  207. else:
  208. logger.debug("Attempted to start already running loop")
  209. async def actual_loop(self, *args, **kwargs):
  210. # Wait for loader to set attribute
  211. while not self.module_instance:
  212. await asyncio.sleep(0.01)
  213. if isinstance(self._stop_clause, str) and self._stop_clause:
  214. self.module_instance.set(self._stop_clause, True)
  215. self.status = True
  216. while self.status:
  217. if self._wait_before:
  218. await asyncio.sleep(self.interval)
  219. if (
  220. isinstance(self._stop_clause, str)
  221. and self._stop_clause
  222. and not self.module_instance.get(self._stop_clause, False)
  223. ):
  224. break
  225. try:
  226. await self.func(self.module_instance, *args, **kwargs)
  227. except StopLoop:
  228. break
  229. except Exception:
  230. logger.exception("Error running loop!")
  231. if not self._wait_before:
  232. await asyncio.sleep(self.interval)
  233. self._wait_for_stop.set()
  234. self.status = False
  235. def __del__(self):
  236. self.stop()
  237. def loop(
  238. interval: int = 5,
  239. autostart: typing.Optional[bool] = False,
  240. wait_before: typing.Optional[bool] = False,
  241. stop_clause: typing.Optional[str] = None,
  242. ) -> FunctionType:
  243. """
  244. Create new infinite loop from class method
  245. :param interval: Loop iterations delay
  246. :param autostart: Start loop once module is loaded
  247. :param wait_before: Insert delay before actual iteration, rather than after
  248. :param stop_clause: Database key, based on which the loop will run.
  249. This key will be set to `True` once loop is started,
  250. and will stop after key resets to `False`
  251. :attr status: Boolean, describing whether the loop is running
  252. """
  253. def wrapped(func):
  254. return InfiniteLoop(func, interval, autostart, wait_before, stop_clause)
  255. return wrapped
  256. MODULES_NAME = "modules"
  257. ru_keys = 'ёйцукенгшщзхъфывапролджэячсмитьбю.Ё"№;%:?ЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭ/ЯЧСМИТЬБЮ,'
  258. en_keys = "`qwertyuiop[]asdfghjkl;'zxcvbnm,./~@#$%^&QWERTYUIOP{}ASDFGHJKL:\"|ZXCVBNM<>?"
  259. BASE_DIR = (
  260. os.path.normpath(os.path.join(utils.get_base_dir(), ".."))
  261. if "OKTETO" not in os.environ and "DOCKER" not in os.environ
  262. else "/data"
  263. )
  264. LOADED_MODULES_DIR = os.path.join(BASE_DIR, "loaded_modules")
  265. if not os.path.isdir(LOADED_MODULES_DIR):
  266. os.mkdir(LOADED_MODULES_DIR, mode=0o755)
  267. def translatable_docstring(cls):
  268. """Decorator that makes triple-quote docstrings translatable"""
  269. @wraps(cls.config_complete)
  270. def config_complete(self, *args, **kwargs):
  271. def proccess_decorators(mark: str, obj: str):
  272. nonlocal self
  273. for attr in dir(func_):
  274. if (
  275. attr.endswith("_doc")
  276. and len(attr) == 6
  277. and isinstance(getattr(func_, attr), str)
  278. ):
  279. var = f"strings_{attr.split('_')[0]}"
  280. if not hasattr(self, var):
  281. setattr(self, var, {})
  282. getattr(self, var).setdefault(f"{mark}{obj}", getattr(func_, attr))
  283. for command_, func_ in get_commands(cls).items():
  284. proccess_decorators("_cmd_doc_", command_)
  285. try:
  286. func_.__doc__ = self.strings[f"_cmd_doc_{command_}"]
  287. except AttributeError:
  288. func_.__func__.__doc__ = self.strings[f"_cmd_doc_{command_}"]
  289. for inline_handler_, func_ in get_inline_handlers(cls).items():
  290. proccess_decorators("_ihandle_doc_", inline_handler_)
  291. try:
  292. func_.__doc__ = self.strings[f"_ihandle_doc_{inline_handler_}"]
  293. except AttributeError:
  294. func_.__func__.__doc__ = self.strings[f"_ihandle_doc_{inline_handler_}"]
  295. self.__doc__ = self.strings["_cls_doc"]
  296. return self.config_complete._old_(self, *args, **kwargs)
  297. config_complete._old_ = cls.config_complete
  298. cls.config_complete = config_complete
  299. for command_, func in get_commands(cls).items():
  300. cls.strings[f"_cmd_doc_{command_}"] = inspect.getdoc(func)
  301. for inline_handler_, func in get_inline_handlers(cls).items():
  302. cls.strings[f"_ihandle_doc_{inline_handler_}"] = inspect.getdoc(func)
  303. cls.strings["_cls_doc"] = inspect.getdoc(cls)
  304. return cls
  305. tds = translatable_docstring # Shorter name for modules to use
  306. def ratelimit(func: callable):
  307. """Decorator that causes ratelimiting for this command to be enforced more strictly
  308. """
  309. func.ratelimit = True
  310. return func
  311. def tag(*tags, **kwarg_tags):
  312. """
  313. Tag function (esp. watchers) with some tags
  314. Currently available tags:
  315. • `no_commands` - Ignore all userbot commands in watcher
  316. • `only_commands` - Capture only userbot commands in watcher
  317. • `out` - Capture only outgoing events
  318. • `in` - Capture only incoming events
  319. • `only_messages` - Capture only messages (not join events)
  320. • `editable` - Capture only messages, which can be edited (no forwards etc.)
  321. • `no_media` - Capture only messages without media and files
  322. • `only_media` - Capture only messages with media and files
  323. • `only_photos` - Capture only messages with photos
  324. • `only_videos` - Capture only messages with videos
  325. • `only_audios` - Capture only messages with audios
  326. • `only_docs` - Capture only messages with documents
  327. • `only_stickers` - Capture only messages with stickers
  328. • `only_inline` - Capture only messages with inline queries
  329. • `only_channels` - Capture only messages with channels
  330. • `only_groups` - Capture only messages with groups
  331. • `only_pm` - Capture only messages with private chats
  332. • `startswith` - Capture only messages that start with given text
  333. • `endswith` - Capture only messages that end with given text
  334. • `contains` - Capture only messages that contain given text
  335. • `regex` - Capture only messages that match given regex
  336. • `filter` - Capture only messages that pass given function
  337. • `from_id` - Capture only messages from given user
  338. • `chat_id` - Capture only messages from given chat
  339. • `thumb_url` - Works for inline command handlers. Will be shown in help
  340. Usage example:
  341. @loader.tag("no_commands", "out")
  342. @loader.tag("no_commands", out=True)
  343. @loader.tag(only_messages=True)
  344. @loader.tag("only_messages", "only_pm", regex=r"^[.] ?hikka$", from_id=659800858)
  345. 💡 These tags can be used directly in `@loader.watcher`:
  346. @loader.watcher("no_commands", out=True)
  347. """
  348. def inner(func: callable):
  349. for _tag in tags:
  350. setattr(func, _tag, True)
  351. for _tag, value in kwarg_tags.items():
  352. setattr(func, _tag, value)
  353. return func
  354. return inner
  355. def _mark_method(mark: str, *args, **kwargs) -> callable:
  356. """
  357. Mark method as a method of a class
  358. """
  359. def decorator(func: callable) -> callable:
  360. setattr(func, mark, True)
  361. for arg in args:
  362. setattr(func, arg, True)
  363. for kwarg, value in kwargs.items():
  364. setattr(func, kwarg, value)
  365. return func
  366. return decorator
  367. def command(*args, **kwargs):
  368. """
  369. Decorator that marks function as userbot command
  370. """
  371. return _mark_method("is_command", *args, **kwargs)
  372. def debug_method(*args, **kwargs):
  373. """
  374. Decorator that marks function as IDM (Internal Debug Method)
  375. :param name: Name of the method
  376. """
  377. return _mark_method("is_debug_method", *args, **kwargs)
  378. def inline_handler(*args, **kwargs):
  379. """
  380. Decorator that marks function as inline handler
  381. """
  382. return _mark_method("is_inline_handler", *args, **kwargs)
  383. def watcher(*args, **kwargs):
  384. """
  385. Decorator that marks function as watcher
  386. """
  387. return _mark_method("is_watcher", *args, **kwargs)
  388. def callback_handler(*args, **kwargs):
  389. """
  390. Decorator that marks function as callback handler
  391. """
  392. return _mark_method("is_callback_handler", *args, **kwargs)
  393. class Modules:
  394. """Stores all registered modules"""
  395. def __init__(
  396. self,
  397. client: "CustomTelegramClient", # type: ignore
  398. db: Database,
  399. allclients: list,
  400. translator: Translator,
  401. ):
  402. self._initial_registration = True
  403. self.commands = {}
  404. self.inline_handlers = {}
  405. self.callback_handlers = {}
  406. self.aliases = {}
  407. self.modules = [] # skipcq: PTC-W0052
  408. self.libraries = []
  409. self.watchers = []
  410. self._log_handlers = []
  411. self._core_commands = []
  412. self.__approve = []
  413. self.allclients = allclients
  414. self.client = client
  415. self._db = db
  416. self._translator = translator
  417. self.secure_boot = False
  418. asyncio.ensure_future(self._junk_collector())
  419. async def _junk_collector(self):
  420. """
  421. Periodically reloads commands, inline handlers, callback handlers and watchers from loaded
  422. modules to prevent zombie handlers
  423. """
  424. while True:
  425. await asyncio.sleep(30)
  426. commands = {}
  427. inline_handlers = {}
  428. callback_handlers = {}
  429. watchers = []
  430. for module in self.modules:
  431. commands.update(module.hikka_commands)
  432. inline_handlers.update(module.hikka_inline_handlers)
  433. callback_handlers.update(module.hikka_callback_handlers)
  434. watchers.extend(module.hikka_watchers.values())
  435. self.commands = commands
  436. self.inline_handlers = inline_handlers
  437. self.callback_handlers = callback_handlers
  438. self.watchers = watchers
  439. logger.debug(
  440. "Reloaded %s commands,"
  441. " %s inline handlers,"
  442. " %s callback handlers and"
  443. " %s watchers",
  444. len(self.commands),
  445. len(self.inline_handlers),
  446. len(self.callback_handlers),
  447. len(self.watchers),
  448. )
  449. async def register_all(
  450. self,
  451. mods: typing.Optional[typing.List[str]] = None,
  452. no_external: bool = False,
  453. ) -> typing.List[Module]:
  454. """Load all modules in the module directory"""
  455. external_mods = []
  456. if not mods:
  457. mods = [
  458. os.path.join(utils.get_base_dir(), MODULES_NAME, mod)
  459. for mod in filter(
  460. lambda x: (x.endswith(".py") and not x.startswith("_")),
  461. os.listdir(os.path.join(utils.get_base_dir(), MODULES_NAME)),
  462. )
  463. ]
  464. self.secure_boot = self._db.get(__name__, "secure_boot", False)
  465. external_mods = (
  466. []
  467. if self.secure_boot
  468. else [
  469. os.path.join(LOADED_MODULES_DIR, mod)
  470. for mod in filter(
  471. lambda x: (
  472. x.endswith(f"{self.client.tg_id}.py")
  473. and not x.startswith("_")
  474. ),
  475. os.listdir(LOADED_MODULES_DIR),
  476. )
  477. ]
  478. )
  479. loaded = []
  480. loaded += await self._register_modules(mods)
  481. if not no_external:
  482. loaded += await self._register_modules(external_mods, "<file>")
  483. return loaded
  484. async def _register_modules(
  485. self,
  486. modules: list,
  487. origin: str = "<core>",
  488. ) -> typing.List[Module]:
  489. with contextlib.suppress(AttributeError):
  490. _hikka_client_id_logging_tag = copy.copy(self.client.tg_id)
  491. loaded = []
  492. for mod in modules:
  493. try:
  494. mod_shortname = (
  495. os.path.basename(mod)
  496. .rsplit(".py", maxsplit=1)[0]
  497. .rsplit("_", maxsplit=1)[0]
  498. )
  499. module_name = f"{__package__}.{MODULES_NAME}.{mod_shortname}"
  500. user_friendly_origin = (
  501. "<core {}>" if origin == "<core>" else "<file {}>"
  502. ).format(mod_shortname)
  503. logger.debug("Loading %s from filesystem", module_name)
  504. with open(mod, "r") as file:
  505. spec = importlib.machinery.ModuleSpec(
  506. module_name,
  507. StringLoader(file.read(), user_friendly_origin),
  508. origin=user_friendly_origin,
  509. )
  510. loaded += [await self.register_module(spec, module_name, origin)]
  511. except BaseException as e:
  512. logger.exception("Failed to load module %s due to %s:", mod, e)
  513. return loaded
  514. async def register_module(
  515. self,
  516. spec: importlib.machinery.ModuleSpec,
  517. module_name: str,
  518. origin: str = "<core>",
  519. save_fs: bool = False,
  520. ) -> Module:
  521. """Register single module from importlib spec"""
  522. with contextlib.suppress(AttributeError):
  523. _hikka_client_id_logging_tag = copy.copy(self.client.tg_id)
  524. module = importlib.util.module_from_spec(spec)
  525. sys.modules[module_name] = module
  526. spec.loader.exec_module(module)
  527. ret = None
  528. ret = next(
  529. (
  530. value()
  531. for value in vars(module).values()
  532. if inspect.isclass(value) and issubclass(value, Module)
  533. ),
  534. None,
  535. )
  536. if hasattr(module, "__version__"):
  537. ret.__version__ = module.__version__
  538. if ret is None:
  539. ret = module.register(module_name)
  540. if not isinstance(ret, Module):
  541. raise TypeError(f"Instance is not a Module, it is {type(ret)}")
  542. await self.complete_registration(ret)
  543. ret.__origin__ = origin
  544. cls_name = ret.__class__.__name__
  545. if save_fs:
  546. path = os.path.join(
  547. LOADED_MODULES_DIR,
  548. f"{cls_name}_{self.client.tg_id}.py",
  549. )
  550. if origin == "<string>":
  551. with open(path, "w") as f:
  552. f.write(spec.loader.data.decode("utf-8"))
  553. logger.debug("Saved class %s to path %s", cls_name, path)
  554. return ret
  555. def add_aliases(self, aliases: dict):
  556. """Saves aliases and applies them to <core>/<file> modules"""
  557. self.aliases.update(aliases)
  558. for alias, cmd in aliases.items():
  559. self.add_alias(alias, cmd)
  560. def register_commands(self, instance: Module):
  561. """Register commands from instance"""
  562. with contextlib.suppress(AttributeError):
  563. _hikka_client_id_logging_tag = copy.copy(self.client.tg_id)
  564. if instance.__origin__.startswith("<core"):
  565. self._core_commands += list(
  566. map(lambda x: x.lower(), list(instance.hikka_commands))
  567. )
  568. for name, cmd in self.commands.copy().items():
  569. if cmd.__self__.__class__.__name__ == instance.__class__.__name__:
  570. logger.debug("Removing command %s for update", name)
  571. del self.commands[name]
  572. for _command, cmd in instance.hikka_commands.items():
  573. # Restrict overwriting core modules' commands
  574. if (
  575. _command.lower() in self._core_commands
  576. and not instance.__origin__.startswith("<core")
  577. ):
  578. with contextlib.suppress(Exception):
  579. self.modules.remove(instance)
  580. raise CoreOverwriteError(command=_command)
  581. self.commands.update({_command.lower(): cmd})
  582. for alias, cmd in self.aliases.copy().items():
  583. if cmd in instance.hikka_commands:
  584. self.add_alias(alias, cmd)
  585. for name, func in instance.hikka_inline_handlers.copy().items():
  586. if name.lower() in self.inline_handlers:
  587. if (
  588. hasattr(func, "__self__")
  589. and hasattr(self.inline_handlers[name], "__self__")
  590. and func.__self__.__class__.__name__
  591. != self.inline_handlers[name].__self__.__class__.__name__
  592. ):
  593. logger.debug("Duplicate inline_handler %s", name)
  594. logger.debug(
  595. "Replacing inline_handler for %s", self.inline_handlers[name]
  596. )
  597. if not func.__doc__:
  598. logger.debug("Missing docs for %s", name)
  599. self.inline_handlers.update({name.lower(): func})
  600. for name, func in instance.hikka_callback_handlers.copy().items():
  601. if name.lower() in self.callback_handlers and (
  602. hasattr(func, "__self__")
  603. and hasattr(self.callback_handlers[name], "__self__")
  604. and func.__self__.__class__.__name__
  605. != self.callback_handlers[name].__self__.__class__.__name__
  606. ):
  607. logger.debug("Duplicate callback_handler %s", name)
  608. self.callback_handlers.update({name.lower(): func})
  609. def register_watcher(self, instance: Module):
  610. """Register watcher from instance"""
  611. with contextlib.suppress(AttributeError):
  612. _hikka_client_id_logging_tag = copy.copy(self.client.tg_id)
  613. for _watcher in self.watchers:
  614. if _watcher.__self__.__class__.__name__ == instance.__class__.__name__:
  615. logger.debug("Removing watcher %s for update", _watcher)
  616. self.watchers.remove(_watcher)
  617. for _watcher in instance.hikka_watchers.values():
  618. self.watchers += [_watcher]
  619. def _lookup(self, modname: str):
  620. return next(
  621. (lib for lib in self.libraries if lib.name.lower() == modname.lower()),
  622. False,
  623. ) or next(
  624. (
  625. mod
  626. for mod in self.modules
  627. if mod.__class__.__name__.lower() == modname.lower()
  628. or mod.name.lower() == modname.lower()
  629. ),
  630. False,
  631. )
  632. @property
  633. def get_approved_channel(self):
  634. return self.__approve.pop(0) if self.__approve else None
  635. async def _approve(
  636. self,
  637. call: InlineCall,
  638. channel: EntityLike,
  639. event: asyncio.Event,
  640. ):
  641. local_event = asyncio.Event()
  642. self.__approve += [(channel, local_event)]
  643. await local_event.wait()
  644. event.status = local_event.status
  645. event.set()
  646. await call.edit(
  647. "💫 <b>Joined <a"
  648. f' href="https://t.me/{channel.username}">{utils.escape_html(channel.title)}</a></b>',
  649. gif="https://static.hikari.gay/0d32cbaa959e755ac8eef610f01ba0bd.gif",
  650. )
  651. async def _decline(
  652. self,
  653. call: InlineCall,
  654. channel: EntityLike,
  655. event: asyncio.Event,
  656. ):
  657. self._db.set(
  658. "hikka.main",
  659. "declined_joins",
  660. list(set(self._db.get("hikka.main", "declined_joins", []) + [channel.id])),
  661. )
  662. event.status = False
  663. event.set()
  664. await call.edit(
  665. "✖️ <b>Declined joining <a"
  666. f' href="https://t.me/{channel.username}">{utils.escape_html(channel.title)}</a></b>',
  667. gif="https://static.hikari.gay/0d32cbaa959e755ac8eef610f01ba0bd.gif",
  668. )
  669. async def _request_join(
  670. self,
  671. peer: EntityLike,
  672. reason: str,
  673. assure_joined: typing.Optional[bool] = False,
  674. _module: Module = None,
  675. ) -> bool:
  676. """
  677. Request to join a channel.
  678. :param peer: The channel to join.
  679. :param reason: The reason for joining.
  680. :param assure_joined: If set, module will not be loaded unless the required channel is joined.
  681. ⚠️ Works only in `client_ready`!
  682. ⚠️ If user declines to join channel, he will not be asked to
  683. join again, so unless he joins it manually, module will not be loaded
  684. ever.
  685. :return: Status of the request.
  686. :rtype: bool
  687. :notice: This method will block module loading until the request is approved or declined.
  688. """
  689. event = asyncio.Event()
  690. await self.client(
  691. UpdateNotifySettingsRequest(
  692. peer=self.inline.bot_username,
  693. settings=InputPeerNotifySettings(show_previews=False, silent=False),
  694. )
  695. )
  696. channel = await self.client.get_entity(peer)
  697. if channel.id in self._db.get("hikka.main", "declined_joins", []):
  698. if assure_joined:
  699. raise LoadError(
  700. f"You need to join @{channel.username} in order to use this module"
  701. )
  702. return False
  703. if not isinstance(channel, Channel):
  704. raise TypeError("`peer` field must be a channel")
  705. if getattr(channel, "left", True):
  706. channel = await self.client.force_get_entity(peer)
  707. if not getattr(channel, "left", True):
  708. return True
  709. _module.strings._base_strings["_hikka_internal_request_join"] = (
  710. f"💫 <b>Module </b><code>{_module.__class__.__name__}</code><b> requested to"
  711. " join channel <a"
  712. f" href='https://t.me/{channel.username}'>{utils.escape_html(channel.title)}</a></b>\n\n<b>❓"
  713. f" Reason: </b><i>{utils.escape_html(reason)}</i>"
  714. )
  715. if not hasattr(_module, "strings_ru"):
  716. _module.strings_ru = {}
  717. _module.strings_ru["_hikka_internal_request_join"] = (
  718. f"💫 <b>Модуль </b><code>{_module.__class__.__name__}</code><b> запросил"
  719. " разрешение на вступление в канал <a"
  720. f" href='https://t.me/{channel.username}'>{utils.escape_html(channel.title)}</a></b>\n\n<b>❓"
  721. f" Причина: </b><i>{utils.escape_html(reason)}</i>"
  722. )
  723. await self.inline.bot.send_animation(
  724. self.client.tg_id,
  725. "https://static.hikari.gay/ab3adf144c94a0883bfe489f4eebc520.gif",
  726. caption=_module.strings("_hikka_internal_request_join"),
  727. reply_markup=self.inline.generate_markup(
  728. [
  729. {
  730. "text": "💫 Approve",
  731. "callback": self._approve,
  732. "args": (channel, event),
  733. },
  734. {
  735. "text": "✖️ Decline",
  736. "callback": self._decline,
  737. "args": (channel, event),
  738. },
  739. ]
  740. ),
  741. )
  742. _module.hikka_wait_channel_approve = (
  743. _module.__class__.__name__,
  744. channel,
  745. reason,
  746. )
  747. await event.wait()
  748. with contextlib.suppress(AttributeError):
  749. delattr(_module, "hikka_wait_channel_approve")
  750. if assure_joined and not event.status:
  751. raise LoadError(
  752. f"You need to join @{channel.username} in order to use this module"
  753. )
  754. return event.status
  755. def get_prefix(self) -> str:
  756. return self._db.get("hikka.main", "command_prefix", ".")
  757. async def complete_registration(self, instance: Module):
  758. """Complete registration of instance"""
  759. with contextlib.suppress(AttributeError):
  760. _hikka_client_id_logging_tag = copy.copy(self.client.tg_id)
  761. instance.allclients = self.allclients
  762. instance.allmodules = self
  763. instance.hikka = True
  764. instance.get = partial(self._get, _owner=instance.__class__.__name__)
  765. instance.set = partial(self._set, _owner=instance.__class__.__name__)
  766. instance.pointer = partial(self._pointer, _owner=instance.__class__.__name__)
  767. instance.get_prefix = self.get_prefix
  768. instance.client = self.client
  769. instance._client = self.client
  770. instance.db = self._db
  771. instance._db = self._db
  772. instance.lookup = self._lookup
  773. instance.import_lib = self._mod_import_lib
  774. instance.tg_id = self.client.tg_id
  775. instance._tg_id = self.client.tg_id
  776. instance.request_join = partial(self._request_join, _module=instance)
  777. instance.animate = self._animate
  778. for module in self.modules:
  779. if module.__class__.__name__ == instance.__class__.__name__:
  780. if module.__origin__.startswith("<core"):
  781. raise CoreOverwriteError(
  782. module=module.__class__.__name__[:-3]
  783. if module.__class__.__name__.endswith("Mod")
  784. else module.__class__.__name__
  785. )
  786. logger.debug("Removing module %s for update", module)
  787. await module.on_unload()
  788. self.modules.remove(module)
  789. for method in dir(module):
  790. if isinstance(getattr(module, method), InfiniteLoop):
  791. getattr(module, method).stop()
  792. logger.debug(
  793. "Stopped loop in module %s, method %s", module, method
  794. )
  795. self.modules += [instance]
  796. def _get(
  797. self,
  798. key: str,
  799. default: typing.Optional[JSONSerializable] = None,
  800. _owner: str = None,
  801. ) -> JSONSerializable:
  802. return self._db.get(_owner, key, default)
  803. def _set(self, key: str, value: JSONSerializable, _owner: str = None) -> bool:
  804. return self._db.set(_owner, key, value)
  805. def _pointer(
  806. self,
  807. key: str,
  808. default: typing.Optional[JSONSerializable] = None,
  809. _owner: str = None,
  810. ) -> JSONSerializable:
  811. return self._db.pointer(_owner, key, default)
  812. async def _mod_import_lib(
  813. self,
  814. url: str,
  815. *,
  816. suspend_on_error: typing.Optional[bool] = False,
  817. _did_requirements: bool = False,
  818. ) -> object:
  819. """
  820. Import library from url and register it in :obj:`Modules`
  821. :param url: Url to import
  822. :param suspend_on_error: Will raise :obj:`loader.SelfSuspend` if library can't be loaded
  823. :return: :obj:`Library`
  824. :raise: SelfUnload if :attr:`suspend_on_error` is True and error occurred
  825. :raise: HTTPError if library is not found
  826. :raise: ImportError if library doesn't have any class which is a subclass of :obj:`loader.Library`
  827. :raise: ImportError if library name doesn't end with `Lib`
  828. :raise: RuntimeError if library throws in :method:`init`
  829. :raise: RuntimeError if library classname exists in :obj:`Modules`.libraries
  830. """
  831. def _raise(e: Exception):
  832. if suspend_on_error:
  833. raise SelfSuspend("Required library is not available or is corrupted.")
  834. raise e
  835. if not utils.check_url(url):
  836. _raise(ValueError("Invalid url for library"))
  837. code = await utils.run_sync(requests.get, url)
  838. code.raise_for_status()
  839. code = code.text
  840. if re.search(r"# ?scope: ?hikka_min", code):
  841. ver = tuple(
  842. map(
  843. int,
  844. re.search(r"# ?scope: ?hikka_min ((\d+\.){2}\d+)", code)[1].split(
  845. "."
  846. ),
  847. )
  848. )
  849. if version.__version__ < ver:
  850. _raise(
  851. RuntimeError(
  852. f"Library requires Hikka version {'{}.{}.{}'.format(*ver)}+"
  853. )
  854. )
  855. module = f"hikka.libraries.{url.replace('%', '%%').replace('.', '%d')}"
  856. origin = f"<library {url}>"
  857. spec = importlib.machinery.ModuleSpec(
  858. module,
  859. StringLoader(code, origin),
  860. origin=origin,
  861. )
  862. try:
  863. instance = importlib.util.module_from_spec(spec)
  864. sys.modules[module] = instance
  865. spec.loader.exec_module(instance)
  866. except ImportError as e:
  867. logger.info(
  868. "Library loading failed, attemping dependency installation (%s)",
  869. e.name,
  870. )
  871. # Let's try to reinstall dependencies
  872. try:
  873. requirements = list(
  874. filter(
  875. lambda x: not x.startswith(("-", "_", ".")),
  876. map(
  877. str.strip,
  878. VALID_PIP_PACKAGES.search(code)[1].split(),
  879. ),
  880. )
  881. )
  882. except TypeError:
  883. logger.warning(
  884. "No valid pip packages specified in code, attemping"
  885. " installation from error"
  886. )
  887. requirements = [e.name]
  888. logger.debug("Installing requirements: %s", requirements)
  889. if not requirements or _did_requirements:
  890. _raise(e)
  891. pip = await asyncio.create_subprocess_exec(
  892. sys.executable,
  893. "-m",
  894. "pip",
  895. "install",
  896. "--upgrade",
  897. "-q",
  898. "--disable-pip-version-check",
  899. "--no-warn-script-location",
  900. *["--user"] if USER_INSTALL else [],
  901. *requirements,
  902. )
  903. rc = await pip.wait()
  904. if rc != 0:
  905. _raise(e)
  906. importlib.invalidate_caches()
  907. kwargs = utils.get_kwargs()
  908. kwargs["_did_requirements"] = True
  909. return await self._mod_import_lib(**kwargs) # Try again
  910. lib_obj = next(
  911. (
  912. value()
  913. for value in vars(instance).values()
  914. if inspect.isclass(value) and issubclass(value, Library)
  915. ),
  916. None,
  917. )
  918. if not lib_obj:
  919. _raise(ImportError("Invalid library. No class found"))
  920. if not lib_obj.__class__.__name__.endswith("Lib"):
  921. _raise(
  922. ImportError(
  923. "Invalid library. Classname {} does not end with 'Lib'".format(
  924. lib_obj.__class__.__name__
  925. )
  926. )
  927. )
  928. if (
  929. all(
  930. line.replace(" ", "") != "#scope:no_stats" for line in code.splitlines()
  931. )
  932. and self._db.get("hikka.main", "stats", True)
  933. and url is not None
  934. and utils.check_url(url)
  935. ):
  936. with contextlib.suppress(Exception):
  937. await self._lookup("loader")._send_stats(url)
  938. lib_obj.client = self.client
  939. lib_obj._client = self.client # skipcq
  940. lib_obj.db = self._db
  941. lib_obj._db = self._db # skipcq
  942. lib_obj.name = lib_obj.__class__.__name__
  943. lib_obj.source_url = url.strip("/")
  944. lib_obj.lookup = self._lookup
  945. lib_obj.inline = self.inline
  946. lib_obj.tg_id = self.client.tg_id
  947. lib_obj.allmodules = self
  948. lib_obj._lib_get = partial(
  949. self._get,
  950. _owner=lib_obj.__class__.__name__,
  951. )
  952. lib_obj._lib_set = partial(
  953. self._set,
  954. _owner=lib_obj.__class__.__name__,
  955. )
  956. lib_obj._lib_pointer = partial(
  957. self._pointer,
  958. _owner=lib_obj.__class__.__name__,
  959. )
  960. lib_obj.get_prefix = self.get_prefix
  961. for old_lib in self.libraries:
  962. if old_lib.name == lib_obj.name and (
  963. not isinstance(getattr(old_lib, "version", None), tuple)
  964. and not isinstance(getattr(lib_obj, "version", None), tuple)
  965. or old_lib.version >= lib_obj.version
  966. ):
  967. logger.debug("Using existing instance of library %s", old_lib.name)
  968. return old_lib
  969. if hasattr(lib_obj, "init"):
  970. if not callable(lib_obj.init):
  971. _raise(ValueError("Library init() must be callable"))
  972. try:
  973. await lib_obj.init()
  974. except Exception:
  975. _raise(RuntimeError("Library init() failed"))
  976. if hasattr(lib_obj, "config"):
  977. if not isinstance(lib_obj.config, LibraryConfig):
  978. _raise(
  979. RuntimeError("Library config must be a `LibraryConfig` instance")
  980. )
  981. libcfg = lib_obj.db.get(
  982. lib_obj.__class__.__name__,
  983. "__config__",
  984. {},
  985. )
  986. for conf in lib_obj.config:
  987. with contextlib.suppress(Exception):
  988. lib_obj.config.set_no_raise(
  989. conf,
  990. (
  991. libcfg[conf]
  992. if conf in libcfg
  993. else os.environ.get(f"{lib_obj.__class__.__name__}.{conf}")
  994. or lib_obj.config.getdef(conf)
  995. ),
  996. )
  997. if hasattr(lib_obj, "strings"):
  998. lib_obj.strings = Strings(lib_obj, self._translator)
  999. lib_obj.translator = self._translator
  1000. for old_lib in self.libraries:
  1001. if old_lib.name == lib_obj.name:
  1002. if hasattr(old_lib, "on_lib_update") and callable(
  1003. old_lib.on_lib_update
  1004. ):
  1005. await old_lib.on_lib_update(lib_obj)
  1006. replace_all_refs(old_lib, lib_obj)
  1007. logger.debug(
  1008. "Replacing existing instance of library %s with updated object",
  1009. lib_obj.name,
  1010. )
  1011. return lib_obj
  1012. self.libraries += [lib_obj]
  1013. return lib_obj
  1014. def dispatch(self, _command: str) -> tuple:
  1015. """Dispatch command to appropriate module"""
  1016. return next(
  1017. (
  1018. (cmd, self.commands[cmd.lower()])
  1019. for cmd in [_command, self.aliases.get(_command.lower())]
  1020. if cmd and cmd.lower() in self.commands
  1021. ),
  1022. (_command, None),
  1023. )
  1024. def send_config(self, skip_hook: bool = False):
  1025. """Configure modules"""
  1026. for mod in self.modules:
  1027. self.send_config_one(mod, skip_hook)
  1028. def send_config_one(self, mod: Module, skip_hook: bool = False):
  1029. """Send config to single instance"""
  1030. with contextlib.suppress(AttributeError):
  1031. _hikka_client_id_logging_tag = copy.copy(self.client.tg_id)
  1032. if hasattr(mod, "config"):
  1033. modcfg = self._db.get(
  1034. mod.__class__.__name__,
  1035. "__config__",
  1036. {},
  1037. )
  1038. try:
  1039. for conf in mod.config:
  1040. with contextlib.suppress(validators.ValidationError):
  1041. mod.config.set_no_raise(
  1042. conf,
  1043. (
  1044. modcfg[conf]
  1045. if conf in modcfg
  1046. else os.environ.get(f"{mod.__class__.__name__}.{conf}")
  1047. or mod.config.getdef(conf)
  1048. ),
  1049. )
  1050. except AttributeError:
  1051. logger.warning(
  1052. "Got invalid config instance. Expected `ModuleConfig`, got %s, %s",
  1053. type(mod.config),
  1054. mod.config,
  1055. )
  1056. if not hasattr(mod, "name"):
  1057. mod.name = mod.strings["name"]
  1058. if skip_hook:
  1059. return
  1060. if hasattr(mod, "strings"):
  1061. mod.strings = Strings(mod, self._translator)
  1062. mod.translator = self._translator
  1063. try:
  1064. mod.config_complete()
  1065. except Exception as e:
  1066. logger.exception("Failed to send mod config complete signal due to %s", e)
  1067. raise
  1068. async def send_ready(self):
  1069. """Send all data to all modules"""
  1070. # Init inline manager anyway, so the modules
  1071. # can access its `init_complete`
  1072. inline_manager = InlineManager(self.client, self._db, self)
  1073. await inline_manager._register_manager()
  1074. # We save it to `Modules` attribute, so not to re-init
  1075. # it everytime module is loaded. Then we can just
  1076. # re-assign it to all modules
  1077. self.inline = inline_manager
  1078. try:
  1079. await asyncio.gather(*[self.send_ready_one(mod) for mod in self.modules])
  1080. except Exception as e:
  1081. logger.exception("Failed to send mod init complete signal due to %s", e)
  1082. async def _animate(
  1083. self,
  1084. message: typing.Union[Message, InlineMessage],
  1085. frames: typing.List[str],
  1086. interval: typing.Union[float, int],
  1087. *,
  1088. inline: bool = False,
  1089. ) -> None:
  1090. """
  1091. Animate message
  1092. :param message: Message to animate
  1093. :param frames: A List of strings which are the frames of animation
  1094. :param interval: Animation delay
  1095. :param inline: Whether to use inline bot for animation
  1096. :returns message:
  1097. Please, note that if you set `inline=True`, first frame will be shown with an empty
  1098. button due to the limitations of Telegram API
  1099. """
  1100. with contextlib.suppress(AttributeError):
  1101. _hikka_client_id_logging_tag = copy.copy(self.client.tg_id)
  1102. if interval < 0.1:
  1103. logger.warning(
  1104. "Resetting animation interval to 0.1s, because it may get you in"
  1105. " floodwaits bro"
  1106. )
  1107. interval = 0.1
  1108. for frame in frames:
  1109. if isinstance(message, Message):
  1110. if inline:
  1111. message = await self.inline.form(
  1112. message=message,
  1113. text=frame,
  1114. reply_markup={"text": "\u0020\u2800", "data": "empty"},
  1115. )
  1116. else:
  1117. message = await utils.answer(message, frame)
  1118. elif isinstance(message, InlineMessage) and inline:
  1119. await message.edit(frame)
  1120. await asyncio.sleep(interval)
  1121. return message
  1122. async def send_ready_one(
  1123. self,
  1124. mod: Module,
  1125. no_self_unload: bool = False,
  1126. from_dlmod: bool = False,
  1127. ):
  1128. with contextlib.suppress(AttributeError):
  1129. _hikka_client_id_logging_tag = copy.copy(self.client.tg_id)
  1130. mod.inline = self.inline
  1131. for method in dir(mod):
  1132. if isinstance(getattr(mod, method), InfiniteLoop):
  1133. setattr(getattr(mod, method), "module_instance", mod)
  1134. if getattr(mod, method).autostart:
  1135. getattr(mod, method).start()
  1136. logger.debug("Added module %s to method %s", mod, method)
  1137. if from_dlmod:
  1138. try:
  1139. if len(inspect.signature(mod.on_dlmod).parameters) == 2:
  1140. await mod.on_dlmod(self.client, self._db)
  1141. else:
  1142. await mod.on_dlmod()
  1143. except Exception:
  1144. logger.info("Can't process `on_dlmod` hook", exc_info=True)
  1145. try:
  1146. if len(inspect.signature(mod.client_ready).parameters) == 2:
  1147. await mod.client_ready(self.client, self._db)
  1148. else:
  1149. await mod.client_ready()
  1150. except SelfUnload as e:
  1151. if no_self_unload:
  1152. raise e
  1153. logger.debug("Unloading %s, because it raised SelfUnload", mod)
  1154. self.modules.remove(mod)
  1155. except SelfSuspend as e:
  1156. if no_self_unload:
  1157. raise e
  1158. logger.debug("Suspending %s, because it raised SelfSuspend", mod)
  1159. return
  1160. except Exception as e:
  1161. logger.exception(
  1162. "Failed to send mod init complete signal for %s due to %s,"
  1163. " attempting unload",
  1164. mod,
  1165. e,
  1166. )
  1167. self.modules.remove(mod)
  1168. raise
  1169. self.register_commands(mod)
  1170. self.register_watcher(mod)
  1171. def get_classname(self, name: str) -> str:
  1172. return next(
  1173. (
  1174. module.__class__.__module__
  1175. for module in reversed(self.modules)
  1176. if name in (module.name, module.__class__.__module__)
  1177. ),
  1178. name,
  1179. )
  1180. async def unload_module(self, classname: str) -> typing.List[str]:
  1181. """Remove module and all stuff from it"""
  1182. worked = []
  1183. with contextlib.suppress(AttributeError):
  1184. _hikka_client_id_logging_tag = copy.copy(self.client.tg_id)
  1185. for module in self.modules:
  1186. if classname.lower() in (
  1187. module.name.lower(),
  1188. module.__class__.__name__.lower(),
  1189. ):
  1190. if module.__origin__.startswith("<core"):
  1191. raise CoreUnloadError(module.__class__.__name__)
  1192. worked += [module.__class__.__name__]
  1193. name = module.__class__.__name__
  1194. path = os.path.join(
  1195. LOADED_MODULES_DIR,
  1196. f"{name}_{self.client.tg_id}.py",
  1197. )
  1198. if os.path.isfile(path):
  1199. os.remove(path)
  1200. logger.debug("Removed %s file at path %s", name, path)
  1201. logger.debug("Removing module %s for unload", module)
  1202. self.modules.remove(module)
  1203. await module.on_unload()
  1204. for method in dir(module):
  1205. if isinstance(getattr(module, method), InfiniteLoop):
  1206. getattr(module, method).stop()
  1207. logger.debug(
  1208. "Stopped loop in module %s, method %s", module, method
  1209. )
  1210. for name, cmd in self.commands.copy().items():
  1211. if cmd.__self__.__class__.__name__ == module.__class__.__name__:
  1212. logger.debug("Removing command %s for unload", name)
  1213. del self.commands[name]
  1214. for alias, _command in self.aliases.copy().items():
  1215. if _command == name:
  1216. del self.aliases[alias]
  1217. for _watcher in self.watchers.copy():
  1218. if (
  1219. _watcher.__self__.__class__.__name__
  1220. == module.__class__.__name__
  1221. ):
  1222. logger.debug("Removing watcher %s for unload", _watcher)
  1223. self.watchers.remove(_watcher)
  1224. logger.debug("Worked: %s", worked)
  1225. return worked
  1226. def add_alias(self, alias: str, cmd: str) -> bool:
  1227. """Make an alias"""
  1228. if cmd not in self.commands:
  1229. return False
  1230. self.aliases[alias.lower().strip()] = cmd
  1231. return True
  1232. def remove_alias(self, alias: str) -> bool:
  1233. """Remove an alias"""
  1234. return bool(self.aliases.pop(alias.lower().strip(), None))
  1235. async def log(self, *args, **kwargs):
  1236. """Unnecessary placeholder for logging"""