api_protection.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  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. # meta pic: https://img.icons8.com/emoji/344/shield-emoji.png
  9. # meta developer: @hikariatama
  10. import asyncio
  11. import io
  12. import json
  13. import logging
  14. import time
  15. from telethon.tl.types import Message
  16. from .. import loader, utils
  17. from ..inline.types import InlineCall
  18. logger = logging.getLogger(__name__)
  19. @loader.tds
  20. class APIRatelimiterMod(loader.Module):
  21. """Helps userbot avoid spamming Telegram API"""
  22. strings = {
  23. "name": "APIRatelimiter",
  24. "warning": (
  25. "<emoji document_id=6319093650693293883>☣️</emoji>"
  26. " <b>WARNING!</b>\n\nYour account exceeded the limit of requests, specified"
  27. " in config. In order to prevent Telegram API Flood, userbot has been"
  28. " <b>fully frozen</b> for {} seconds. Further info is provided in attached"
  29. " file. \n\nIt is recommended to get help in <code>{prefix}support</code>"
  30. " group!\n\nIf you think, that it is an intended behavior, then wait until"
  31. " userbot gets unlocked and next time, when you will be going to perform"
  32. " such an operation, use <code>{prefix}suspend_api_protect</code> &lt;time"
  33. " in seconds&gt;"
  34. ),
  35. "args_invalid": (
  36. "<emoji document_id=6319093650693293883>☣️</emoji> <b>Invalid arguments</b>"
  37. ),
  38. "suspended_for": (
  39. "<emoji document_id=5458450833857322148>👌</emoji> <b>API Flood Protection"
  40. " is disabled for {} seconds</b>"
  41. ),
  42. "test": (
  43. "<emoji document_id=6319093650693293883>☣️</emoji> <b>This action will"
  44. " expose your account to flooding Telegram API.</b> <i>In order to confirm,"
  45. " that you really know, what you are doing, complete this simple test -"
  46. " find the emoji, differing from others</i>"
  47. ),
  48. "on": (
  49. "<emoji document_id=5458450833857322148>👌</emoji> <b>Protection enabled</b>"
  50. ),
  51. "off": (
  52. "<emoji document_id=5458450833857322148>👌</emoji> <b>Protection"
  53. " disabled</b>"
  54. ),
  55. "u_sure": (
  56. "<emoji document_id=6319093650693293883>☣️</emoji> <b>Are you sure?</b>"
  57. ),
  58. }
  59. strings_ru = {
  60. "warning": (
  61. "<emoji document_id=6319093650693293883>☣️</emoji>"
  62. " <b>ВНИМАНИЕ!</b>\n\nАккаунт вышел за лимиты запросов, указанные в"
  63. " конфиге. С целью предотвращения флуда Telegram API, юзербот был"
  64. " <b>полностью заморожен</b> на {} секунд. Дополнительная информация"
  65. " прикреплена в файле ниже. \n\nРекомендуется обратиться за помощью в"
  66. " <code>{prefix}support</code> группу!\n\nЕсли ты считаешь, что это"
  67. " запланированное поведение юзербота, просто подожди, пока закончится"
  68. " таймер и в следующий раз, когда запланируешь выполнять такую"
  69. " ресурсозатратную операцию, используй"
  70. " <code>{prefix}suspend_api_protect</code> &lt;время в секундах&gt;"
  71. ),
  72. "args_invalid": (
  73. "<emoji document_id=6319093650693293883>☣️</emoji> <b>Неверные"
  74. " аргументы</b>"
  75. ),
  76. "suspended_for": (
  77. "<emoji document_id=5458450833857322148>👌</emoji> <b>Защита API отключена"
  78. " на {} секунд</b>"
  79. ),
  80. "test": (
  81. "<emoji document_id=6319093650693293883>☣️</emoji> <b>Это действие"
  82. " открывает юзерботу возможность флудить Telegram API.</b> <i>Для того,"
  83. " чтобы убедиться, что ты действительно уверен в том, что делаешь - реши"
  84. " простенький тест - найди отличающийся эмодзи.</i>"
  85. ),
  86. "on": "<emoji document_id=5458450833857322148>👌</emoji> <b>Защита включена</b>",
  87. "off": (
  88. "<emoji document_id=5458450833857322148>👌</emoji> <b>Защита отключена</b>"
  89. ),
  90. "u_sure": "<emoji document_id=6319093650693293883>☣️</emoji> <b>Ты уверен?</b>",
  91. }
  92. _ratelimiter = []
  93. _suspend_until = 0
  94. _lock = False
  95. def __init__(self):
  96. self.config = loader.ModuleConfig(
  97. loader.ConfigValue(
  98. "time_sample",
  99. 15,
  100. lambda: "Time sample DO NOT TOUCH",
  101. validator=loader.validators.Integer(minimum=1),
  102. ),
  103. loader.ConfigValue(
  104. "threshold",
  105. 100,
  106. lambda: "Threshold DO NOT TOUCH",
  107. validator=loader.validators.Integer(minimum=10),
  108. ),
  109. loader.ConfigValue(
  110. "local_floodwait",
  111. 30,
  112. lambda: "Local FW DO NOT TOUCH",
  113. validator=loader.validators.Integer(minimum=10, maximum=3600),
  114. ),
  115. )
  116. async def client_ready(self):
  117. asyncio.ensure_future(self._install_protection())
  118. async def _install_protection(self):
  119. await asyncio.sleep(30) # Restart lock
  120. if hasattr(self._client._call, "_old_call_rewritten"):
  121. raise loader.SelfUnload("Already installed")
  122. old_call = self._client._call
  123. async def new_call(
  124. sender: "MTProtoSender", # type: ignore
  125. request: "TLRequest", # type: ignore
  126. ordered: bool = False,
  127. flood_sleep_threshold: int = None,
  128. ):
  129. if time.perf_counter() > self._suspend_until and not self.get(
  130. "disable_protection",
  131. True,
  132. ):
  133. request_name = type(request).__name__
  134. self._ratelimiter += [[request_name, time.perf_counter()]]
  135. self._ratelimiter = list(
  136. filter(
  137. lambda x: time.perf_counter() - x[1]
  138. < int(self.config["time_sample"]),
  139. self._ratelimiter,
  140. )
  141. )
  142. if (
  143. len(self._ratelimiter) > int(self.config["threshold"])
  144. and not self._lock
  145. ):
  146. self._lock = True
  147. report = io.BytesIO(
  148. json.dumps(
  149. self._ratelimiter,
  150. indent=4,
  151. ).encode("utf-8")
  152. )
  153. report.name = "local_fw_report.json"
  154. await self.inline.bot.send_document(
  155. self.tg_id,
  156. report,
  157. caption=self.strings("warning").format(
  158. self.config["local_floodwait"],
  159. prefix=self.get_prefix(),
  160. ),
  161. )
  162. # It is intented to use time.sleep instead of asyncio.sleep
  163. time.sleep(int(self.config["local_floodwait"]))
  164. self._lock = False
  165. return await old_call(sender, request, ordered, flood_sleep_threshold)
  166. self._client._call = new_call
  167. self._client._old_call_rewritten = old_call
  168. self._client._call._hikka_overwritten = True
  169. logger.debug("Successfully installed ratelimiter")
  170. async def on_unload(self):
  171. if hasattr(self._client, "_old_call_rewritten"):
  172. self._client._call = self._client._old_call_rewritten
  173. delattr(self._client, "_old_call_rewritten")
  174. logger.debug("Successfully uninstalled ratelimiter")
  175. @loader.command(ru_doc="<время в секундах> - Заморозить защиту API на N секунд")
  176. async def suspend_api_protect(self, message: Message):
  177. """<time in seconds> - Suspend API Ratelimiter for n seconds"""
  178. args = utils.get_args_raw(message)
  179. if not args or not args.isdigit():
  180. await utils.answer(message, self.strings("args_invalid"))
  181. return
  182. self._suspend_until = time.perf_counter() + int(args)
  183. await utils.answer(message, self.strings("suspended_for").format(args))
  184. @loader.command(ru_doc="Включить/выключить защиту API")
  185. async def api_fw_protection(self, message: Message):
  186. """Toggle API Ratelimiter"""
  187. await self.inline.form(
  188. message=message,
  189. text=self.strings("u_sure"),
  190. reply_markup=[
  191. {"text": "🚫 No", "action": "close"},
  192. {"text": "✅ Yes", "callback": self._finish},
  193. ],
  194. )
  195. async def _finish(self, call: InlineCall):
  196. state = self.get("disable_protection", True)
  197. self.set("disable_protection", not state)
  198. await call.edit(self.strings("on" if state else "off"))