File size: 2,164 Bytes
e581a8c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
from pyrogram import Client, filters
from pyrogram.types import ChatMemberUpdated
from Backend.config import Telegram
from Backend import db
from datetime import datetime
from Backend.logger import LOGGER
from pyrogram.enums import ChatMemberStatus

@Client.on_chat_member_updated()
async def on_user_join(client: Client, chat_member_updated: ChatMemberUpdated):
    if not Telegram.SUBSCRIPTION:
        return

    # Check if this update is for the subscription group
    if chat_member_updated.chat.id != Telegram.SUBSCRIPTION_GROUP_ID:
        return

    # Check if it's a join event (user was not a member, now is a member)
    old_status = chat_member_updated.old_chat_member.status if chat_member_updated.old_chat_member else None
    new_status = chat_member_updated.new_chat_member.status if chat_member_updated.new_chat_member else None
    
    if new_status == ChatMemberStatus.MEMBER:
        user = chat_member_updated.new_chat_member.user
        
        # Verify subscription
        db_user = await db.get_user(user.id)
        is_active = False
        if db_user and db_user.get("subscription_status") == "active":
            if db_user.get("subscription_expiry") and db_user.get("subscription_expiry") > datetime.utcnow():
                is_active = True
                
        if not is_active:
            try:
                # Kick the user
                await client.ban_chat_member(chat_member_updated.chat.id, user.id)
                await client.unban_chat_member(chat_member_updated.chat.id, user.id)
                LOGGER.info(f"Kicked unauthorized user {user.id} from group {chat_member_updated.chat.id}")
                
                # Notify them
                await client.send_message(
                    user.id,
                    "❌ <b>Access Denied</b>\n\n"
                    "You were removed from the private group because you do not have an active subscription.\n"
                    "Please press /start in this bot to purchase or renew your subscription."
                )
            except Exception as e:
                LOGGER.error(f"Failed to kick/notify unauthorized user {user.id}: {e}")