from telethon import TelegramClient, events
import re
import datetime
import os

api_id = 6
api_hash = "eb06d4abfb49dc3eeb1aeb98ae0f581e"

client = TelegramClient('session', api_id, api_hash)

patterns = [
    r'ss://[^\s]+',
    r'vmess://[^\s]+',
    r'vless://[^\s]+',
    r'trojan://[^\s]+',
    r'[A-Za-z0-9\/\+=]{30,}',
    r'\{(?:[^{}]|(?R))*\}'
]

save_path = "/var/www/html/configs.txt"
os.makedirs(os.path.dirname(save_path), exist_ok=True)

async def process_message(message):
    if not message.message:
        return

    text = message.message
    found = []
    for pattern in patterns:
        matches = re.findall(pattern, text, flags=re.I | re.S)
        if matches:
            found.extend(matches)

    for config in found:
        time_str = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        chat_id = message.chat_id or 0
        line = f"[{time_str}] [chat_id={chat_id}] [msg_id={message.id}] [from={message.sender_id}] {config}\n"
        with open(save_path, "a", encoding="utf-8") as f:
            f.write(line)
        print(line.strip())

@client.on(events.NewMessage)
async def handler(event):
    await process_message(event.message)

async def main():
    print("✅ Ready - live monitor only, no history scanning")
    await client.run_until_disconnected()

with client:
    client.loop.run_until_complete(main())