loader.py 54 KB

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