form.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  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 time
  13. from asyncio import Event
  14. from typing import List, Optional, Union
  15. import random
  16. from urllib.parse import urlparse
  17. import grapheme
  18. import traceback
  19. from aiogram.types import (
  20. InlineQuery,
  21. InlineQueryResultArticle,
  22. InlineQueryResultPhoto,
  23. InputTextMessageContent,
  24. InlineQueryResultDocument,
  25. InlineQueryResultGif,
  26. InlineQueryResultVideo,
  27. InlineQueryResultLocation,
  28. InlineQueryResultAudio,
  29. )
  30. from telethon.tl.types import Message
  31. from telethon.errors.rpcerrorlist import ChatSendInlineForbiddenError
  32. from .. import utils, main
  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: Union[Message, int],
  56. reply_markup: Union[List[List[dict]], List[dict], dict] = None,
  57. *,
  58. force_me: Optional[bool] = False,
  59. always_allow: Optional[List[list]] = None,
  60. manual_security: Optional[bool] = False,
  61. disable_security: Optional[bool] = False,
  62. ttl: Optional[int] = None,
  63. on_unload: Optional[callable] = None,
  64. photo: Optional[str] = None,
  65. gif: Optional[str] = None,
  66. file: Optional[str] = None,
  67. mime_type: Optional[str] = None,
  68. video: Optional[str] = None,
  69. location: Optional[str] = None,
  70. audio: Optional[Union[dict, str]] = None,
  71. silent: Optional[bool] = False,
  72. ) -> 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 "Loading inline 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("Invalid type for `text`")
  110. return False
  111. if not isinstance(silent, bool):
  112. logger.error("Invalid type for `silent`")
  113. return False
  114. if not isinstance(manual_security, bool):
  115. logger.error("Invalid type for `manual_security`")
  116. return False
  117. if not isinstance(disable_security, bool):
  118. logger.error("Invalid type for `disable_security`")
  119. return False
  120. if not isinstance(message, (Message, int)):
  121. logger.error("Invalid type for `message`")
  122. return False
  123. if not isinstance(reply_markup, (list, dict)):
  124. logger.error("Invalid type for `reply_markup`")
  125. return False
  126. if photo and (not isinstance(photo, str) or not utils.check_url(photo)):
  127. logger.error("Invalid type for `photo`")
  128. return False
  129. try:
  130. path = urlparse(photo).path
  131. ext = os.path.splitext(path)[1]
  132. except Exception:
  133. ext = None
  134. if photo is not None and ext in {".gif", ".mp4"}:
  135. gif = copy.copy(photo)
  136. photo = None
  137. if gif and (not isinstance(gif, str) or not utils.check_url(gif)):
  138. logger.error("Invalid type for `gif`")
  139. return False
  140. if file and (not isinstance(file, str) or not utils.check_url(file)):
  141. logger.error("Invalid type for `file`")
  142. return False
  143. if file and not mime_type:
  144. logger.error(
  145. "You must pass `mime_type` along with `file` field\n"
  146. "It may be either 'application/zip' or 'application/pdf'"
  147. )
  148. return False
  149. if video and (not isinstance(video, str) or not utils.check_url(video)):
  150. logger.error("Invalid type for `video`")
  151. return False
  152. if isinstance(audio, str):
  153. audio = {"url": audio}
  154. if audio and (
  155. not isinstance(audio, dict)
  156. or "url" not in audio
  157. or not utils.check_url(audio["url"])
  158. ):
  159. logger.error("Invalid type for `audio`")
  160. return False
  161. if location and (
  162. not isinstance(location, (list, tuple))
  163. or len(location) != 2
  164. or not all(isinstance(item, float) for item in location)
  165. ):
  166. logger.error("Invalid type for `location`")
  167. return False
  168. if [
  169. photo is not None,
  170. gif is not None,
  171. file is not None,
  172. video is not None,
  173. audio is not None,
  174. location is not None,
  175. ].count(True) > 1:
  176. logger.error("You passed two or more exclusive parameters simultaneously")
  177. return False
  178. reply_markup = self._validate_markup(reply_markup) or []
  179. if not isinstance(force_me, bool):
  180. logger.error("Invalid type for `force_me`")
  181. return False
  182. if not isinstance(always_allow, list):
  183. logger.error("Invalid type for `always_allow`")
  184. return False
  185. if not isinstance(ttl, int) and ttl:
  186. logger.error("Invalid type for `ttl`")
  187. return False
  188. if isinstance(message, Message) and not silent:
  189. try:
  190. status_message = await (
  191. message.edit if message.out else message.respond
  192. )("🌘 <b>Loading inline form...</b>")
  193. except Exception:
  194. status_message = None
  195. else:
  196. status_message = None
  197. unit_id = utils.rand(16)
  198. perms_map = None if manual_security else self._find_caller_sec_map()
  199. if (
  200. not any(
  201. any(
  202. "callback" in button or "input" in button or "data" in button
  203. for button in row
  204. )
  205. for row in reply_markup
  206. )
  207. and not ttl
  208. ):
  209. logger.debug("Patching form reply markup with empty data")
  210. base_reply_markup = copy.deepcopy(reply_markup) or None
  211. reply_markup = self._validate_markup({"text": "­", "data": "­"})
  212. else:
  213. base_reply_markup = Placeholder()
  214. if (
  215. not any(
  216. any("callback" in button or "input" in button for button in row)
  217. for row in reply_markup
  218. )
  219. and not ttl
  220. ):
  221. logger.debug(
  222. "Patching form ttl to 10 minutes, because it doesn't contain any"
  223. " buttons"
  224. )
  225. ttl = 10 * 60
  226. self._units[unit_id] = {
  227. "type": "form",
  228. "text": text,
  229. "buttons": reply_markup,
  230. "chat": None,
  231. "message_id": None,
  232. "uid": unit_id,
  233. "on_unload": on_unload,
  234. "future": Event(),
  235. **({"photo": photo} if photo else {}),
  236. **({"video": video} if video else {}),
  237. **({"gif": gif} if gif else {}),
  238. **({"location": location} if location else {}),
  239. **({"audio": audio} if audio else {}),
  240. **({"location": location} if location else {}),
  241. **({"perms_map": perms_map} if perms_map else {}),
  242. **({"message": message} if isinstance(message, Message) else {}),
  243. **({"force_me": force_me} if force_me else {}),
  244. **({"disable_security": disable_security} if disable_security else {}),
  245. **({"ttl": round(time.time()) + ttl} if ttl else {}),
  246. **({"always_allow": always_allow} if always_allow else {}),
  247. }
  248. async def answer(msg: str):
  249. nonlocal message
  250. if isinstance(message, Message):
  251. await (message.edit if message.out else message.respond)(msg)
  252. else:
  253. await self._client.send_message(message, msg)
  254. try:
  255. q = await self._client.inline_query(self.bot_username, unit_id)
  256. m = await q[0].click(
  257. utils.get_chat_id(message) if isinstance(message, Message) else message,
  258. reply_to=message.reply_to_msg_id
  259. if isinstance(message, Message)
  260. else None,
  261. )
  262. except ChatSendInlineForbiddenError:
  263. await answer("🚫 <b>You can't send inline units in this chat</b>")
  264. except Exception:
  265. logger.exception("Can't send form")
  266. if not self._db.get(main.__name__, "inlinelogs", True):
  267. msg = "<b>🚫 Form invoke failed! More info in logs</b>"
  268. else:
  269. exc = traceback.format_exc()
  270. # Remove `Traceback (most recent call last):`
  271. exc = "\n".join(exc.splitlines()[1:])
  272. msg = (
  273. "<b>🚫 Form invoke failed!</b>\n\n"
  274. f"<b>🧾 Logs:</b>\n<code>{exc}</code>"
  275. )
  276. del self._units[unit_id]
  277. await answer(msg)
  278. return False
  279. await self._units[unit_id]["future"].wait()
  280. del self._units[unit_id]["future"]
  281. self._units[unit_id]["chat"] = utils.get_chat_id(m)
  282. self._units[unit_id]["message_id"] = m.id
  283. if isinstance(message, Message) and message.out:
  284. await message.delete()
  285. if status_message and not message.out:
  286. await status_message.delete()
  287. inline_message_id = self._units[unit_id]["inline_message_id"]
  288. msg = InlineMessage(self, unit_id, inline_message_id)
  289. if not isinstance(base_reply_markup, Placeholder):
  290. await msg.edit(text, reply_markup=base_reply_markup)
  291. return msg
  292. async def _form_inline_handler(self, inline_query: InlineQuery):
  293. try:
  294. query = inline_query.query.split()[0]
  295. except IndexError:
  296. return
  297. for unit in self._units.copy().values():
  298. for button in utils.array_sum(unit.get("buttons", [])):
  299. if (
  300. "_switch_query" in button
  301. and "input" in button
  302. and button["_switch_query"] == query
  303. and inline_query.from_user.id
  304. in [self._me]
  305. + self._client.dispatcher.security._owner
  306. + unit.get("always_allow", [])
  307. ):
  308. await inline_query.answer(
  309. [
  310. InlineQueryResultArticle(
  311. id=utils.rand(20),
  312. title=button["input"],
  313. description=(
  314. "⚠️ Do not remove ID!"
  315. f" {random.choice(VERIFICATION_EMOJIES)}"
  316. ),
  317. input_message_content=InputTextMessageContent(
  318. "🔄 <b>Transferring value to userbot...</b>\n"
  319. "<i>This message will be deleted automatically</i>"
  320. if inline_query.from_user.id == self._me
  321. else "🔄 <b>Transferring value to userbot...</b>",
  322. "HTML",
  323. disable_web_page_preview=True,
  324. ),
  325. )
  326. ],
  327. cache_time=60,
  328. )
  329. return
  330. if (
  331. inline_query.query not in self._units
  332. or self._units[inline_query.query]["type"] != "form"
  333. ):
  334. return
  335. # Otherwise, answer it with templated form
  336. form = self._units[inline_query.query]
  337. if "photo" in form:
  338. await inline_query.answer(
  339. [
  340. InlineQueryResultPhoto(
  341. id=utils.rand(20),
  342. title="Hikka",
  343. description="Hikka",
  344. caption=form.get("text"),
  345. parse_mode="HTML",
  346. photo_url=form["photo"],
  347. thumb_url=(
  348. "https://img.icons8.com/cotton/452/moon-satellite.png"
  349. ),
  350. reply_markup=self.generate_markup(
  351. form["uid"],
  352. ),
  353. )
  354. ],
  355. cache_time=0,
  356. )
  357. elif "gif" in form:
  358. await inline_query.answer(
  359. [
  360. InlineQueryResultGif(
  361. id=utils.rand(20),
  362. title="Hikka",
  363. caption=form.get("text"),
  364. parse_mode="HTML",
  365. gif_url=form["gif"],
  366. thumb_url=(
  367. "https://img.icons8.com/cotton/452/moon-satellite.png"
  368. ),
  369. reply_markup=self.generate_markup(
  370. form["uid"],
  371. ),
  372. )
  373. ],
  374. cache_time=0,
  375. )
  376. elif "video" in form:
  377. await inline_query.answer(
  378. [
  379. InlineQueryResultVideo(
  380. id=utils.rand(20),
  381. title="Hikka",
  382. description="Hikka",
  383. caption=form.get("text"),
  384. parse_mode="HTML",
  385. video_url=form["video"],
  386. thumb_url=(
  387. "https://img.icons8.com/cotton/452/moon-satellite.png"
  388. ),
  389. mime_type="video/mp4",
  390. reply_markup=self.generate_markup(
  391. form["uid"],
  392. ),
  393. )
  394. ],
  395. cache_time=0,
  396. )
  397. elif "file" in form:
  398. await inline_query.answer(
  399. [
  400. InlineQueryResultDocument(
  401. id=utils.rand(20),
  402. title="Hikka",
  403. description="Hikka",
  404. caption=form.get("text"),
  405. parse_mode="HTML",
  406. document_url=form["file"],
  407. mime_type=form["mime_type"],
  408. reply_markup=self.generate_markup(
  409. form["uid"],
  410. ),
  411. )
  412. ],
  413. cache_time=0,
  414. )
  415. elif "location" in form:
  416. await inline_query.answer(
  417. [
  418. InlineQueryResultLocation(
  419. id=utils.rand(20),
  420. latitude=form["location"][0],
  421. longitude=form["location"][1],
  422. title="Hikka",
  423. reply_markup=self.generate_markup(
  424. form["uid"],
  425. ),
  426. )
  427. ],
  428. cache_time=0,
  429. )
  430. elif "audio" in form:
  431. await inline_query.answer(
  432. [
  433. InlineQueryResultAudio(
  434. id=utils.rand(20),
  435. audio_url=form["audio"]["url"],
  436. caption=form.get("text"),
  437. parse_mode="HTML",
  438. title=form["audio"].get("title", "Hikka"),
  439. performer=form["audio"].get("performer"),
  440. audio_duration=form["audio"].get("duration"),
  441. reply_markup=self.generate_markup(
  442. form["uid"],
  443. ),
  444. )
  445. ],
  446. cache_time=0,
  447. )
  448. else:
  449. await inline_query.answer(
  450. [
  451. InlineQueryResultArticle(
  452. id=utils.rand(20),
  453. title="Hikka",
  454. input_message_content=InputTextMessageContent(
  455. form["text"],
  456. "HTML",
  457. disable_web_page_preview=True,
  458. ),
  459. reply_markup=self.generate_markup(inline_query.query),
  460. )
  461. ],
  462. cache_time=0,
  463. )