form.py 21 KB

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