form.py 22 KB

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