inline_stuff.py 5.1 KB

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