events.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  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. import inspect
  9. import logging
  10. import re
  11. from asyncio import Event
  12. from typing import List
  13. from aiogram.types import CallbackQuery, ChosenInlineResult
  14. from aiogram.types import InlineQuery as AiogramInlineQuery
  15. from aiogram.types import (
  16. InlineQueryResultArticle,
  17. InlineQueryResultDocument,
  18. InlineQueryResultGif,
  19. InlineQueryResultPhoto,
  20. InlineQueryResultVideo,
  21. InputTextMessageContent,
  22. )
  23. from aiogram.types import Message as AiogramMessage
  24. from .. import utils
  25. from .types import InlineCall, InlineQuery, InlineUnit, BotInlineCall
  26. logger = logging.getLogger(__name__)
  27. class Events(InlineUnit):
  28. async def _message_handler(self, message: AiogramMessage):
  29. """Processes incoming messages"""
  30. if message.chat.type != "private" or message.text == "/start hikka init":
  31. return
  32. for mod in self._allmodules.modules:
  33. if (
  34. not hasattr(mod, "aiogram_watcher")
  35. or message.text == "/start"
  36. and mod.__class__.__name__ != "InlineStuffMod"
  37. ):
  38. continue
  39. try:
  40. await mod.aiogram_watcher(message)
  41. except BaseException:
  42. logger.exception("Error on running aiogram watcher!")
  43. async def _inline_handler(self, inline_query: AiogramInlineQuery):
  44. """Inline query handler (forms' calls)"""
  45. # Retrieve query from passed object
  46. query = inline_query.query
  47. # If we didn't get any query, return help
  48. if not query:
  49. await self._query_help(inline_query)
  50. return
  51. # First, dispatch all registered inline handlers
  52. cmd = inline_query.query.split()[0].lower()
  53. if (
  54. cmd in self._allmodules.inline_handlers
  55. and await self.check_inline_security(
  56. func=self._allmodules.inline_handlers[cmd],
  57. user=inline_query.from_user.id,
  58. )
  59. ):
  60. instance = InlineQuery(inline_query)
  61. try:
  62. result = await self._allmodules.inline_handlers[cmd](instance)
  63. except BaseException:
  64. logger.exception("Error on running inline watcher!")
  65. return
  66. if not result:
  67. return
  68. if isinstance(result, dict):
  69. result = [result]
  70. if not isinstance(result, list):
  71. logger.error(
  72. "Got invalid type from inline handler. It must be `dict`, got"
  73. f" `{type(result)}`"
  74. )
  75. await instance.e500()
  76. return
  77. for res in result:
  78. mandatory = {"message", "photo", "gif", "video", "file"}
  79. if all(item not in res for item in mandatory):
  80. logger.error(
  81. "Got invalid type from inline handler. It must contain one of"
  82. f" `{mandatory}`"
  83. )
  84. await instance.e500()
  85. return
  86. if "file" in res and "mime_type" not in res:
  87. logger.error(
  88. "Got invalid type from inline handler. It contains field"
  89. " `file`, so it must contain `mime_type` as well"
  90. )
  91. inline_result = []
  92. for res in result:
  93. if "message" in res:
  94. inline_result += [
  95. InlineQueryResultArticle(
  96. id=utils.rand(20),
  97. title=res["title"],
  98. description=res.get("description"),
  99. input_message_content=InputTextMessageContent(
  100. res["message"],
  101. "HTML",
  102. disable_web_page_preview=True,
  103. ),
  104. thumb_url=res.get("thumb"),
  105. thumb_width=128,
  106. thumb_height=128,
  107. reply_markup=self.generate_markup(res.get("reply_markup")),
  108. )
  109. ]
  110. elif "photo" in res:
  111. inline_result += [
  112. InlineQueryResultPhoto(
  113. id=utils.rand(20),
  114. title=res.get("title"),
  115. description=res.get("description"),
  116. caption=res.get("caption"),
  117. parse_mode="HTML",
  118. thumb_url=res.get("thumb", res["photo"]),
  119. photo_url=res["photo"],
  120. reply_markup=self.generate_markup(res.get("reply_markup")),
  121. )
  122. ]
  123. elif "gif" in res:
  124. inline_result += [
  125. InlineQueryResultGif(
  126. id=utils.rand(20),
  127. title=res.get("title"),
  128. caption=res.get("caption"),
  129. parse_mode="HTML",
  130. thumb_url=res.get("thumb", res["gif"]),
  131. gif_url=res["gif"],
  132. reply_markup=self.generate_markup(res.get("reply_markup")),
  133. )
  134. ]
  135. elif "video" in res:
  136. inline_result += [
  137. InlineQueryResultVideo(
  138. id=utils.rand(20),
  139. title=res.get("title"),
  140. description=res.get("description"),
  141. caption=res.get("caption"),
  142. parse_mode="HTML",
  143. thumb_url=res.get("thumb", res["video"]),
  144. video_url=res["video"],
  145. mime_type="video/mp4",
  146. reply_markup=self.generate_markup(res.get("reply_markup")),
  147. )
  148. ]
  149. elif "file" in res:
  150. inline_result += [
  151. InlineQueryResultDocument(
  152. id=utils.rand(20),
  153. title=res.get("title"),
  154. description=res.get("description"),
  155. caption=res.get("caption"),
  156. parse_mode="HTML",
  157. thumb_url=res.get("thumb", res["file"]),
  158. document_url=res["file"],
  159. mime_type=res["mime_type"],
  160. reply_markup=self.generate_markup(res.get("reply_markup")),
  161. )
  162. ]
  163. try:
  164. await inline_query.answer(inline_result, cache_time=0)
  165. except Exception:
  166. logger.exception(
  167. f"Exception when answering inline query with result from {cmd}"
  168. )
  169. return
  170. await self._form_inline_handler(inline_query)
  171. await self._gallery_inline_handler(inline_query)
  172. await self._list_inline_handler(inline_query)
  173. async def _callback_query_handler(
  174. self,
  175. call: CallbackQuery,
  176. reply_markup: List[List[dict]] = None,
  177. ):
  178. """Callback query handler (buttons' presses)"""
  179. if reply_markup is None:
  180. reply_markup = []
  181. if re.search(r"authorize_web_(.{8})", call.data):
  182. self._web_auth_tokens += [re.search(r"authorize_web_(.{8})", call.data)[1]]
  183. return
  184. # First, dispatch all registered callback handlers
  185. for func in self._allmodules.callback_handlers.values():
  186. if await self.check_inline_security(func=func, user=call.from_user.id):
  187. try:
  188. await func(
  189. (
  190. BotInlineCall
  191. if getattr(getattr(call, "message", None), "chat", None)
  192. else InlineCall
  193. )(call, self, None)
  194. )
  195. except Exception:
  196. logger.exception("Error on running callback watcher!")
  197. await call.answer(
  198. "Error occured while processing request. More info in logs",
  199. show_alert=True,
  200. )
  201. continue
  202. for unit_id, unit in self._units.copy().items():
  203. for button in utils.array_sum(unit.get("buttons", [])):
  204. if not isinstance(button, dict):
  205. logger.warning(
  206. f"Can't process update, because of corrupted button: {button}"
  207. )
  208. continue
  209. if button.get("_callback_data") == call.data:
  210. if (
  211. button.get("disable_security", False)
  212. or unit.get("disable_security", False)
  213. or (
  214. unit.get("force_me", False)
  215. and call.from_user.id == self._me
  216. )
  217. or not unit.get("force_me", False)
  218. and (
  219. await self.check_inline_security(
  220. func=unit.get(
  221. "perms_map",
  222. lambda: self._client.dispatcher.security._default,
  223. )(), # we call it so we can get reloaded rights in runtime
  224. user=call.from_user.id,
  225. )
  226. if "message" in unit
  227. else False
  228. )
  229. ):
  230. pass
  231. elif (
  232. call.from_user.id
  233. not in self._client.dispatcher.security._owner
  234. + unit.get("always_allow", [])
  235. + button.get("always_allow", [])
  236. ):
  237. await call.answer("You are not allowed to press this button!")
  238. return
  239. try:
  240. result = await button["callback"](
  241. (
  242. BotInlineCall
  243. if getattr(getattr(call, "message", None), "chat", None)
  244. else InlineCall
  245. )(call, self, unit_id),
  246. *button.get("args", []),
  247. **button.get("kwargs", {}),
  248. )
  249. except Exception:
  250. logger.exception("Error on running callback watcher!")
  251. await call.answer(
  252. "Error occurred while "
  253. "processing request. "
  254. "More info in logs",
  255. show_alert=True,
  256. )
  257. return
  258. return result
  259. if call.data in self._custom_map:
  260. if (
  261. self._custom_map[call.data].get("disable_security", False)
  262. or (
  263. self._custom_map[call.data].get("force_me", False)
  264. and call.from_user.id == self._me
  265. )
  266. or not self._custom_map[call.data].get("force_me", False)
  267. and (
  268. await self.check_inline_security(
  269. func=self._custom_map[call.data].get(
  270. "perms_map",
  271. lambda: self._client.dispatcher.security._default,
  272. )(),
  273. user=call.from_user.id,
  274. )
  275. if "message" in self._custom_map[call.data]
  276. else False
  277. )
  278. ):
  279. pass
  280. elif (
  281. call.from_user.id not in self._client.dispatcher.security._owner
  282. and call.from_user.id
  283. not in self._custom_map[call.data].get("always_allow", [])
  284. ):
  285. await call.answer("You are not allowed to press this button!")
  286. return
  287. await self._custom_map[call.data]["handler"](
  288. (
  289. BotInlineCall
  290. if getattr(getattr(call, "message", None), "chat", None)
  291. else InlineCall
  292. )(call, self, None),
  293. *self._custom_map[call.data].get("args", []),
  294. **self._custom_map[call.data].get("kwargs", {}),
  295. )
  296. return
  297. async def _chosen_inline_handler(
  298. self,
  299. chosen_inline_query: ChosenInlineResult,
  300. ):
  301. query = chosen_inline_query.query
  302. if not query:
  303. return
  304. for unit_id, unit in self._units.items():
  305. if (
  306. unit_id == query
  307. and "future" in unit
  308. and isinstance(unit["future"], Event)
  309. ):
  310. unit["inline_message_id"] = chosen_inline_query.inline_message_id
  311. unit["future"].set()
  312. return
  313. for unit_id, unit in self._units.copy().items():
  314. for button in utils.array_sum(unit.get("buttons", [])):
  315. if (
  316. "_switch_query" in button
  317. and "input" in button
  318. and button["_switch_query"] == query.split()[0]
  319. and chosen_inline_query.from_user.id
  320. in [self._me]
  321. + self._client.dispatcher.security._owner
  322. + unit.get("always_allow", [])
  323. ):
  324. query = query.split(maxsplit=1)[1] if len(query.split()) > 1 else ""
  325. try:
  326. return await button["handler"](
  327. InlineCall(chosen_inline_query, self, unit_id),
  328. query,
  329. *button.get("args", []),
  330. **button.get("kwargs", {}),
  331. )
  332. except Exception:
  333. logger.exception(
  334. "Exception while running chosen query watcher!"
  335. )
  336. return
  337. async def _query_help(self, inline_query: InlineQuery):
  338. _help = ""
  339. for name, fun in self._allmodules.inline_handlers.items():
  340. # If user doesn't have enough permissions
  341. # to run this inline command, do not show it
  342. # in help
  343. if not await self.check_inline_security(
  344. func=fun,
  345. user=inline_query.from_user.id,
  346. ):
  347. continue
  348. # Retrieve docs from func
  349. try:
  350. doc = utils.escape_html(inspect.getdoc(fun))
  351. except Exception:
  352. doc = "🦥 No docs"
  353. _help += f"🎹 <code>@{self.bot_username} {name}</code> - {doc}\n"
  354. if not _help:
  355. await inline_query.answer(
  356. [
  357. InlineQueryResultArticle(
  358. id=utils.rand(20),
  359. title="Show available inline commands",
  360. description="You have no available commands",
  361. input_message_content=InputTextMessageContent(
  362. "<b>😔 There are no available inline commands or you lack"
  363. " access to them</b>",
  364. "HTML",
  365. disable_web_page_preview=True,
  366. ),
  367. thumb_url=(
  368. "https://img.icons8.com/fluency/50/000000/info-squared.png"
  369. ),
  370. thumb_width=128,
  371. thumb_height=128,
  372. )
  373. ],
  374. cache_time=0,
  375. )
  376. return
  377. await inline_query.answer(
  378. [
  379. InlineQueryResultArticle(
  380. id=utils.rand(20),
  381. title="Show available inline commands",
  382. description=(
  383. f"You have {len(_help.splitlines())} available command(-s)"
  384. ),
  385. input_message_content=InputTextMessageContent(
  386. f"<b>ℹ️ Available inline commands:</b>\n\n{_help}",
  387. "HTML",
  388. disable_web_page_preview=True,
  389. ),
  390. thumb_url=(
  391. "https://img.icons8.com/fluency/50/000000/info-squared.png"
  392. ),
  393. thumb_width=128,
  394. thumb_height=128,
  395. )
  396. ],
  397. cache_time=0,
  398. )