test.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  1. # █ █ ▀ █▄▀ ▄▀█ █▀█ ▀
  2. # █▀█ █ █ █ █▀█ █▀▄ █
  3. # © Copyright 2022
  4. # https://t.me/hikariatama
  5. #
  6. # 🔒 Licensed under the GNU AGPLv3
  7. # 🌐 https://www.gnu.org/licenses/agpl-3.0.html
  8. # scope: inline
  9. import inspect
  10. import logging
  11. import os
  12. import random
  13. import time
  14. from io import BytesIO
  15. from typing import Union
  16. from telethon.tl.functions.channels import EditAdminRequest, InviteToChannelRequest
  17. from telethon.tl.types import ChatAdminRights, Message
  18. from .. import loader, main, utils
  19. from ..inline.types import InlineCall
  20. logger = logging.getLogger(__name__)
  21. if "DYNO" not in os.environ:
  22. DEBUG_MODS_DIR = os.path.join(utils.get_base_dir(), "debug_modules")
  23. if not os.path.isdir(DEBUG_MODS_DIR):
  24. os.mkdir(DEBUG_MODS_DIR, mode=0o755)
  25. for mod in os.scandir(DEBUG_MODS_DIR):
  26. os.remove(mod.path)
  27. @loader.tds
  28. class TestMod(loader.Module):
  29. """Perform operations based on userbot self-testing"""
  30. _memory = {}
  31. strings = {
  32. "name": "Tester",
  33. "set_loglevel": "🚫 <b>Please specify verbosity as an integer or string</b>",
  34. "no_logs": "ℹ️ <b>You don't have any logs at verbosity {}.</b>",
  35. "logs_filename": "hikka-logs.txt",
  36. "logs_caption": (
  37. "🌘 <b>Hikka logs with verbosity </b><code>{}</code>\n\n👩‍🎤 <b>Hikka"
  38. " version: {}.{}.{}</b>{}\n⏱ <b>Uptime:"
  39. " {}</b>\n<b>{}</b>\n\n<b>{} NoNick</b>\n<b>{} Grep</b>\n<b>{}"
  40. " InlineLogs</b>"
  41. ),
  42. "suspend_invalid_time": "🚫 <b>Invalid time to suspend</b>",
  43. "suspended": "🥶 <b>Bot suspended for</b> <code>{}</code> <b>seconds</b>",
  44. "results_ping": (
  45. "⏱ <b>Telegram ping:</b> <code>{}</code> <b>ms</b>\n👩‍💼 <b>Uptime: {}</b>"
  46. ),
  47. "ping_hint": (
  48. "💡 <i>Telegram ping mostly depends on Telegram servers latency and other"
  49. " external factors and has nothing to do with the parameters of server on"
  50. " which userbot is installed</i>"
  51. ),
  52. "confidential": (
  53. "⚠️ <b>Log level </b><code>{}</code><b> may reveal your confidential info,"
  54. " be careful</b>"
  55. ),
  56. "confidential_text": (
  57. "⚠️ <b>Log level </b><code>{0}</code><b> may reveal your confidential info,"
  58. " be careful</b>\n<b>Type </b><code>.logs {0} force_insecure</code><b> to"
  59. " ignore this warning</b>"
  60. ),
  61. "choose_loglevel": "💁‍♂️ <b>Choose log level</b>",
  62. "bad_module": "🚫 <b>Module not found</b>",
  63. "debugging_enabled": (
  64. "🧑‍💻 <b>Debugging mode enabled for module </b><code>{0}</code>\n<i>Go to"
  65. " directory named `debug_modules`, edit file named `{0}.py` and see changes"
  66. " in real time</i>"
  67. ),
  68. "debugging_disabled": "✅ <b>Debugging disabled</b>",
  69. "heroku_debug": "🚫 <b>Debugging is not available on Heroku</b>",
  70. }
  71. strings_ru = {
  72. "set_loglevel": "🚫 <b>Укажи уровень логов числом или строкой</b>",
  73. "no_logs": "ℹ️ <b>У тебя нет логов уровня {}.</b>",
  74. "logs_filename": "hikka-logs.txt",
  75. "logs_caption": (
  76. "🌘 <b>Логи Hikka уровня </b><code>{}</code>\n\n👩‍🎤 <b>Версия Hikka:"
  77. " {}.{}.{}</b>{}\n⏱ <b>Uptime: {}</b>\n<b>{}</b>\n\n<b>{}"
  78. " NoNick</b>\n<b>{} Grep</b>\n<b>{} InlineLogs</b>"
  79. ),
  80. "bad_module": "🚫 <b>Модуль не найден</b>",
  81. "debugging_enabled": (
  82. "🧑‍💻 <b>Режим разработчика включен для модуля"
  83. " </b><code>{0}</code>\n<i>Отправляйся в директорию `debug_modules`,"
  84. " изменяй файл `{0}.py`, и смотри изменения в режиме реального времени</i>"
  85. ),
  86. "debugging_disabled": "✅ <b>Режим разработчика выключен</b>",
  87. "suspend_invalid_time": "🚫 <b>Неверное время заморозки</b>",
  88. "suspended": "🥶 <b>Бот заморожен на</b> <code>{}</code> <b>секунд</b>",
  89. "results_ping": (
  90. "⏱ <b>Скорость отклика Telegram:</b> <code>{}</code> <b>ms</b>\n👩‍💼"
  91. " <b>Прошло с последней перезагрузки: {}</b>"
  92. ),
  93. "ping_hint": (
  94. "💡 <i>Скорость отклика Telegram в большей степени зависит от загруженности"
  95. " серверов Telegram и других внешних факторов и никак не связана с"
  96. " параметрами сервера, на который установлен юзербот</i>"
  97. ),
  98. "confidential": (
  99. "⚠️ <b>Уровень логов </b><code>{}</code><b> может содержать личную"
  100. " информацию, будь осторожен</b>"
  101. ),
  102. "confidential_text": (
  103. "⚠️ <b>Уровень логов </b><code>{0}</code><b> может содержать личную"
  104. " информацию, будь осторожен</b>\n<b>Напиши </b><code>.logs {0}"
  105. " force_insecure</code><b>, чтобы отправить логи игнорируя"
  106. " предупреждение</b>"
  107. ),
  108. "choose_loglevel": "💁‍♂️ <b>Выбери уровень логов</b>",
  109. "_cmd_doc_dump": "Показать информацию о сообщении",
  110. "_cmd_doc_logs": (
  111. "<уровень> - Отправляет лог-файл. Уровни ниже WARNING могут содержать"
  112. " личную инфомрацию."
  113. ),
  114. "_cmd_doc_suspend": "<время> - Заморозить бота на некоторое время",
  115. "_cmd_doc_ping": "Проверяет скорость отклика юзербота",
  116. "_cls_doc": "Операции, связанные с самотестированием",
  117. "heroku_debug": "🚫 <b>Режим разработчика не доступен на Heroku</b>",
  118. }
  119. def __init__(self):
  120. self.config = loader.ModuleConfig(
  121. loader.ConfigValue(
  122. "force_send_all",
  123. False,
  124. "Forcefully send logs to all clients, aka do not split logs "
  125. "to <mine> and <not-mine>. Restart required after setting",
  126. validator=loader.validators.Boolean(),
  127. )
  128. )
  129. logging.getLogger().handlers[0].force_send_all = self.config["force_send_all"]
  130. async def dumpcmd(self, message: Message):
  131. """Use in reply to get a dump of a message"""
  132. if not message.is_reply:
  133. return
  134. await utils.answer(
  135. message,
  136. "<code>"
  137. + utils.escape_html((await message.get_reply_message()).stringify())
  138. + "</code>",
  139. )
  140. @loader.loop(interval=1)
  141. async def watchdog(self):
  142. try:
  143. for module in os.scandir(DEBUG_MODS_DIR):
  144. last_modified = os.stat(module.path).st_mtime
  145. cls_ = module.path.split("/")[-1].split(".py")[0]
  146. if cls_ not in self._memory:
  147. self._memory[cls_] = last_modified
  148. continue
  149. if self._memory[cls_] == last_modified:
  150. continue
  151. self._memory[cls_] = last_modified
  152. logger.debug(f"Reloading debug module {cls_}")
  153. with open(module.path, "r") as f:
  154. try:
  155. await next(
  156. module
  157. for module in self.allmodules.modules
  158. if module.__class__.__name__ == "LoaderMod"
  159. ).load_module(
  160. f.read(),
  161. None,
  162. save_fs=False,
  163. )
  164. except Exception:
  165. logger.exception("Failed to reload module in watchdog")
  166. except Exception:
  167. logger.exception("Failed debugging watchdog")
  168. return
  169. async def debugmodcmd(self, message: Message):
  170. """[module] - For developers: Open module for debugging
  171. You will be able to track changes in real-time"""
  172. if "DYNO" in os.environ:
  173. await utils.answer(message, self.strings("heroku_debug"))
  174. return
  175. args = utils.get_args_raw(message)
  176. instance = None
  177. for module in self.allmodules.modules:
  178. if (
  179. module.__class__.__name__.lower() == args.lower()
  180. or module.strings["name"].lower() == args.lower()
  181. ):
  182. if os.path.isfile(
  183. os.path.join(
  184. DEBUG_MODS_DIR,
  185. f"{module.__class__.__name__}.py",
  186. )
  187. ):
  188. os.remove(
  189. os.path.join(
  190. DEBUG_MODS_DIR,
  191. f"{module.__class__.__name__}.py",
  192. )
  193. )
  194. try:
  195. delattr(module, "hikka_debug")
  196. except AttributeError:
  197. pass
  198. await utils.answer(message, self.strings("debugging_disabled"))
  199. return
  200. module.hikka_debug = True
  201. instance = module
  202. break
  203. if not instance:
  204. await utils.answer(message, self.strings("bad_module"))
  205. return
  206. with open(
  207. os.path.join(
  208. DEBUG_MODS_DIR,
  209. f"{instance.__class__.__name__}.py",
  210. ),
  211. "wb",
  212. ) as f:
  213. f.write(inspect.getmodule(instance).__loader__.data)
  214. await utils.answer(
  215. message,
  216. self.strings("debugging_enabled").format(instance.__class__.__name__),
  217. )
  218. async def logscmd(
  219. self,
  220. message: Union[Message, InlineCall],
  221. force: bool = False,
  222. lvl: Union[int, None] = None,
  223. ):
  224. """<level> - Dumps logs. Loglevels below WARNING may contain personal info."""
  225. if not isinstance(lvl, int):
  226. args = utils.get_args_raw(message)
  227. try:
  228. try:
  229. lvl = int(args.split()[0])
  230. except ValueError:
  231. lvl = getattr(logging, args.split()[0].upper(), None)
  232. except IndexError:
  233. lvl = None
  234. if not isinstance(lvl, int):
  235. try:
  236. if not self.inline.init_complete or not await self.inline.form(
  237. text=self.strings("choose_loglevel"),
  238. reply_markup=[
  239. [
  240. {
  241. "text": "🚨 Critical",
  242. "callback": self.logscmd,
  243. "args": (False, 50),
  244. },
  245. {
  246. "text": "🚫 Error",
  247. "callback": self.logscmd,
  248. "args": (False, 40),
  249. },
  250. ],
  251. [
  252. {
  253. "text": "⚠️ Warning",
  254. "callback": self.logscmd,
  255. "args": (False, 30),
  256. },
  257. {
  258. "text": "ℹ️ Info",
  259. "callback": self.logscmd,
  260. "args": (False, 20),
  261. },
  262. ],
  263. [
  264. {
  265. "text": "🧑‍💻 Debug",
  266. "callback": self.logscmd,
  267. "args": (False, 10),
  268. },
  269. {
  270. "text": "👁 All",
  271. "callback": self.logscmd,
  272. "args": (False, 0),
  273. },
  274. ],
  275. [{"text": "🚫 Cancel", "action": "close"}],
  276. ],
  277. message=message,
  278. ):
  279. raise
  280. except Exception:
  281. await utils.answer(message, self.strings("set_loglevel"))
  282. return
  283. logs = "\n\n".join(
  284. [
  285. "\n".join(
  286. handler.dumps(lvl, client_id=self._client.tg_id)
  287. if "client_id" in inspect.signature(handler.dumps).parameters
  288. else handler.dumps(lvl)
  289. )
  290. for handler in logging.getLogger().handlers
  291. ]
  292. )
  293. named_lvl = (
  294. lvl
  295. if lvl not in logging._levelToName
  296. else logging._levelToName[lvl] # skipcq: PYL-W0212
  297. )
  298. if (
  299. lvl < logging.WARNING
  300. and not force
  301. and (
  302. not isinstance(message, Message)
  303. or "force_insecure" not in message.raw_text.lower()
  304. )
  305. ):
  306. try:
  307. if not self.inline.init_complete:
  308. raise
  309. cfg = {
  310. "text": self.strings("confidential").format(named_lvl),
  311. "reply_markup": [
  312. {
  313. "text": "📤 Send anyway",
  314. "callback": self.logscmd,
  315. "args": [True, lvl],
  316. },
  317. {"text": "🚫 Cancel", "action": "close"},
  318. ],
  319. }
  320. if isinstance(message, Message):
  321. if not await self.inline.form(**cfg, message=message):
  322. raise
  323. else:
  324. await message.edit(**cfg)
  325. except Exception:
  326. await utils.answer(
  327. message,
  328. self.strings("confidential_text").format(named_lvl),
  329. )
  330. return
  331. if len(logs) <= 2:
  332. if isinstance(message, Message):
  333. await utils.answer(message, self.strings("no_logs").format(named_lvl))
  334. else:
  335. await message.edit(self.strings("no_logs").format(named_lvl))
  336. await message.unload()
  337. return
  338. if btoken := self._db.get("hikka.inline", "bot_token", False):
  339. logs = logs.replace(
  340. btoken,
  341. f'{btoken.split(":")[0]}:***************************',
  342. )
  343. if hikka_token := self._db.get("HikkaDL", "token", False):
  344. logs = logs.replace(
  345. hikka_token,
  346. f'{hikka_token.split("_")[0]}_********************************',
  347. )
  348. if hikka_token := self._db.get("Kirito", "token", False):
  349. logs = logs.replace(
  350. hikka_token,
  351. f'{hikka_token.split("_")[0]}_********************************',
  352. )
  353. if os.environ.get("DATABASE_URL"):
  354. logs = logs.replace(
  355. os.environ.get("DATABASE_URL"),
  356. "postgre://**************************",
  357. )
  358. if os.environ.get("REDIS_URL"):
  359. logs = logs.replace(
  360. os.environ.get("REDIS_URL"),
  361. "postgre://**************************",
  362. )
  363. if os.environ.get("hikka_session"):
  364. logs = logs.replace(
  365. os.environ.get("hikka_session"),
  366. "StringSession(**************************)",
  367. )
  368. logs = BytesIO(logs.encode("utf-16"))
  369. logs.name = self.strings("logs_filename")
  370. ghash = utils.get_git_hash()
  371. other = (
  372. *main.__version__,
  373. " <i><a"
  374. f' href="https://github.com/hikariatama/Hikka/commit/{ghash}">({ghash[:8]})</a></i>'
  375. if ghash
  376. else "",
  377. utils.formatted_uptime(),
  378. utils.get_named_platform(),
  379. "✅" if self._db.get(main.__name__, "no_nickname", False) else "🚫",
  380. "✅" if self._db.get(main.__name__, "grep", False) else "🚫",
  381. "✅" if self._db.get(main.__name__, "inlinelogs", False) else "🚫",
  382. )
  383. if getattr(message, "out", True):
  384. await message.delete()
  385. if isinstance(message, Message):
  386. await utils.answer(
  387. message,
  388. logs,
  389. caption=self.strings("logs_caption").format(named_lvl, *other),
  390. )
  391. else:
  392. await self._client.send_file(
  393. message.form["chat"],
  394. logs,
  395. caption=self.strings("logs_caption").format(named_lvl, *other),
  396. )
  397. @loader.owner
  398. async def suspendcmd(self, message: Message):
  399. """<time> - Suspends the bot for N seconds"""
  400. try:
  401. time_sleep = float(utils.get_args_raw(message))
  402. await utils.answer(
  403. message,
  404. self.strings("suspended").format(time_sleep),
  405. )
  406. time.sleep(time_sleep)
  407. except ValueError:
  408. await utils.answer(message, self.strings("suspend_invalid_time"))
  409. async def pingcmd(self, message: Message):
  410. """Test your userbot ping"""
  411. start = time.perf_counter_ns()
  412. message = await utils.answer(message, "<code>🐻 Nofin...</code>")
  413. await utils.answer(
  414. message,
  415. self.strings("results_ping").format(
  416. round((time.perf_counter_ns() - start) / 10**6, 3),
  417. utils.formatted_uptime(),
  418. )
  419. + (
  420. ("\n\n" + self.strings("ping_hint"))
  421. if random.choice([0, 0, 1]) == 1
  422. else ""
  423. ),
  424. )
  425. async def client_ready(self, *_):
  426. chat, is_new = await utils.asset_channel(
  427. self._client,
  428. "hikka-logs",
  429. "🌘 Your Hikka logs will appear in this chat",
  430. silent=True,
  431. avatar="https://github.com/hikariatama/assets/raw/master/hikka-logs.png",
  432. )
  433. self._logchat = int(f"-100{chat.id}")
  434. if "DYNO" not in os.environ:
  435. self.watchdog.start()
  436. if not is_new and any(
  437. participant.id == self.inline.bot_id
  438. for participant in (await self._client.get_participants(chat, limit=3))
  439. ):
  440. logging.getLogger().handlers[0].install_tg_log(self)
  441. logger.debug(f"Bot logging installed for {self._logchat}")
  442. return
  443. logger.debug("New logging chat created, init setup...")
  444. try:
  445. await self._client(InviteToChannelRequest(chat, [self.inline.bot_username]))
  446. except Exception:
  447. logger.warning("Unable to invite logger to chat")
  448. try:
  449. await self._client(
  450. EditAdminRequest(
  451. channel=chat,
  452. user_id=self.inline.bot_username,
  453. admin_rights=ChatAdminRights(ban_users=True),
  454. rank="Logger",
  455. )
  456. )
  457. except Exception:
  458. pass
  459. logging.getLogger().handlers[0].install_tg_log(self)
  460. logger.debug(f"Bot logging installed for {self._logchat}")