form.py 21 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. import contextlib
  9. import copy
  10. import logging
  11. import os
  12. import re
  13. import time
  14. from asyncio import Event
  15. from typing import List, Optional, Union
  16. import random
  17. from urllib.parse import urlparse
  18. import grapheme
  19. import traceback
  20. from aiogram.types import (
  21. InlineQuery,
  22. InlineQueryResultArticle,
  23. InlineQueryResultPhoto,
  24. InputTextMessageContent,
  25. InlineQueryResultDocument,
  26. InlineQueryResultGif,
  27. InlineQueryResultVideo,
  28. InlineQueryResultLocation,
  29. InlineQueryResultAudio,
  30. )
  31. from telethon.tl.types import Message
  32. from telethon.errors.rpcerrorlist import ChatSendInlineForbiddenError
  33. from .. import utils, main
  34. from .types import InlineMessage, InlineUnit
  35. logger = logging.getLogger(__name__)
  36. VERIFICATION_EMOJIES = list(
  37. grapheme.graphemes(
  38. "👨‍🏫👩‍🏫👨‍🎤🧑‍🎤👩‍🎤👨‍🎓👩‍🎓👩‍🍳👩‍🌾👩‍⚕️🕵️‍♀️💂‍♀️👷‍♂️👮‍♂️👴🧑‍🦳👩‍🦳👱‍♀️👩‍🦰👨‍🦱👩‍⚖️🧙‍♂️🧝‍♀️🧛‍♀️"
  39. "🎅🧚‍♂️🙆‍♀️🙍‍♂️👩‍👦🧶🪢🪡🧵🩲👖👕👚🦺👗👙🩱👘🥻🩴🥿🧦🥾👟👞"
  40. "👢👡👠🪖👑💍👝👛👜💼🌂🥽🕶👓🧳🎒🐶🐱🐭🐹🐰🦊🐻🐷🐮"
  41. "🦁🐯🐨🐻‍❄️🐼🐽🐸🐵🙈🙉🙊🐒🦆🐥🐣🐤🐦🐧🐔🦅🦉🦇🐺🐗🐴"
  42. "🦄🐜🐞🐌🦋🐛🪱🐝🪰🪲🪳🦟🦗🕷🕸🐙🦕🦖🦎🐍🐢🦂🦑🦐🦞"
  43. "🦀🐡🐠🐟🐅🐊🦭🦈🐋🐳🐬🐆🦓🦍🦧🦣🐘🦛🐃🦬🦘🦒🐫🐪🦏"
  44. "🐂🐄🐎🐖🐏🐑🦙🐈🐕‍🦺🦮🐩🐕🦌🐐🐈‍⬛🪶🐓🦃🦤🦚🦜🦡🦨🦝🐇"
  45. "🕊🦩🦢🦫🦦🦥🐁🐀🐿🦔🌳🌲🌵🐲🐉🐾🎋🍂🍁🍄🐚🌾🪨💐🌷"
  46. "🥀🌺🌸🌻🌞🌜🌘🌗🌎🪐💫⭐️✨⚡️☄️💥☀️🌪🔥🌈🌤⛅️❄️⛄️🌊"
  47. "☂️🍏🍎🍐🍊🍋🍌🍉🥭🍑🍒🍈🫐🍓🍇🍍🥥🥝🍅🥑🥦🧔‍♂️"
  48. )
  49. )
  50. class Placeholder:
  51. """Placeholder"""
  52. class Form(InlineUnit):
  53. async def form(
  54. self,
  55. text: str,
  56. message: Union[Message, int],
  57. reply_markup: Union[List[List[dict]], List[dict], dict] = None,
  58. *,
  59. force_me: Optional[bool] = False,
  60. always_allow: Optional[List[list]] = None,
  61. manual_security: Optional[bool] = False,
  62. disable_security: Optional[bool] = False,
  63. ttl: Optional[int] = None,
  64. on_unload: Optional[callable] = None,
  65. photo: Optional[str] = None,
  66. gif: Optional[str] = None,
  67. file: Optional[str] = None,
  68. mime_type: Optional[str] = None,
  69. video: Optional[str] = None,
  70. location: Optional[str] = None,
  71. audio: Optional[Union[dict, str]] = None,
  72. silent: Optional[bool] = False,
  73. ) -> Union[InlineMessage, bool]:
  74. """
  75. Send inline form to chat
  76. :param text: Content of inline form. HTML markdown supported
  77. :param message: Where to send inline. Can be either `Message` or `int`
  78. :param reply_markup: List of buttons to insert in markup. List of dicts with keys: text, callback
  79. :param force_me: Either this form buttons must be pressed only by owner scope or no
  80. :param always_allow: Users, that are allowed to press buttons in addition to previous rules
  81. :param ttl: Time, when the form is going to be unloaded. Unload means, that the form
  82. buttons with inline queries and callback queries will become unusable, but
  83. buttons with type url will still work as usual. Pay attention, that ttl can't
  84. be bigger, than default one (1 day) and must be either `int` or `False`
  85. :param on_unload: Callback, called when form is unloaded and/or closed. You can clean up trash
  86. or perform another needed action
  87. :param manual_security: By default, Hikka will try to inherit inline buttons security from the caller (command)
  88. If you want to avoid this, pass `manual_security=True`
  89. :param disable_security: By default, Hikka will try to inherit inline buttons security from the caller (command)
  90. If you want to disable all security checks on this form in particular, pass `disable_security=True`
  91. :param photo: Attach a photo to the form. URL must be supplied
  92. :param gif: Attach a gif to the form. URL must be supplied
  93. :param file: Attach a file to the form. URL must be supplied
  94. :param mime_type: Only needed, if `file` field is not empty. Must be either 'application/pdf' or 'application/zip'
  95. :param video: Attach a video to the form. URL must be supplied
  96. :param location: Attach a map point to the form. List/tuple must be supplied (latitude, longitude)
  97. Example: (55.749931, 48.742371)
  98. ⚠️ If you pass this parameter, you'll need to pass empty string to `text` ⚠️
  99. :param audio: Attach a audio to the form. Dict or URL must be supplied
  100. :param silent: Whether the form must be sent silently (w/o "Loading inline form..." message)
  101. :return: If form is sent, returns :obj:`InlineMessage`, otherwise returns `False`
  102. """
  103. with contextlib.suppress(AttributeError):
  104. _hikka_client_id_logging_tag = copy.copy(self._client.tg_id)
  105. if reply_markup is None:
  106. reply_markup = []
  107. if always_allow is None:
  108. always_allow = []
  109. if not isinstance(text, str):
  110. logger.error("Invalid type for `text`")
  111. return False
  112. text = self.sanitise_text(text)
  113. if not isinstance(silent, bool):
  114. logger.error("Invalid type for `silent`")
  115. return False
  116. if not isinstance(manual_security, bool):
  117. logger.error("Invalid type for `manual_security`")
  118. return False
  119. if not isinstance(disable_security, bool):
  120. logger.error("Invalid type for `disable_security`")
  121. return False
  122. if not isinstance(message, (Message, int)):
  123. logger.error("Invalid type for `message`")
  124. return False
  125. if not isinstance(reply_markup, (list, dict)):
  126. logger.error("Invalid type for `reply_markup`")
  127. return False
  128. if photo and (not isinstance(photo, str) or not utils.check_url(photo)):
  129. logger.error("Invalid type for `photo`")
  130. return False
  131. try:
  132. path = urlparse(photo).path
  133. ext = os.path.splitext(path)[1]
  134. except Exception:
  135. ext = None
  136. if photo is not None and ext in {".gif", ".mp4"}:
  137. gif = copy.copy(photo)
  138. photo = None
  139. if gif and (not isinstance(gif, str) or not utils.check_url(gif)):
  140. logger.error("Invalid type for `gif`")
  141. return False
  142. if file and (not isinstance(file, str) or not utils.check_url(file)):
  143. logger.error("Invalid type for `file`")
  144. return False
  145. if file and not mime_type:
  146. logger.error(
  147. "You must pass `mime_type` along with `file` field\n"
  148. "It may be either 'application/zip' or 'application/pdf'"
  149. )
  150. return False
  151. if video and (not isinstance(video, str) or not utils.check_url(video)):
  152. logger.error("Invalid type for `video`")
  153. return False
  154. if isinstance(audio, str):
  155. audio = {"url": audio}
  156. if audio and (
  157. not isinstance(audio, dict)
  158. or "url" not in audio
  159. or not utils.check_url(audio["url"])
  160. ):
  161. logger.error("Invalid type for `audio`")
  162. return False
  163. if location and (
  164. not isinstance(location, (list, tuple))
  165. or len(location) != 2
  166. or not all(isinstance(item, float) for item in location)
  167. ):
  168. logger.error("Invalid type for `location`")
  169. return False
  170. if [
  171. photo is not None,
  172. gif is not None,
  173. file is not None,
  174. video is not None,
  175. audio is not None,
  176. location is not None,
  177. ].count(True) > 1:
  178. logger.error("You passed two or more exclusive parameters simultaneously")
  179. return False
  180. reply_markup = self._validate_markup(reply_markup) or []
  181. if not isinstance(force_me, bool):
  182. logger.error("Invalid type for `force_me`")
  183. return False
  184. if not isinstance(always_allow, list):
  185. logger.error("Invalid type for `always_allow`")
  186. return False
  187. if not isinstance(ttl, int) and ttl:
  188. logger.error("Invalid type for `ttl`")
  189. return False
  190. if isinstance(message, Message) and not silent:
  191. try:
  192. status_message = await (
  193. message.edit if message.out else message.respond
  194. )("🌘 <b>Loading inline form...</b>")
  195. except Exception:
  196. status_message = None
  197. else:
  198. status_message = None
  199. unit_id = utils.rand(16)
  200. perms_map = None if manual_security else self._find_caller_sec_map()
  201. if (
  202. not any(
  203. any(
  204. "callback" in button or "input" in button or "data" in button
  205. for button in row
  206. )
  207. for row in reply_markup
  208. )
  209. and not ttl
  210. ):
  211. logger.debug("Patching form reply markup with empty data")
  212. base_reply_markup = copy.deepcopy(reply_markup) or None
  213. reply_markup = self._validate_markup({"text": "­", "data": "­"})
  214. else:
  215. base_reply_markup = Placeholder()
  216. if (
  217. not any(
  218. any("callback" in button or "input" in button for button in row)
  219. for row in reply_markup
  220. )
  221. and not ttl
  222. ):
  223. logger.debug(
  224. "Patching form ttl to 10 minutes, because it doesn't contain any"
  225. " buttons"
  226. )
  227. ttl = 10 * 60
  228. self._units[unit_id] = {
  229. "type": "form",
  230. "text": text,
  231. "buttons": reply_markup,
  232. "chat": None,
  233. "message_id": None,
  234. "uid": unit_id,
  235. "on_unload": on_unload,
  236. "future": Event(),
  237. **({"photo": photo} if photo else {}),
  238. **({"video": video} if video else {}),
  239. **({"gif": gif} if gif else {}),
  240. **({"location": location} if location else {}),
  241. **({"audio": audio} if audio else {}),
  242. **({"location": location} if location else {}),
  243. **({"perms_map": perms_map} if perms_map else {}),
  244. **({"message": message} if isinstance(message, Message) else {}),
  245. **({"force_me": force_me} if force_me else {}),
  246. **({"disable_security": disable_security} if disable_security else {}),
  247. **({"ttl": round(time.time()) + ttl} if ttl else {}),
  248. **({"always_allow": always_allow} if always_allow else {}),
  249. }
  250. async def answer(msg: str):
  251. nonlocal message
  252. if isinstance(message, Message):
  253. await (message.edit if message.out else message.respond)(msg)
  254. else:
  255. await self._client.send_message(message, msg)
  256. try:
  257. q = await self._client.inline_query(self.bot_username, unit_id)
  258. m = await q[0].click(
  259. utils.get_chat_id(message) if isinstance(message, Message) else message,
  260. reply_to=message.reply_to_msg_id
  261. if isinstance(message, Message)
  262. else None,
  263. )
  264. except ChatSendInlineForbiddenError:
  265. await answer("🚫 <b>You can't send inline units in this chat</b>")
  266. except Exception:
  267. logger.exception("Can't send form")
  268. if not self._db.get(main.__name__, "inlinelogs", True):
  269. msg = "<b>🚫 Form invoke failed! More info in logs</b>"
  270. else:
  271. exc = traceback.format_exc()
  272. # Remove `Traceback (most recent call last):`
  273. exc = "\n".join(exc.splitlines()[1:])
  274. msg = (
  275. "<b>🚫 Form invoke failed!</b>\n\n"
  276. f"<b>🧾 Logs:</b>\n<code>{utils.escape_html(exc)}</code>"
  277. )
  278. del self._units[unit_id]
  279. await answer(msg)
  280. return False
  281. await self._units[unit_id]["future"].wait()
  282. del self._units[unit_id]["future"]
  283. self._units[unit_id]["chat"] = utils.get_chat_id(m)
  284. self._units[unit_id]["message_id"] = m.id
  285. if isinstance(message, Message) and message.out:
  286. await message.delete()
  287. if status_message and not message.out:
  288. await status_message.delete()
  289. inline_message_id = self._units[unit_id]["inline_message_id"]
  290. msg = InlineMessage(self, unit_id, inline_message_id)
  291. if not isinstance(base_reply_markup, Placeholder):
  292. await msg.edit(text, reply_markup=base_reply_markup)
  293. return msg
  294. async def _form_inline_handler(self, inline_query: InlineQuery):
  295. try:
  296. query = inline_query.query.split()[0]
  297. except IndexError:
  298. return
  299. for unit in self._units.copy().values():
  300. for button in utils.array_sum(unit.get("buttons", [])):
  301. if (
  302. "_switch_query" in button
  303. and "input" in button
  304. and button["_switch_query"] == query
  305. and inline_query.from_user.id
  306. in [self._me]
  307. + self._client.dispatcher.security._owner
  308. + unit.get("always_allow", [])
  309. ):
  310. await inline_query.answer(
  311. [
  312. InlineQueryResultArticle(
  313. id=utils.rand(20),
  314. title=button["input"],
  315. description=(
  316. "⚠️ Do not remove ID!"
  317. f" {random.choice(VERIFICATION_EMOJIES)}"
  318. ),
  319. input_message_content=InputTextMessageContent(
  320. "🔄 <b>Transferring value to userbot...</b>\n"
  321. "<i>This message will be deleted automatically</i>"
  322. if inline_query.from_user.id == self._me
  323. else "🔄 <b>Transferring value to userbot...</b>",
  324. "HTML",
  325. disable_web_page_preview=True,
  326. ),
  327. )
  328. ],
  329. cache_time=60,
  330. )
  331. return
  332. if (
  333. inline_query.query not in self._units
  334. or self._units[inline_query.query]["type"] != "form"
  335. ):
  336. return
  337. # Otherwise, answer it with templated form
  338. form = self._units[inline_query.query]
  339. if "photo" in form:
  340. await inline_query.answer(
  341. [
  342. InlineQueryResultPhoto(
  343. id=utils.rand(20),
  344. title="Hikka",
  345. description="Hikka",
  346. caption=form.get("text"),
  347. parse_mode="HTML",
  348. photo_url=form["photo"],
  349. thumb_url=(
  350. "https://img.icons8.com/cotton/452/moon-satellite.png"
  351. ),
  352. reply_markup=self.generate_markup(
  353. form["uid"],
  354. ),
  355. )
  356. ],
  357. cache_time=0,
  358. )
  359. elif "gif" in form:
  360. await inline_query.answer(
  361. [
  362. InlineQueryResultGif(
  363. id=utils.rand(20),
  364. title="Hikka",
  365. caption=form.get("text"),
  366. parse_mode="HTML",
  367. gif_url=form["gif"],
  368. thumb_url=(
  369. "https://img.icons8.com/cotton/452/moon-satellite.png"
  370. ),
  371. reply_markup=self.generate_markup(
  372. form["uid"],
  373. ),
  374. )
  375. ],
  376. cache_time=0,
  377. )
  378. elif "video" in form:
  379. await inline_query.answer(
  380. [
  381. InlineQueryResultVideo(
  382. id=utils.rand(20),
  383. title="Hikka",
  384. description="Hikka",
  385. caption=form.get("text"),
  386. parse_mode="HTML",
  387. video_url=form["video"],
  388. thumb_url=(
  389. "https://img.icons8.com/cotton/452/moon-satellite.png"
  390. ),
  391. mime_type="video/mp4",
  392. reply_markup=self.generate_markup(
  393. form["uid"],
  394. ),
  395. )
  396. ],
  397. cache_time=0,
  398. )
  399. elif "file" in form:
  400. await inline_query.answer(
  401. [
  402. InlineQueryResultDocument(
  403. id=utils.rand(20),
  404. title="Hikka",
  405. description="Hikka",
  406. caption=form.get("text"),
  407. parse_mode="HTML",
  408. document_url=form["file"],
  409. mime_type=form["mime_type"],
  410. reply_markup=self.generate_markup(
  411. form["uid"],
  412. ),
  413. )
  414. ],
  415. cache_time=0,
  416. )
  417. elif "location" in form:
  418. await inline_query.answer(
  419. [
  420. InlineQueryResultLocation(
  421. id=utils.rand(20),
  422. latitude=form["location"][0],
  423. longitude=form["location"][1],
  424. title="Hikka",
  425. reply_markup=self.generate_markup(
  426. form["uid"],
  427. ),
  428. )
  429. ],
  430. cache_time=0,
  431. )
  432. elif "audio" in form:
  433. await inline_query.answer(
  434. [
  435. InlineQueryResultAudio(
  436. id=utils.rand(20),
  437. audio_url=form["audio"]["url"],
  438. caption=form.get("text"),
  439. parse_mode="HTML",
  440. title=form["audio"].get("title", "Hikka"),
  441. performer=form["audio"].get("performer"),
  442. audio_duration=form["audio"].get("duration"),
  443. reply_markup=self.generate_markup(
  444. form["uid"],
  445. ),
  446. )
  447. ],
  448. cache_time=0,
  449. )
  450. else:
  451. await inline_query.answer(
  452. [
  453. InlineQueryResultArticle(
  454. id=utils.rand(20),
  455. title="Hikka",
  456. input_message_content=InputTextMessageContent(
  457. form["text"],
  458. "HTML",
  459. disable_web_page_preview=True,
  460. ),
  461. reply_markup=self.generate_markup(inline_query.query),
  462. )
  463. ],
  464. cache_time=0,
  465. )