inline_stuff.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  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. # scope: inline
  9. import logging
  10. import re
  11. import string
  12. from telethon.errors.rpcerrorlist import YouBlockedUserError
  13. from telethon.tl.functions.contacts import UnblockRequest
  14. from telethon.tl.types import Message
  15. from .. import loader, utils
  16. logger = logging.getLogger(__name__)
  17. @loader.tds
  18. class InlineStuffMod(loader.Module):
  19. """Provides support for inline stuff"""
  20. strings = {
  21. "name": "InlineStuff",
  22. "bot_username_invalid": (
  23. "<emoji document_id='5415905755406539934'>🚫</emoji> <b>Specified bot"
  24. " username is invalid. It must end with </b><code>bot</code><b> and contain"
  25. " at least 4 symbols</b>"
  26. ),
  27. "bot_username_occupied": (
  28. "<emoji document_id='5415905755406539934'>🚫</emoji> <b>This username is"
  29. " already occupied</b>"
  30. ),
  31. "bot_updated": (
  32. "<emoji document_id='6318792204118656433'>🎉</emoji> <b>Config successfully"
  33. " saved. Restart userbot to apply changes</b>"
  34. ),
  35. }
  36. strings_ru = {
  37. "bot_username_invalid": (
  38. "<emoji document_id='5415905755406539934'>🚫</emoji> <b>Неправильный ник"
  39. " бота. Он должен заканчиваться на </b><code>bot</code><b> и быть не короче"
  40. " чем 5 символов</b>"
  41. ),
  42. "bot_username_occupied": (
  43. "<emoji document_id='5415905755406539934'>🚫</emoji> <b>Такой ник бота уже"
  44. " занят</b>"
  45. ),
  46. "bot_updated": (
  47. "<emoji document_id='6318792204118656433'>🎉</emoji> <b>Настройки сохранены."
  48. " Для их применения нужно перезагрузить юзербот</b>"
  49. ),
  50. }
  51. async def watcher(self, message: Message):
  52. if (
  53. getattr(message, "out", False)
  54. and getattr(message, "via_bot_id", False)
  55. and message.via_bot_id == self.inline.bot_id
  56. and "This message will be deleted automatically"
  57. in getattr(message, "raw_text", "")
  58. ):
  59. await message.delete()
  60. return
  61. if (
  62. not getattr(message, "out", False)
  63. or not getattr(message, "via_bot_id", False)
  64. or message.via_bot_id != self.inline.bot_id
  65. or "Loading Hikka gallery..." not in getattr(message, "raw_text", "")
  66. ):
  67. return
  68. id_ = re.search(r"#id: ([a-zA-Z0-9]+)", message.raw_text)[1]
  69. await message.delete()
  70. m = await message.respond("🌘 <b>Opening gallery... wait</b>")
  71. await self.inline.gallery(
  72. message=m,
  73. next_handler=self.inline._custom_map[id_]["handler"],
  74. caption=self.inline._custom_map[id_].get("caption", ""),
  75. force_me=self.inline._custom_map[id_].get("force_me", False),
  76. disable_security=self.inline._custom_map[id_].get(
  77. "disable_security", False
  78. ),
  79. )
  80. async def _check_bot(self, username: str) -> bool:
  81. async with self._client.conversation("@BotFather", exclusive=False) as conv:
  82. try:
  83. m = await conv.send_message("/token")
  84. except YouBlockedUserError:
  85. await self._client(UnblockRequest(id="@BotFather"))
  86. m = await conv.send_message("/token")
  87. r = await conv.get_response()
  88. await m.delete()
  89. await r.delete()
  90. if not hasattr(r, "reply_markup") or not hasattr(r.reply_markup, "rows"):
  91. return False
  92. for row in r.reply_markup.rows:
  93. for button in row.buttons:
  94. if username != button.text.strip("@"):
  95. continue
  96. m = await conv.send_message("/cancel")
  97. r = await conv.get_response()
  98. await m.delete()
  99. await r.delete()
  100. return True
  101. @loader.command(ru_doc="<юзернейм> - Изменить юзернейм инлайн бота")
  102. async def ch_hikka_bot(self, message: Message):
  103. """<username> - Change your Hikka inline bot username"""
  104. args = utils.get_args_raw(message).strip("@")
  105. if (
  106. not args
  107. or not args.lower().endswith("bot")
  108. or len(args) <= 4
  109. or any(
  110. litera not in (string.ascii_letters + string.digits + "_")
  111. for litera in args
  112. )
  113. ):
  114. await utils.answer(message, self.strings("bot_username_invalid"))
  115. return
  116. try:
  117. await self._client.get_entity(f"@{args}")
  118. except ValueError:
  119. pass
  120. else:
  121. if not await self._check_bot(args):
  122. await utils.answer(message, self.strings("bot_username_occupied"))
  123. return
  124. self._db.set("hikka.inline", "custom_bot", args)
  125. self._db.set("hikka.inline", "bot_token", None)
  126. await utils.answer(message, self.strings("bot_updated"))