main.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. import os
  2. import time
  3. import random
  4. import string
  5. import asyncio
  6. from datetime import datetime, timedelta
  7. import aiohttp
  8. from dotenv import load_dotenv
  9. from telethon import TelegramClient, events
  10. from telethon.utils import get_peer_id, get_display_name
  11. from telethon.tl.functions.channels import EditBannedRequest
  12. from telethon.tl.types import ChatBannedRights
  13. from captcha.image import ImageCaptcha
  14. def get_user_name(user):
  15. full_name = get_display_name(user)
  16. if not full_name:
  17. full_name = user.username
  18. if not full_name:
  19. full_name = "user"
  20. return full_name
  21. def get_link_to_user(user):
  22. full_name = get_user_name(user)
  23. if user.username:
  24. return f"[{full_name}](@{user.username})"
  25. return f"[{full_name}](tg://user?id={user.id})"
  26. load_dotenv()
  27. API_ID = int(os.getenv("API_ID"))
  28. API_HASH = os.getenv("API_HASH")
  29. BOT_TOKEN = os.getenv("BOT_TOKEN")
  30. ALLOWED_GROUPS = set(
  31. map(lambda cid: int("-100" + cid), os.getenv("ALLOWED_GROUPS").split(","))
  32. )
  33. CAPTCHA_WAIT_TIME = int(os.getenv("CAPTCHA_WAIT_TIME", 80))
  34. MAX_CAPTCHA_ATTEMPTS = int(os.getenv("MAX_CAPTCHA_ATTEMPTS", 8))
  35. USE_LOLS_API = os.getenv("USE_LOLS_API", "yes") == "yes"
  36. bot = TelegramClient("captcha_bot", API_ID, API_HASH).start(bot_token=BOT_TOKEN)
  37. pending = {peer_id: {} for peer_id in ALLOWED_GROUPS}
  38. whitelist = {}
  39. blacklist = {}
  40. async def lols_check(user_id):
  41. try:
  42. async with aiohttp.ClientSession() as session:
  43. async with session.get(
  44. f"https://api.lols.bot/account?id={user_id}"
  45. ) as response:
  46. data = await response.json()
  47. banned = data.get("banned", False)
  48. scammer = data.get("scammer", False)
  49. return not banned and not scammer
  50. except Exception:
  51. pass
  52. return True
  53. class PendingUser:
  54. def __init__(self, peer_id, user_id):
  55. self.peer_id = peer_id
  56. self.user_id = user_id
  57. self.ban_flag = False
  58. self.text = None
  59. self.message_id = None
  60. self.captcha = None
  61. self.captcha_im = None
  62. self.join_ts = time.time()
  63. self.retries = 0
  64. @property
  65. def expired(self):
  66. return time.time() - self.join_ts >= CAPTCHA_WAIT_TIME
  67. async def start(self, event):
  68. if USE_LOLS_API:
  69. if not await lols_check(self.user_id):
  70. blacklist[self.user_id] = time.time()
  71. await self.kick(forever=True)
  72. return
  73. await self.update_captcha()
  74. if self.user_id not in pending[self.peer_id]:
  75. return
  76. if self.ban_flag:
  77. return
  78. self.text = f"Welcome, {get_link_to_user(event.user)}! Please write a message with the **four latin letters (case insensitive)** that appear in this image to verify that you are a human. If you don't solve the captcha in **{CAPTCHA_WAIT_TIME}** seconds, you will be automatically kicked out of the group."
  79. message = await bot.send_message(
  80. event.chat_id,
  81. self.text,
  82. file=self.captcha_im,
  83. )
  84. self.message_id = message
  85. if self.user_id not in pending[self.peer_id]:
  86. try:
  87. await bot.delete_messages(self.peer_id, self.message_id)
  88. except Exception:
  89. pass
  90. async def update_captcha(self, only_text=False):
  91. if not only_text:
  92. self.captcha = "".join(random.sample(string.ascii_uppercase, 4))
  93. self.captcha_im = ImageCaptcha().generate(self.captcha)
  94. self.captcha_im.name = "captcha.png"
  95. if self.message_id is not None:
  96. try:
  97. attempts = MAX_CAPTCHA_ATTEMPTS - self.retries
  98. message = await bot.edit_message(
  99. self.peer_id,
  100. self.message_id,
  101. text=self.text
  102. + f"\n\nYou have **{attempts}** attempt{'' if attempts == 1 else 's'} left.",
  103. file=None if only_text else self.captcha_im,
  104. )
  105. self.message_id = message.id
  106. except Exception:
  107. pass
  108. async def check_captcha(self, captcha):
  109. if self.ban_flag:
  110. await self.kick()
  111. return False
  112. captcha = captcha.replace(" ", "").strip().upper()
  113. if captcha == self.captcha:
  114. del pending[self.peer_id][self.user_id]
  115. try:
  116. await bot.delete_messages(self.peer_id, self.message_id)
  117. except Exception:
  118. pass
  119. return True
  120. self.retries += 1
  121. if self.retries > MAX_CAPTCHA_ATTEMPTS:
  122. await self.kick()
  123. else:
  124. await self.update_captcha(
  125. only_text=not (
  126. len(captcha) == 4
  127. and all(map(lambda c: c in string.ascii_uppercase, captcha))
  128. )
  129. )
  130. return False
  131. async def remove(self):
  132. del pending[self.peer_id][self.user_id]
  133. if self.message_id is not None:
  134. try:
  135. await bot.delete_messages(self.peer_id, self.message_id)
  136. except Exception:
  137. pass
  138. async def kick(self, forever=False):
  139. if self.user_id not in pending[self.peer_id]:
  140. return
  141. await self.remove()
  142. try:
  143. await bot(
  144. EditBannedRequest(
  145. self.peer_id,
  146. self.user_id,
  147. ChatBannedRights(
  148. until_date=None
  149. if forever
  150. else datetime.now() + timedelta(minutes=5),
  151. view_messages=True,
  152. ),
  153. )
  154. )
  155. except Exception:
  156. pass
  157. @bot.on(events.ChatAction)
  158. async def handler(event):
  159. if event.chat_id not in ALLOWED_GROUPS:
  160. return
  161. peer_id = event.chat_id
  162. if (event.user_left or event.user_kicked) and event.user_id in pending[peer_id]:
  163. await pending[peer_id][event.user_id].remove()
  164. return
  165. if not event.user_joined:
  166. return
  167. if event.user_id in whitelist:
  168. return
  169. pending[peer_id][event.user_id] = PendingUser(
  170. peer_id=event.chat_id, user_id=event.user_id
  171. )
  172. if event.user_id in blacklist:
  173. await pending[peer_id][event.user_id].kick()
  174. return
  175. await pending[peer_id][event.user_id].start(event)
  176. @bot.on(events.NewMessage)
  177. async def handler(event):
  178. peer_id = get_peer_id(event.peer_id)
  179. if peer_id not in ALLOWED_GROUPS:
  180. return
  181. if not event.sender:
  182. return
  183. pending_user = pending[peer_id].get(event.sender.id)
  184. if not pending_user:
  185. return
  186. try:
  187. await event.delete()
  188. except Exception:
  189. pass
  190. if time.time() - pending_user.join_ts <= 1.0:
  191. blacklist[event.sender.id] = time.time()
  192. pending_user.ban_flag = True
  193. if pending_user.message_id is None:
  194. return
  195. text = getattr(event, "text", "")
  196. if await pending_user.check_captcha(text):
  197. whitelist[event.sender.id] = time.time()
  198. for peer_id in pending:
  199. if event.sender.id in pending[peer_id]:
  200. await pending[peer_id][event.sender.id].remove()
  201. async def check_pending():
  202. while True:
  203. for peers in dict(pending).values():
  204. for pending_user in dict(peers).values():
  205. if pending_user.expired or pending_user.ban_flag:
  206. await pending_user.kick()
  207. await asyncio.sleep(1)
  208. async def cleanup_whitelist():
  209. while True:
  210. for user_id in dict(whitelist):
  211. ts = whitelist[user_id]
  212. if time.time() - ts >= 30 * 60:
  213. del whitelist[user_id]
  214. await asyncio.sleep(60 * 60)
  215. async def cleanup_blacklist():
  216. while True:
  217. for user_id in dict(blacklist):
  218. ts = blacklist[user_id]
  219. if time.time() - ts >= 86400:
  220. del blacklist[user_id]
  221. await asyncio.sleep(60)
  222. if __name__ == "__main__":
  223. bot.loop.create_task(check_pending())
  224. bot.loop.create_task(cleanup_whitelist())
  225. bot.loop.create_task(cleanup_blacklist())
  226. bot.start()
  227. bot.run_until_disconnected()