123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316 |
- import os
- import time
- import random
- import string
- import asyncio
- from datetime import datetime, timedelta
- import aiohttp
- from dotenv import load_dotenv
- from telethon import TelegramClient, events
- from telethon.utils import get_peer_id, get_display_name
- from telethon.tl.functions.channels import EditBannedRequest
- from telethon.tl.types import ChatBannedRights
- from captcha.image import ImageCaptcha
- def get_user_name(user):
- full_name = get_display_name(user)
- if not full_name:
- full_name = user.username
- if not full_name:
- full_name = "user"
- return full_name
- def get_link_to_user(user):
- full_name = get_user_name(user)
- if user.username:
- return f"[{full_name}](@{user.username})"
- return f"[{full_name}](tg://user?id={user.id})"
- load_dotenv()
- API_ID = int(os.getenv("API_ID"))
- API_HASH = os.getenv("API_HASH")
- BOT_TOKEN = os.getenv("BOT_TOKEN")
- ALLOWED_GROUPS = set(
- map(lambda cid: int("-100" + cid), os.getenv("ALLOWED_GROUPS").split(","))
- )
- CAPTCHA_WAIT_TIME = int(os.getenv("CAPTCHA_WAIT_TIME", 80))
- MAX_CAPTCHA_ATTEMPTS = int(os.getenv("MAX_CAPTCHA_ATTEMPTS", 8))
- USE_LOLS_API = os.getenv("USE_LOLS_API", "yes") == "yes"
- bot = TelegramClient("captcha_bot", API_ID, API_HASH).start(bot_token=BOT_TOKEN)
- pending = {peer_id: {} for peer_id in ALLOWED_GROUPS}
- whitelist = {}
- blacklist = {}
- async def lols_check(user_id):
- try:
- async with aiohttp.ClientSession() as session:
- async with session.get(
- f"https://api.lols.bot/account?id={user_id}"
- ) as response:
- data = await response.json()
- banned = data.get("banned", False)
- scammer = data.get("scammer", False)
- return not banned and not scammer
- except Exception:
- pass
- return True
- class PendingUser:
- def __init__(self, peer_id, user_id):
- self.peer_id = peer_id
- self.user_id = user_id
- self.ban_flag = False
- self.text = None
- self.message_id = None
- self.captcha = None
- self.captcha_im = None
- self.join_ts = time.time()
- self.retries = 0
- @property
- def expired(self):
- return time.time() - self.join_ts >= CAPTCHA_WAIT_TIME
- async def start(self, event):
- if USE_LOLS_API:
- if not await lols_check(self.user_id):
- blacklist[self.user_id] = time.time()
- await self.kick(forever=True)
- return
- await self.update_captcha()
- if self.user_id not in pending[self.peer_id]:
- return
- if self.ban_flag:
- return
- 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."
- message = await bot.send_message(
- event.chat_id,
- self.text,
- file=self.captcha_im,
- )
- self.message_id = message
- if self.user_id not in pending[self.peer_id]:
- try:
- await bot.delete_messages(self.peer_id, self.message_id)
- except Exception:
- pass
- async def update_captcha(self, only_text=False):
- if not only_text:
- self.captcha = "".join(random.sample(string.ascii_uppercase, 4))
- self.captcha_im = ImageCaptcha().generate(self.captcha)
- self.captcha_im.name = "captcha.png"
- if self.message_id is not None:
- try:
- attempts = MAX_CAPTCHA_ATTEMPTS - self.retries
- message = await bot.edit_message(
- self.peer_id,
- self.message_id,
- text=self.text
- + f"\n\nYou have **{attempts}** attempt{'' if attempts == 1 else 's'} left.",
- file=None if only_text else self.captcha_im,
- )
- self.message_id = message.id
- except Exception:
- pass
- async def check_captcha(self, captcha):
- if self.ban_flag:
- await self.kick()
- return False
- captcha = captcha.replace(" ", "").strip().upper()
- if captcha == self.captcha:
- del pending[self.peer_id][self.user_id]
- try:
- await bot.delete_messages(self.peer_id, self.message_id)
- except Exception:
- pass
- return True
- self.retries += 1
- if self.retries > MAX_CAPTCHA_ATTEMPTS:
- await self.kick()
- else:
- await self.update_captcha(
- only_text=not (
- len(captcha) == 4
- and all(map(lambda c: c in string.ascii_uppercase, captcha))
- )
- )
- return False
- async def remove(self):
- del pending[self.peer_id][self.user_id]
- if self.message_id is not None:
- try:
- await bot.delete_messages(self.peer_id, self.message_id)
- except Exception:
- pass
- async def kick(self, forever=False):
- if self.user_id not in pending[self.peer_id]:
- return
- await self.remove()
- try:
- await bot(
- EditBannedRequest(
- self.peer_id,
- self.user_id,
- ChatBannedRights(
- until_date=None
- if forever
- else datetime.now() + timedelta(minutes=5),
- view_messages=True,
- ),
- )
- )
- except Exception:
- pass
- @bot.on(events.ChatAction)
- async def handler(event):
- if event.chat_id not in ALLOWED_GROUPS:
- return
- peer_id = event.chat_id
- if (event.user_left or event.user_kicked) and event.user_id in pending[peer_id]:
- await pending[peer_id][event.user_id].remove()
- return
- if not event.user_joined:
- return
- if event.user_id in whitelist:
- return
- pending[peer_id][event.user_id] = PendingUser(
- peer_id=event.chat_id, user_id=event.user_id
- )
- if event.user_id in blacklist:
- await pending[peer_id][event.user_id].kick()
- return
- await pending[peer_id][event.user_id].start(event)
- @bot.on(events.NewMessage)
- async def handler(event):
- peer_id = get_peer_id(event.peer_id)
- if peer_id not in ALLOWED_GROUPS:
- return
- if not event.sender:
- return
- pending_user = pending[peer_id].get(event.sender.id)
- if not pending_user:
- return
- try:
- await event.delete()
- except Exception:
- pass
- if time.time() - pending_user.join_ts <= 1.0:
- blacklist[event.sender.id] = time.time()
- pending_user.ban_flag = True
- if pending_user.message_id is None:
- return
- text = getattr(event, "text", "")
- if await pending_user.check_captcha(text):
- whitelist[event.sender.id] = time.time()
- for peer_id in pending:
- if event.sender.id in pending[peer_id]:
- await pending[peer_id][event.sender.id].remove()
- async def check_pending():
- while True:
- for peers in dict(pending).values():
- for pending_user in dict(peers).values():
- if pending_user.expired or pending_user.ban_flag:
- await pending_user.kick()
- await asyncio.sleep(1)
- async def cleanup_whitelist():
- while True:
- for user_id in dict(whitelist):
- ts = whitelist[user_id]
- if time.time() - ts >= 30 * 60:
- del whitelist[user_id]
- await asyncio.sleep(60 * 60)
- async def cleanup_blacklist():
- while True:
- for user_id in dict(blacklist):
- ts = blacklist[user_id]
- if time.time() - ts >= 86400:
- del blacklist[user_id]
- await asyncio.sleep(60)
- if __name__ == "__main__":
- bot.loop.create_task(check_pending())
- bot.loop.create_task(cleanup_whitelist())
- bot.loop.create_task(cleanup_blacklist())
- bot.start()
- bot.run_until_disconnected()
|