loader.py 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181
  1. """Registers modules"""
  2. # Friendly Telegram (telegram userbot)
  3. # Copyright (C) 2018-2021 The Authors
  4. # This program is free software: you can redistribute it and/or modify
  5. # it under the terms of the GNU Affero General Public License as published by
  6. # the Free Software Foundation, either version 3 of the License, or
  7. # (at your option) any later version.
  8. # This program is distributed in the hope that it will be useful,
  9. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. # GNU Affero General Public License for more details.
  12. # You should have received a copy of the GNU Affero General Public License
  13. # along with this program. If not, see <https://www.gnu.org/licenses/>.
  14. # █ █ ▀ █▄▀ ▄▀█ █▀█ ▀
  15. # █▀█ █ █ █ █▀█ █▀▄ █
  16. # © Copyright 2022
  17. # https://t.me/hikariatama
  18. #
  19. # 🔒 Licensed under the GNU AGPLv3
  20. # 🌐 https://www.gnu.org/licenses/agpl-3.0.html
  21. import asyncio
  22. import contextlib
  23. import copy
  24. from functools import partial, wraps
  25. import importlib
  26. import importlib.util
  27. import inspect
  28. import logging
  29. import os
  30. import sys
  31. from importlib.machinery import ModuleSpec
  32. from types import FunctionType
  33. from typing import Any, Hashable, Optional, Union, List
  34. import requests
  35. from telethon import TelegramClient
  36. from telethon.tl.types import Message
  37. from . import security, utils, validators
  38. from ._types import (
  39. ConfigValue, # skipcq
  40. LoadError, # skipcq
  41. Module,
  42. Library, # skipcq
  43. ModuleConfig, # skipcq
  44. LibraryConfig, # skipcq
  45. SelfUnload,
  46. SelfSuspend,
  47. StopLoop,
  48. InlineMessage,
  49. CoreOverwriteError,
  50. StringLoader,
  51. )
  52. from .inline.core import InlineManager
  53. from .translations import Strings, Translator
  54. import gc as _gc
  55. import types as _types
  56. logger = logging.getLogger(__name__)
  57. owner = security.owner
  58. sudo = security.sudo
  59. support = security.support
  60. group_owner = security.group_owner
  61. group_admin_add_admins = security.group_admin_add_admins
  62. group_admin_change_info = security.group_admin_change_info
  63. group_admin_ban_users = security.group_admin_ban_users
  64. group_admin_delete_messages = security.group_admin_delete_messages
  65. group_admin_pin_messages = security.group_admin_pin_messages
  66. group_admin_invite_users = security.group_admin_invite_users
  67. group_admin = security.group_admin
  68. group_member = security.group_member
  69. pm = security.pm
  70. unrestricted = security.unrestricted
  71. inline_everyone = security.inline_everyone
  72. def proxy0(data):
  73. def proxy1():
  74. return data
  75. return proxy1
  76. _CELLTYPE = type(proxy0(None).__closure__[0])
  77. def replace_all_refs(replace_from: Any, replace_to: Any) -> Any:
  78. """
  79. :summary: Uses the :mod:`gc` module to replace all references to obj
  80. :attr:`replace_from` with :attr:`replace_to` (it tries it's best,
  81. anyway).
  82. :param replace_from: The obj you want to replace.
  83. :param replace_to: The new objject you want in place of the old one.
  84. :returns: The replace_from
  85. """
  86. # https://github.com/cart0113/pyjack/blob/dd1f9b70b71f48335d72f53ee0264cf70dbf4e28/pyjack.py
  87. _gc.collect()
  88. hit = False
  89. for referrer in _gc.get_referrers(replace_from):
  90. # FRAMES -- PASS THEM UP
  91. if isinstance(referrer, _types.FrameType):
  92. continue
  93. # DICTS
  94. if isinstance(referrer, dict):
  95. cls = None
  96. # THIS CODE HERE IS TO DEAL WITH DICTPROXY TYPES
  97. if "__dict__" in referrer and "__weakref__" in referrer:
  98. for cls in _gc.get_referrers(referrer):
  99. if inspect.isclass(cls) and cls.__dict__ == referrer:
  100. break
  101. for key, value in referrer.items():
  102. # REMEMBER TO REPLACE VALUES ...
  103. if value is replace_from:
  104. hit = True
  105. value = replace_to
  106. referrer[key] = value
  107. if cls: # AGAIN, CLEANUP DICTPROXY PROBLEM
  108. setattr(cls, key, replace_to)
  109. # AND KEYS.
  110. if key is replace_from:
  111. hit = True
  112. del referrer[key]
  113. referrer[replace_to] = value
  114. elif isinstance(referrer, list):
  115. for i, value in enumerate(referrer):
  116. if value is replace_from:
  117. hit = True
  118. referrer[i] = replace_to
  119. elif isinstance(referrer, set):
  120. referrer.remove(replace_from)
  121. referrer.add(replace_to)
  122. hit = True
  123. elif isinstance(
  124. referrer,
  125. (
  126. tuple,
  127. frozenset,
  128. ),
  129. ):
  130. new_tuple = []
  131. for obj in referrer:
  132. if obj is replace_from:
  133. new_tuple.append(replace_to)
  134. else:
  135. new_tuple.append(obj)
  136. replace_all_refs(referrer, type(referrer)(new_tuple))
  137. elif isinstance(referrer, _CELLTYPE):
  138. def _proxy0(data):
  139. def proxy1():
  140. return data
  141. return proxy1
  142. proxy = _proxy0(replace_to)
  143. newcell = proxy.__closure__[0]
  144. replace_all_refs(referrer, newcell)
  145. elif isinstance(referrer, _types.FunctionType):
  146. localsmap = {}
  147. for key in ["code", "globals", "name", "defaults", "closure"]:
  148. orgattr = getattr(referrer, f"__{key}__")
  149. localsmap[key] = replace_to if orgattr is replace_from else orgattr
  150. localsmap["argdefs"] = localsmap["defaults"]
  151. del localsmap["defaults"]
  152. newfn = _types.FunctionType(**localsmap)
  153. replace_all_refs(referrer, newfn)
  154. else:
  155. logging.debug(f"{referrer} is not supported.")
  156. if hit is False:
  157. raise AttributeError(f"Object '{replace_from}' not found")
  158. return replace_from
  159. async def stop_placeholder() -> bool:
  160. return True
  161. class Placeholder:
  162. """Placeholder"""
  163. class InfiniteLoop:
  164. _task = None
  165. status = False
  166. module_instance = None # Will be passed later
  167. def __init__(
  168. self,
  169. func: FunctionType,
  170. interval: int,
  171. autostart: bool,
  172. wait_before: bool,
  173. stop_clause: Union[str, None],
  174. ):
  175. self.func = func
  176. self.interval = interval
  177. self._wait_before = wait_before
  178. self._stop_clause = stop_clause
  179. self.autostart = autostart
  180. def _stop(self, *args, **kwargs):
  181. self._wait_for_stop.set()
  182. def stop(self, *args, **kwargs):
  183. with contextlib.suppress(AttributeError):
  184. _hikka_client_id_logging_tag = copy.copy(
  185. self.module_instance.allmodules.client.tg_id
  186. )
  187. if self._task:
  188. logger.debug(f"Stopped loop for {self.func}")
  189. self._wait_for_stop = asyncio.Event()
  190. self.status = False
  191. self._task.add_done_callback(self._stop)
  192. self._task.cancel()
  193. return asyncio.ensure_future(self._wait_for_stop.wait())
  194. logger.debug("Loop is not running")
  195. return asyncio.ensure_future(stop_placeholder())
  196. def start(self, *args, **kwargs):
  197. with contextlib.suppress(AttributeError):
  198. _hikka_client_id_logging_tag = copy.copy(
  199. self.module_instance.allmodules.client.tg_id
  200. )
  201. if not self._task:
  202. logger.debug(f"Started loop for {self.func}")
  203. self._task = asyncio.ensure_future(self.actual_loop(*args, **kwargs))
  204. else:
  205. logger.debug("Attempted to start already running loop")
  206. async def actual_loop(self, *args, **kwargs):
  207. # Wait for loader to set attribute
  208. while not self.module_instance:
  209. await asyncio.sleep(0.01)
  210. if isinstance(self._stop_clause, str) and self._stop_clause:
  211. self.module_instance.set(self._stop_clause, True)
  212. self.status = True
  213. while self.status:
  214. if self._wait_before:
  215. await asyncio.sleep(self.interval)
  216. if (
  217. isinstance(self._stop_clause, str)
  218. and self._stop_clause
  219. and not self.module_instance.get(self._stop_clause, False)
  220. ):
  221. break
  222. try:
  223. await self.func(self.module_instance, *args, **kwargs)
  224. except StopLoop:
  225. break
  226. except Exception:
  227. logger.exception("Error running loop!")
  228. if not self._wait_before:
  229. await asyncio.sleep(self.interval)
  230. self._wait_for_stop.set()
  231. self.status = False
  232. def __del__(self):
  233. self.stop()
  234. def loop(
  235. interval: int = 5,
  236. autostart: Optional[bool] = False,
  237. wait_before: Optional[bool] = False,
  238. stop_clause: Optional[str] = None,
  239. ) -> FunctionType:
  240. """
  241. Create new infinite loop from class method
  242. :param interval: Loop iterations delay
  243. :param autostart: Start loop once module is loaded
  244. :param wait_before: Insert delay before actual iteration, rather than after
  245. :param stop_clause: Database key, based on which the loop will run.
  246. This key will be set to `True` once loop is started,
  247. and will stop after key resets to `False`
  248. :attr status: Boolean, describing whether the loop is running
  249. """
  250. def wrapped(func):
  251. return InfiniteLoop(func, interval, autostart, wait_before, stop_clause)
  252. return wrapped
  253. MODULES_NAME = "modules"
  254. ru_keys = 'ёйцукенгшщзхъфывапролджэячсмитьбю.Ё"№;%:?ЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭ/ЯЧСМИТЬБЮ,'
  255. en_keys = "`qwertyuiop[]asdfghjkl;'zxcvbnm,./~@#$%^&QWERTYUIOP{}ASDFGHJKL:\"|ZXCVBNM<>?"
  256. BASE_DIR = (
  257. os.path.normpath(os.path.join(utils.get_base_dir(), ".."))
  258. if "OKTETO" not in os.environ and "DOCKER" not in os.environ
  259. else "/data"
  260. )
  261. LOADED_MODULES_DIR = os.path.join(BASE_DIR, "loaded_modules")
  262. if not os.path.isdir(LOADED_MODULES_DIR) and "DYNO" not in os.environ:
  263. os.mkdir(LOADED_MODULES_DIR, mode=0o755)
  264. def translatable_docstring(cls):
  265. """Decorator that makes triple-quote docstrings translatable"""
  266. @wraps(cls.config_complete)
  267. def config_complete(self, *args, **kwargs):
  268. for command_, func_ in get_commands(cls).items():
  269. try:
  270. func_.__doc__ = self.strings[f"_cmd_doc_{command_}"]
  271. except AttributeError:
  272. func_.__func__.__doc__ = self.strings[f"_cmd_doc_{command_}"]
  273. for inline_handler_, func_ in get_inline_handlers(cls).items():
  274. try:
  275. func_.__doc__ = self.strings[f"_ihandle_doc_{inline_handler_}"]
  276. except AttributeError:
  277. func_.__func__.__doc__ = self.strings[f"_ihandle_doc_{inline_handler_}"]
  278. self.__doc__ = self.strings["_cls_doc"]
  279. return self.config_complete._old_(self, *args, **kwargs)
  280. config_complete._old_ = cls.config_complete
  281. cls.config_complete = config_complete
  282. for command, func in get_commands(cls).items():
  283. cls.strings[f"_cmd_doc_{command}"] = inspect.getdoc(func)
  284. for inline_handler, func in get_inline_handlers(cls).items():
  285. cls.strings[f"_ihandle_doc_{inline_handler}"] = inspect.getdoc(func)
  286. cls.strings["_cls_doc"] = inspect.getdoc(cls)
  287. return cls
  288. tds = translatable_docstring # Shorter name for modules to use
  289. def ratelimit(func):
  290. """Decorator that causes ratelimiting for this command to be enforced more strictly"""
  291. func.ratelimit = True
  292. return func
  293. def get_commands(mod):
  294. """Introspect the module to get its commands"""
  295. return {
  296. method_name.rsplit("cmd", maxsplit=1)[0]: getattr(mod, method_name)
  297. for method_name in dir(mod)
  298. if callable(getattr(mod, method_name)) and method_name.endswith("cmd")
  299. }
  300. def get_inline_handlers(mod):
  301. """Introspect the module to get its inline handlers"""
  302. return {
  303. method_name.rsplit("_inline_handler", maxsplit=1)[0]: getattr(mod, method_name)
  304. for method_name in dir(mod)
  305. if callable(getattr(mod, method_name))
  306. and method_name.endswith("_inline_handler")
  307. }
  308. def get_callback_handlers(mod):
  309. """Introspect the module to get its callback handlers"""
  310. return {
  311. method_name.rsplit("_callback_handler", maxsplit=1)[0]: getattr(
  312. mod,
  313. method_name,
  314. )
  315. for method_name in dir(mod)
  316. if callable(getattr(mod, method_name))
  317. and method_name.endswith("_callback_handler")
  318. }
  319. class Modules:
  320. """Stores all registered modules"""
  321. client = None
  322. _initial_registration = True
  323. commands = {}
  324. inline_handlers = {}
  325. callback_handlers = {}
  326. aliases = {}
  327. modules = [] # skipcq: PTC-W0052
  328. libraries = []
  329. watchers = []
  330. _log_handlers = []
  331. _core_commands = []
  332. def __init__(
  333. self,
  334. client: TelegramClient,
  335. db: "Database", # type: ignore
  336. allclients: list,
  337. translator: Translator,
  338. ):
  339. self.allclients = allclients
  340. self.client = client
  341. self._db = db
  342. self._translator = translator
  343. def register_all(self, mods: list = None):
  344. """Load all modules in the module directory"""
  345. external_mods = []
  346. if not mods:
  347. mods = [
  348. os.path.join(utils.get_base_dir(), MODULES_NAME, mod)
  349. for mod in filter(
  350. lambda x: (x.endswith(".py") and not x.startswith("_")),
  351. os.listdir(os.path.join(utils.get_base_dir(), MODULES_NAME)),
  352. )
  353. ]
  354. if "DYNO" not in os.environ and not self._db.get(
  355. __name__, "secure_boot", False
  356. ):
  357. external_mods = [
  358. os.path.join(LOADED_MODULES_DIR, mod)
  359. for mod in filter(
  360. lambda x: (
  361. x.endswith(f"{self.client.tg_id}.py")
  362. and not x.startswith("_")
  363. ),
  364. os.listdir(LOADED_MODULES_DIR),
  365. )
  366. ]
  367. else:
  368. external_mods = []
  369. self._register_modules(mods)
  370. self._register_modules(external_mods, "<file>")
  371. def _register_modules(self, modules: list, origin: str = "<core>"):
  372. with contextlib.suppress(AttributeError):
  373. _hikka_client_id_logging_tag = copy.copy(self.client.tg_id)
  374. for mod in modules:
  375. try:
  376. mod_shortname = (
  377. os.path.basename(mod)
  378. .rsplit(".py", maxsplit=1)[0]
  379. .rsplit("_", maxsplit=1)[0]
  380. )
  381. module_name = f"{__package__}.{MODULES_NAME}.{mod_shortname}"
  382. user_friendly_origin = (
  383. "<core {}>" if origin == "<core>" else "<file {}>"
  384. ).format(mod_shortname)
  385. logger.debug(f"Loading {module_name} from filesystem")
  386. with open(mod, "r") as file:
  387. spec = ModuleSpec(
  388. module_name,
  389. StringLoader(file.read(), user_friendly_origin),
  390. origin=user_friendly_origin,
  391. )
  392. self.register_module(spec, module_name, origin)
  393. except BaseException as e:
  394. logger.exception(f"Failed to load module {mod} due to {e}:")
  395. def register_module(
  396. self,
  397. spec: ModuleSpec,
  398. module_name: str,
  399. origin: str = "<core>",
  400. save_fs: bool = False,
  401. ) -> Module:
  402. """Register single module from importlib spec"""
  403. with contextlib.suppress(AttributeError):
  404. _hikka_client_id_logging_tag = copy.copy(self.client.tg_id)
  405. module = importlib.util.module_from_spec(spec)
  406. sys.modules[module_name] = module
  407. spec.loader.exec_module(module)
  408. ret = None
  409. ret = next(
  410. (
  411. value()
  412. for value in vars(module).values()
  413. if inspect.isclass(value) and issubclass(value, Module)
  414. ),
  415. None,
  416. )
  417. if hasattr(module, "__version__"):
  418. ret.__version__ = module.__version__
  419. if ret is None:
  420. ret = module.register(module_name)
  421. if not isinstance(ret, Module):
  422. raise TypeError(f"Instance is not a Module, it is {type(ret)}")
  423. self.complete_registration(ret)
  424. ret.__origin__ = origin
  425. cls_name = ret.__class__.__name__
  426. if save_fs and "DYNO" not in os.environ:
  427. path = os.path.join(
  428. LOADED_MODULES_DIR,
  429. f"{cls_name}_{self.client.tg_id}.py",
  430. )
  431. if origin == "<string>":
  432. with open(path, "w") as f:
  433. f.write(spec.loader.data.decode("utf-8"))
  434. logger.debug(f"Saved {cls_name=} to {path=}")
  435. return ret
  436. def add_aliases(self, aliases: dict):
  437. """Saves aliases and applies them to <core>/<file> modules"""
  438. self.aliases.update(aliases)
  439. for alias, cmd in aliases.items():
  440. self.add_alias(alias, cmd)
  441. def register_commands(self, instance: Module):
  442. """Register commands from instance"""
  443. with contextlib.suppress(AttributeError):
  444. _hikka_client_id_logging_tag = copy.copy(self.client.tg_id)
  445. if getattr(instance, "__origin__", "") == "<core>":
  446. self._core_commands += list(map(lambda x: x.lower(), instance.commands))
  447. for command in instance.commands.copy():
  448. # Restrict overwriting core modules' commands
  449. if (
  450. command.lower() in self._core_commands
  451. and getattr(instance, "__origin__", "") != "<core>"
  452. ):
  453. with contextlib.suppress(Exception):
  454. self.modules.remove(instance)
  455. raise CoreOverwriteError(command=command)
  456. # Verify that command does not already exist, or,
  457. # if it does, the command must be from the same class name
  458. if command.lower() in self.commands:
  459. if (
  460. hasattr(instance.commands[command], "__self__")
  461. and hasattr(self.commands[command], "__self__")
  462. and instance.commands[command].__self__.__class__.__name__
  463. != self.commands[command].__self__.__class__.__name__
  464. ):
  465. logger.debug(f"Duplicate command {command}")
  466. logger.debug(f"Replacing command for {self.commands[command]}")
  467. if not instance.commands[command].__doc__:
  468. logger.debug(f"Missing docs for {command}")
  469. self.commands.update({command.lower(): instance.commands[command]})
  470. for alias, cmd in self.aliases.items():
  471. if cmd in instance.commands:
  472. self.add_alias(alias, cmd)
  473. for handler in instance.inline_handlers.copy():
  474. if handler.lower() in self.inline_handlers:
  475. if (
  476. hasattr(instance.inline_handlers[handler], "__self__")
  477. and hasattr(self.inline_handlers[handler], "__self__")
  478. and instance.inline_handlers[handler].__self__.__class__.__name__
  479. != self.inline_handlers[handler].__self__.__class__.__name__
  480. ):
  481. logger.debug(f"Duplicate inline_handler {handler}")
  482. logger.debug(
  483. f"Replacing inline_handler for {self.inline_handlers[handler]}"
  484. )
  485. if not instance.inline_handlers[handler].__doc__:
  486. logger.debug(f"Missing docs for {handler}")
  487. self.inline_handlers.update(
  488. {handler.lower(): instance.inline_handlers[handler]}
  489. )
  490. for handler in instance.callback_handlers.copy():
  491. if handler.lower() in self.callback_handlers and (
  492. hasattr(instance.callback_handlers[handler], "__self__")
  493. and hasattr(self.callback_handlers[handler], "__self__")
  494. and instance.callback_handlers[handler].__self__.__class__.__name__
  495. != self.callback_handlers[handler].__self__.__class__.__name__
  496. ):
  497. logger.debug(f"Duplicate callback_handler {handler}")
  498. self.callback_handlers.update(
  499. {handler.lower(): instance.callback_handlers[handler]}
  500. )
  501. def register_watcher(self, instance: Module):
  502. """Register watcher from instance"""
  503. with contextlib.suppress(AttributeError):
  504. _hikka_client_id_logging_tag = copy.copy(self.client.tg_id)
  505. with contextlib.suppress(AttributeError):
  506. if instance.watcher:
  507. for watcher in self.watchers:
  508. if (
  509. hasattr(watcher, "__self__")
  510. and watcher.__self__.__class__.__name__
  511. == instance.watcher.__self__.__class__.__name__
  512. ):
  513. logger.debug(f"Removing watcher for update {watcher}")
  514. self.watchers.remove(watcher)
  515. self.watchers += [instance.watcher]
  516. def _lookup(self, modname: str):
  517. return next(
  518. (lib for lib in self.libraries if lib.name.lower() == modname.lower()),
  519. False,
  520. ) or next(
  521. (
  522. mod
  523. for mod in self.modules
  524. if mod.__class__.__name__.lower() == modname.lower()
  525. or mod.name.lower() == modname.lower()
  526. ),
  527. False,
  528. )
  529. def complete_registration(self, instance: Module):
  530. """Complete registration of instance"""
  531. with contextlib.suppress(AttributeError):
  532. _hikka_client_id_logging_tag = copy.copy(self.client.tg_id)
  533. instance.allclients = self.allclients
  534. instance.allmodules = self
  535. instance.hikka = True
  536. instance.get = partial(self._mod_get, _module=instance)
  537. instance.set = partial(self._mod_set, _modname=instance.__class__.__name__)
  538. instance.get_prefix = partial(self._db.get, "hikka.main", "command_prefix", ".")
  539. instance.client = self.client
  540. instance._client = self.client
  541. instance.db = self._db
  542. instance._db = self._db
  543. instance.lookup = self._lookup
  544. instance.import_lib = self._mod_import_lib
  545. instance.tg_id = self.client.tg_id
  546. instance._tg_id = self.client.tg_id
  547. instance.animate = self._animate
  548. for module in self.modules:
  549. if module.__class__.__name__ == instance.__class__.__name__:
  550. if getattr(module, "__origin__", "") == "<core>":
  551. raise CoreOverwriteError(
  552. module=module.__class__.__name__[:-3]
  553. if module.__class__.__name__.endswith("Mod")
  554. else module.__class__.__name__
  555. )
  556. logger.debug(f"Removing module for update {module}")
  557. asyncio.ensure_future(module.on_unload())
  558. self.modules.remove(module)
  559. for method in dir(module):
  560. if isinstance(getattr(module, method), InfiniteLoop):
  561. getattr(module, method).stop()
  562. logger.debug(f"Stopped loop in {module=}, {method=}")
  563. self.modules += [instance]
  564. def _mod_get(
  565. self,
  566. key: str,
  567. default: Optional[Hashable] = None,
  568. _module: Module = None,
  569. ) -> Hashable:
  570. mod, legacy = _module.__class__.__name__, _module.strings["name"]
  571. if self._db.get(legacy, key, Placeholder) is not Placeholder:
  572. for iterkey, value in self._db[legacy].items():
  573. if iterkey == "__config__":
  574. # Config already uses classname as key
  575. # No need to migrate
  576. continue
  577. if isinstance(value, dict) and isinstance(
  578. self._db.get(mod, iterkey), dict
  579. ):
  580. self._db[mod][iterkey].update(value)
  581. else:
  582. self._db.set(mod, iterkey, value)
  583. logger.debug(f"Migrated {legacy} -> {mod}")
  584. del self._db[legacy]
  585. return self._db.get(mod, key, default)
  586. def _mod_set(self, key: str, value: Hashable, _modname: str = None) -> bool:
  587. return self._db.set(_modname, key, value)
  588. def _lib_get(
  589. self,
  590. key: str,
  591. default: Optional[Hashable] = None,
  592. _lib: Library = None,
  593. ) -> Hashable:
  594. return self._db.get(_lib.__class__.__name__, key, default)
  595. def _lib_set(self, key: str, value: Hashable, _lib: Library = None) -> bool:
  596. return self._db.set(_lib.__class__.__name__, key, value)
  597. async def _mod_import_lib(
  598. self,
  599. url: str,
  600. *,
  601. suspend_on_error: Optional[bool] = False,
  602. ) -> object:
  603. """
  604. Import library from url and register it in :obj:`Modules`
  605. :param url: Url to import
  606. :param suspend_on_error: Will raise :obj:`loader.SelfSuspend` if library can't be loaded
  607. :return: :obj:`Library`
  608. :raise: SelfUnload if :attr:`suspend_on_error` is True and error occurred
  609. :raise: HTTPError if library is not found
  610. :raise: ImportError if library doesn't have any class which is a subclass of :obj:`loader.Library`
  611. :raise: ImportError if library name doesn't end with `Lib`
  612. :raise: RuntimeError if library throws in :method:`init`
  613. :raise: RuntimeError if library classname exists in :obj:`Modules`.libraries
  614. """
  615. def _raise(e: Exception):
  616. if suspend_on_error:
  617. raise SelfSuspend("Required library is not available or is corrupted.")
  618. else:
  619. raise e
  620. if not utils.check_url(url):
  621. _raise(ValueError("Invalid url for library"))
  622. code = await utils.run_sync(requests.get, url)
  623. code.raise_for_status()
  624. code = code.text
  625. module = f"hikka.libraries.{url.replace('%', '%%').replace('.', '%d')}"
  626. origin = f"<library {url}>"
  627. spec = ModuleSpec(module, StringLoader(code, origin), origin=origin)
  628. instance = importlib.util.module_from_spec(spec)
  629. sys.modules[module] = instance
  630. spec.loader.exec_module(instance)
  631. lib_obj = next(
  632. (
  633. value()
  634. for value in vars(instance).values()
  635. if inspect.isclass(value) and issubclass(value, Library)
  636. ),
  637. None,
  638. )
  639. if not lib_obj:
  640. _raise(ImportError("Invalid library. No class found"))
  641. if not lib_obj.__class__.__name__.endswith("Lib"):
  642. _raise(ImportError("Invalid library. Class name must end with 'Lib'"))
  643. lib_obj.client = self.client
  644. lib_obj._client = self.client # skipcq
  645. lib_obj.db = self._db
  646. lib_obj._db = self._db # skipcq
  647. lib_obj.name = lib_obj.__class__.__name__
  648. lib_obj.source_url = url.strip("/")
  649. lib_obj.lookup = self._lookup
  650. lib_obj.tg_id = self.client.tg_id
  651. lib_obj.allmodules = self
  652. lib_obj._lib_get = partial(self._lib_get, _lib=lib_obj) # skipcq
  653. lib_obj._lib_set = partial(self._lib_set, _lib=lib_obj) # skipcq
  654. lib_obj.get_prefix = partial(self._db.get, "hikka.main", "command_prefix", ".")
  655. for old_lib in self.libraries:
  656. if old_lib.source_url == lib_obj.source_url and (
  657. not isinstance(getattr(old_lib, "version", None), tuple)
  658. and not isinstance(getattr(lib_obj, "version", None), tuple)
  659. or old_lib.version == lib_obj.version
  660. ):
  661. logging.debug(
  662. f"Using existing instance of library {old_lib.source_url}"
  663. )
  664. return old_lib
  665. new = True
  666. for old_lib in self.libraries:
  667. if old_lib.source_url == lib_obj.source_url:
  668. if hasattr(old_lib, "on_lib_update") and callable(
  669. old_lib.on_lib_update
  670. ):
  671. await old_lib.on_lib_update(lib_obj)
  672. replace_all_refs(old_lib, lib_obj)
  673. new = False
  674. logging.debug(
  675. "Replacing existing instance of library"
  676. f" {lib_obj.source_url} with updated object"
  677. )
  678. if hasattr(lib_obj, "init") and callable(lib_obj.init):
  679. try:
  680. await lib_obj.init()
  681. except Exception:
  682. _raise(RuntimeError("Library init() failed"))
  683. if hasattr(lib_obj, "config"):
  684. if not isinstance(lib_obj.config, LibraryConfig):
  685. _raise(
  686. RuntimeError("Library config must be a `LibraryConfig` instance")
  687. )
  688. libcfg = lib_obj.db.get(
  689. lib_obj.__class__.__name__,
  690. "__config__",
  691. {},
  692. )
  693. for conf in lib_obj.config.keys():
  694. with contextlib.suppress(Exception):
  695. lib_obj.config.set_no_raise(
  696. conf,
  697. (
  698. libcfg[conf]
  699. if conf in libcfg.keys()
  700. else os.environ.get(f"{lib_obj.__class__.__name__}.{conf}")
  701. or lib_obj.config.getdef(conf)
  702. ),
  703. )
  704. if hasattr(lib_obj, "strings"):
  705. lib_obj.strings = Strings(lib_obj, self._translator)
  706. lib_obj.translator = self._translator
  707. if new:
  708. self.libraries += [lib_obj]
  709. return lib_obj
  710. def dispatch(self, command: str) -> tuple:
  711. """Dispatch command to appropriate module"""
  712. change = str.maketrans(ru_keys + en_keys, en_keys + ru_keys)
  713. try:
  714. return command, self.commands[command.lower()]
  715. except KeyError:
  716. try:
  717. cmd = self.aliases[command.lower()]
  718. return cmd, self.commands[cmd.lower()]
  719. except KeyError:
  720. try:
  721. cmd = self.aliases[str.translate(command, change).lower()]
  722. return cmd, self.commands[cmd.lower()]
  723. except KeyError:
  724. try:
  725. cmd = str.translate(command, change).lower()
  726. return cmd, self.commands[cmd.lower()]
  727. except KeyError:
  728. return command, None
  729. def send_config(self, skip_hook: bool = False):
  730. """Configure modules"""
  731. for mod in self.modules:
  732. self.send_config_one(mod, skip_hook)
  733. def send_config_one(self, mod: "Module", skip_hook: bool = False):
  734. """Send config to single instance"""
  735. with contextlib.suppress(AttributeError):
  736. _hikka_client_id_logging_tag = copy.copy(self.client.tg_id)
  737. if hasattr(mod, "config"):
  738. modcfg = self._db.get(
  739. mod.__class__.__name__,
  740. "__config__",
  741. {},
  742. )
  743. try:
  744. for conf in mod.config.keys():
  745. with contextlib.suppress(validators.ValidationError):
  746. mod.config.set_no_raise(
  747. conf,
  748. (
  749. modcfg[conf]
  750. if conf in modcfg.keys()
  751. else os.environ.get(f"{mod.__class__.__name__}.{conf}")
  752. or mod.config.getdef(conf)
  753. ),
  754. )
  755. except AttributeError:
  756. logger.warning(
  757. "Got invalid config instance. Expected `ModuleConfig`, got"
  758. f" {type(mod.config)=}, {mod.config=}"
  759. )
  760. if skip_hook:
  761. return
  762. if not hasattr(mod, "name"):
  763. mod.name = mod.strings["name"]
  764. if hasattr(mod, "strings"):
  765. mod.strings = Strings(mod, self._translator)
  766. mod.translator = self._translator
  767. try:
  768. mod.config_complete()
  769. except Exception as e:
  770. logger.exception(f"Failed to send mod config complete signal due to {e}")
  771. raise
  772. async def send_ready(self):
  773. """Send all data to all modules"""
  774. # Init inline manager anyway, so the modules
  775. # can access its `init_complete`
  776. inline_manager = InlineManager(self.client, self._db, self)
  777. await inline_manager._register_manager()
  778. # We save it to `Modules` attribute, so not to re-init
  779. # it everytime module is loaded. Then we can just
  780. # re-assign it to all modules
  781. self.inline = inline_manager
  782. try:
  783. await asyncio.gather(*[self.send_ready_one(mod) for mod in self.modules])
  784. except Exception as e:
  785. logger.exception(f"Failed to send mod init complete signal due to {e}")
  786. async def _animate(
  787. self,
  788. message: Union[Message, InlineMessage],
  789. frames: List[str],
  790. interval: Union[float, int],
  791. *,
  792. inline: bool = False,
  793. ) -> None:
  794. """
  795. Animate message
  796. :param message: Message to animate
  797. :param frames: A List of strings which are the frames of animation
  798. :param interval: Animation delay
  799. :param inline: Whether to use inline bot for animation
  800. :returns message:
  801. Please, note that if you set `inline=True`, first frame will be shown with an empty
  802. button due to the limitations of Telegram API
  803. """
  804. with contextlib.suppress(AttributeError):
  805. _hikka_client_id_logging_tag = copy.copy(self.client.tg_id)
  806. if interval < 0.1:
  807. logger.warning(
  808. "Resetting animation interval to 0.1s, because it may get you in"
  809. " floodwaits bro"
  810. )
  811. interval = 0.1
  812. for frame in frames:
  813. if isinstance(message, Message):
  814. if inline:
  815. message = await self.inline.form(
  816. message=message,
  817. text=frame,
  818. reply_markup={"text": "\u0020\u2800", "data": "empty"},
  819. )
  820. else:
  821. message = await utils.answer(message, frame)
  822. elif isinstance(message, InlineMessage) and inline:
  823. await message.edit(frame)
  824. await asyncio.sleep(interval)
  825. return message
  826. async def send_ready_one(
  827. self,
  828. mod: Module,
  829. no_self_unload: bool = False,
  830. from_dlmod: bool = False,
  831. ):
  832. with contextlib.suppress(AttributeError):
  833. _hikka_client_id_logging_tag = copy.copy(self.client.tg_id)
  834. mod.inline = self.inline
  835. for method in dir(mod):
  836. if isinstance(getattr(mod, method), InfiniteLoop):
  837. setattr(getattr(mod, method), "module_instance", mod)
  838. if getattr(mod, method).autostart:
  839. getattr(mod, method).start()
  840. logger.debug(f"Added {mod=} to {method=}")
  841. if from_dlmod:
  842. try:
  843. await mod.on_dlmod(self.client, self._db)
  844. except Exception:
  845. logger.info("Can't process `on_dlmod` hook", exc_info=True)
  846. try:
  847. await mod.client_ready(self.client, self._db)
  848. except SelfUnload as e:
  849. if no_self_unload:
  850. raise e
  851. logger.debug(f"Unloading {mod}, because it raised SelfUnload")
  852. self.modules.remove(mod)
  853. except SelfSuspend as e:
  854. if no_self_unload:
  855. raise e
  856. logger.debug(f"Suspending {mod}, because it raised SelfSuspend")
  857. return
  858. except Exception as e:
  859. logger.exception(
  860. f"Failed to send mod init complete signal for {mod} due to {e},"
  861. " attempting unload"
  862. )
  863. self.modules.remove(mod)
  864. raise
  865. if not hasattr(mod, "commands"):
  866. mod.commands = get_commands(mod)
  867. if not hasattr(mod, "inline_handlers"):
  868. mod.inline_handlers = get_inline_handlers(mod)
  869. if not hasattr(mod, "callback_handlers"):
  870. mod.callback_handlers = get_callback_handlers(mod)
  871. self.register_commands(mod)
  872. self.register_watcher(mod)
  873. def get_classname(self, name: str) -> str:
  874. return next(
  875. (
  876. module.__class__.__module__
  877. for module in reversed(self.modules)
  878. if name in (module.name, module.__class__.__module__)
  879. ),
  880. name,
  881. )
  882. def unload_module(self, classname: str) -> bool:
  883. """Remove module and all stuff from it"""
  884. worked = []
  885. to_remove = []
  886. with contextlib.suppress(AttributeError):
  887. _hikka_client_id_logging_tag = copy.copy(self.client.tg_id)
  888. for module in self.modules:
  889. if classname.lower() in (
  890. module.name.lower(),
  891. module.__class__.__name__.lower(),
  892. ):
  893. if getattr(module, "__origin__", "") == "<core>":
  894. raise RuntimeError("You can't unload core module")
  895. worked += [module.__class__.__name__]
  896. name = module.__class__.__name__
  897. if "DYNO" not in os.environ:
  898. path = os.path.join(
  899. LOADED_MODULES_DIR,
  900. f"{name}_{self.client.tg_id}.py",
  901. )
  902. if os.path.isfile(path):
  903. os.remove(path)
  904. logger.debug(f"Removed {name} file at {path=}")
  905. logger.debug(f"Removing module for unload {module}")
  906. self.modules.remove(module)
  907. asyncio.ensure_future(module.on_unload())
  908. for method in dir(module):
  909. if isinstance(getattr(module, method), InfiniteLoop):
  910. getattr(module, method).stop()
  911. logger.debug(f"Stopped loop in {module=}, {method=}")
  912. to_remove += (
  913. module.commands
  914. if isinstance(getattr(module, "commands", None), dict)
  915. else {}
  916. ).values()
  917. if hasattr(module, "watcher"):
  918. to_remove += [module.watcher]
  919. logger.debug(f"{to_remove=}, {worked=}")
  920. for watcher in self.watchers.copy():
  921. if watcher in to_remove:
  922. logger.debug(f"Removing {watcher=} for unload")
  923. self.watchers.remove(watcher)
  924. aliases_to_remove = []
  925. for name, command in self.commands.copy().items():
  926. if command in to_remove:
  927. logger.debug(f"Removing {command=} for unload")
  928. del self.commands[name]
  929. aliases_to_remove.append(name)
  930. for alias, command in self.aliases.copy().items():
  931. if command in aliases_to_remove:
  932. del self.aliases[alias]
  933. return worked
  934. def add_alias(self, alias, cmd):
  935. """Make an alias"""
  936. if cmd not in self.commands:
  937. return False
  938. self.aliases[alias.lower().strip()] = cmd
  939. return True
  940. def remove_alias(self, alias):
  941. """Remove an alias"""
  942. try:
  943. del self.aliases[alias.lower().strip()]
  944. except KeyError:
  945. return False
  946. return True
  947. async def log(
  948. self,
  949. type_,
  950. *,
  951. group=None,
  952. affected_uids=None,
  953. data=None,
  954. ):
  955. return await asyncio.gather(
  956. *[fun(type_, group, affected_uids, data) for fun in self._log_handlers]
  957. )
  958. def register_logger(self, _logger):
  959. self._log_handlers += [_logger]