Skip to content
TheChatArchiveThe Chat Archive
o3-2025-04-16· OpenAIHugging Face LMArena Human Preference 140K

برام یه ربات تلگرامی بساز وظایف ربات چت ناشناس به سه روش 1 با لینک ساخته شده توسط خود…

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Geminigemini-2.5-pro’s answer.
  1. User

    برام یه ربات تلگرامی بساز وظایف ربات چت ناشناس به سه روش 1 با لینک ساخته شده توسط خود ربات که به صورت کدینگ شده داده میشود 2 با استفاده از ارسال یوزر نیم که بررسی میکند کاربران لاگین شده داخل ربات رو و به کاربر مناسب چت رو برقرار میکنه 3 چت به صورت تصادفی که کاربران آنلاینی که در صف چت تصادفی هستند با استفاده از فیلتر هایی مثل جنسیت و شهر و ... به همدیگر متصل میشوند

    چند مورد مهم داخل این ربات باید تمام اطلاعات کاربران و چت ها به یک ادمین ربات ارسال شود کاربران در حین چت امکان ارسال عکس و استیکر و ویدیو برای هم رو داشته باشند تمام اطلاعات و دیتا های ربات به صورت دیتا بیسی روی سرور ذخیره شود به شکلی که با آپدیت های جزعی بعدی قابل استفاده باشند

    تمام قابلیت ها و امکانات ربات داخل دکمه های اینلاین و کیبورد گذاشته شود

    یک مورد لازم برای چت ها ارسال هر پیام ناشناس دو دکمه زیر پیام باید باشه یکی برای ارسال پاسخ به همون فرستنده پیام که با زدن روی دکمه پیام کاربر رو دریافت کنه و بفرسته برای ارسال کننده پیام قبلی یک دکمه هم به عنوان بلاک که با زدن این دکمه کاربر ارسال کننده پیام دیگه نتواند به این کاربر پیام ارسال کند

    برای چت ناشناس لازمه که هر کاربر یک پروفایل داشته باشد قسمتی درربات که مخصوص پروفایل کاربران و اطلاعات شخصی و عکس و علاقه مندی هاشونو وارد کنند تا در چت تصادفی بر اساس اون همدیگر رو پیدا کنند و برای هم امکان ارسال پروفایل داشته باشند

    نسخه اولیه ربات رو بده تا بعد دوباره اصلاحات لازم رو روش انجام بدیم

  2. Assistant

    🎉 نسخه‌ی اولیه‌ی «ربات چت ناشناس سه‌حالته» (MVP)

    در این نسخه فقط اسکلت اصلی (قابل اجرا) + ساختار دیتابیس و دکمه‌ها را داریم تا بعداً جزئیات و بهینه‌سازی‌ها را اضافه کنیم.

    ───────────────────────── ۱) پیش‌نیازها • Python ≥ 3.10
    • Postgres یا SQLite (برای تست)
    • کتاب‌خانه‌ی aiogram v3

    python -m venv venv && source venv/bin/activate
    pip install -U aiogram[fast] asyncpg python-dotenv
    

    فایل ‌env.‌/. یا متغیّرهای محیطی:

    BOT_TOKEN=xxxxxxxxxxxxxxxxxxxxxxxxxxxx
    ADMIN_ID=123456789   # آیدی عددی ادمین
    DATABASE_URL=postgres://user:pass@localhost:5432/anonbot
    

    ───────────────────────── ۲) ساختار پوشه‌ها

    anonbot/
     ├─ bot.py          # منطق اصلی
     ├─ db.py           # لایه‌ی دیتابیس (async)
     ├─ keyboards.py    # همه‌ی کیبوردها
     ├─ filters.py      # فیلترهای سفارشی (بعداً)
     ├─ config.py       # تنظیمات
     └─ .env
    

    ───────────────────────── ۳) دیتابیس (PostgreSQL)

    -- users & profiles
    CREATE TABLE users(
        tg_id        BIGINT PRIMARY KEY,
        username     TEXT,
        first_name   TEXT,
        last_name    TEXT,
        lang         TEXT,
        joined_at    TIMESTAMP DEFAULT now()
    );
    
    CREATE TABLE profiles(
        user_id      BIGINT REFERENCES users(tg_id) ON DELETE CASCADE,
        gender       TEXT, -- male/female/other
        city         TEXT,
        interests    TEXT,
        photo_id     TEXT,
        updated_at   TIMESTAMP DEFAULT now(),
        PRIMARY KEY (user_id)
    );
    
    -- ناشناس با لینک
    CREATE TABLE link_codes(
        code     TEXT PRIMARY KEY,
        owner_id BIGINT REFERENCES users(tg_id),
        active   BOOLEAN DEFAULT TRUE,
        created_at TIMESTAMP DEFAULT now()
    );
    
    -- بلاک‌ها
    CREATE TABLE blocks(
        blocker_id BIGINT,
        blocked_id BIGINT,
        PRIMARY KEY(blocker_id, blocked_id)
    );
    
    -- صف چت تصادفی
    CREATE TABLE random_queue(
        user_id      BIGINT PRIMARY KEY REFERENCES users(tg_id),
        gender_pref  TEXT,
        city_pref    TEXT,
        joined_at    TIMESTAMP DEFAULT now()
    );
    
    -- سشن/گفت‌وگو
    CREATE TABLE sessions(
        id          SERIAL PRIMARY KEY,
        u1          BIGINT REFERENCES users(tg_id),
        u2          BIGINT REFERENCES users(tg_id),
        mode        TEXT,      -- link | username | random
        active      BOOLEAN DEFAULT TRUE,
        started_at  TIMESTAMP DEFAULT now()
    );
    
    -- پیام‌ها (برای لاگ و فوروارد به ادمین)
    CREATE TABLE messages(
        id          SERIAL PRIMARY KEY,
        session_id  INT REFERENCES sessions(id),
        sender_id   BIGINT,
        content_type TEXT,   -- text/photo/video/...
        payload     TEXT,    -- متن یا file_id
        sent_at     TIMESTAMP DEFAULT now()
    );
    

    ───────────────────────── ۴) کُد (فایل‌های خلاصه)

    🔹 config.py

    import os
    from dotenv import load_dotenv
    load_dotenv()
    
    BOT_TOKEN = os.getenv("BOT_TOKEN")
    ADMIN_ID  = int(os.getenv("ADMIN_ID"))
    DB_DSN    = os.getenv("DATABASE_URL")
    

    🔹 db.py (خیلی خلاصه)

    import asyncpg, uuid
    from config import DB_DSN
    
    class DB:
        def __init__(self): self.pool=None
    
        async def connect(self): self.pool = await asyncpg.create_pool(dsn=DB_DSN)
    
        # ----- کاربران -----
        async def add_user(self, tg_user):
            q="""INSERT INTO users (tg_id,username,first_name,last_name,lang)
                VALUES($1,$2,$3,$4,$5)
                ON CONFLICT (tg_id) DO UPDATE SET username=EXCLUDED.username"""
            await self.pool.execute(q, tg_user.id, tg_user.username,
                                    tg_user.first_name, tg_user.last_name, tg_user.language_code)
    
        async def get_profile(self, uid):
            return await self.pool.fetchrow("SELECT * FROM profiles WHERE user_id=$1", uid)
    
        async def upsert_profile(self, uid, gender, city, interests, photo):
            q = """INSERT INTO profiles(user_id,gender,city,interests,photo_id)
                   VALUES($1,$2,$3,$4,$5)
                   ON CONFLICT(user_id) DO UPDATE SET
                   gender=$2,city=$3,interests=$4,photo_id=$5,updated_at=now()"""
            await self.pool.execute(q, uid, gender, city, interests, photo)
    
        # ----- لینک ناشناس -----
        async def new_link(self, uid):
            code = uuid.uuid4().hex[:8]
            await self.pool.execute("INSERT INTO link_codes(code,owner_id) VALUES($1,$2)", code, uid)
            return code
    
        async def resolve_link(self, code):
            return await self.pool.fetchrow("SELECT * FROM link_codes WHERE code=$1 AND active", code)
    
        # سایر متدها: queue, sessions, blocks ...
    db = DB()
    

    🔹 keyboards.py

    from aiogram.types import InlineKeyboardMarkup, InlineKeyboardButton, ReplyKeyboardMarkup, KeyboardButton
    
    def main_kb():
        return ReplyKeyboardMarkup(resize_keyboard=True, row_width=2, keyboard=[
            [KeyboardButton("💬 چت ناشناس با لینک"), KeyboardButton("🔀 چت تصادفی")],
            [KeyboardButton("👤 پروفایل من")],
        ])
    
    def reply_or_block(sender_id:int):
        return InlineKeyboardMarkup(inline_keyboard=[
            [InlineKeyboardButton("↩️ پاسخ", callback_data=f"reply_{sender_id}"),
             InlineKeyboardButton("🚫 بلاک",  callback_data=f"block_{sender_id}")]
        ])
    

    🔹 bot.py (ساده‌شده)

    import asyncio, logging
    from aiogram import Bot, Dispatcher, types, F
    from aiogram.filters import CommandStart, Command
    from config import BOT_TOKEN, ADMIN_ID
    from db import db
    import keyboards as kb
    
    logging.basicConfig(level=logging.INFO)
    bot = Bot(BOT_TOKEN, parse_mode="HTML")
    dp  = Dispatcher()
    
    # -------------- میدل‌ویر فوروارد به ادمین --------------
    @dp.message()
    async def forward_to_admin(message: types.Message, handler):
        if message.from_user.id != ADMIN_ID:
            try:
                await bot.forward_message(ADMIN_ID, message.chat.id, message.message_id)
            except: pass
        await handler(message)
    
    # -------------- start / menu --------------
    @dp.message(CommandStart())
    async def start(m: types.Message):
        await db.add_user(m.from_user)
        await m.answer("به ربات چت ناشناس خوش آمدید! 👋", reply_markup=kb.main_kb())
    
    # -------------- لینک ناشناس --------------
    @dp.message(F.text=="💬 چت ناشناس با لینک")
    async def anon_link(m: types.Message):
        code = await db.new_link(m.from_user.id)
        link = f"https://t.me/{(await bot.me()).username}?start={code}"
        await m.answer(f"🔗 لینک اختصاصی شما:\n{link}\nآن را برای هر کسی بفرستید!", disable_web_page_preview=True)
    
    @dp.message(Command())
    async def deep_link_router(m: types.Message):
        if m.text.startswith("/start ") and len(m.text.split())==2:
            code = m.text.split()[1]
            rec = await db.resolve_link(code)
            if rec and rec["owner_id"]!=m.from_user.id:
                # ایجاد سشن
                sid = await create_session(rec["owner_id"], m.from_user.id, "link")
                await bot.send_message(rec["owner_id"], "یک نفر با لینک شما وارد چت شد!")
                await m.answer("به چت ناشناس خوش آمدید! 🚀 \nبرای پایان /stop را بزنید.")
                # علامت‌گذاری کانتکستِ جاری (state) => بعداً
            else:
                await m.answer("لینک نامعتبر یا منقضی شده است ❌")
    
    # -------------- چت تصادفی --------------
    @dp.message(F.text=="🔀 چت تصادفی")
    async def random_chat(m: types.Message):
        # بررسی صف...
        await m.answer("🔎 در حال جستجوی فرد مناسب ... /stop برای لغو")
    
    # -------------- مسیج ریلای / بلاک --------------
    @dp.callback_query(F.data.startswith("reply_"))
    async def cb_reply(cq: types.CallbackQuery):
        target = int(cq.data.split("_")[1])
        await cq.message.answer("✉️ پیامت رو بنویس:", reply_markup=types.ForceReply(selective=True))
        # بعداً هندلر ForceReply از روی reply_to_message ...
    
    @dp.callback_query(F.data.startswith("block_"))
    async def cb_block(cq: types.CallbackQuery):
        bad = int(cq.data.split("_")[1])
        await db.pool.execute("INSERT INTO blocks(blocker_id,blocked_id) VALUES($1,$2) ON CONFLICT DO NOTHING",
                               cq.from_user.id, bad)
        await cq.answer("کاربر بلاک شد!")
        await cq.message.edit_reply_markup()  # حذف دکمه‌ها
    
    # -------------- Relay messages between partners --------------
    async def relay(msg: types.Message, partner_id:int):
        kb_under = kb.reply_or_block(msg.from_user.id)
        if msg.photo:
            file_id = msg.photo[-1].file_id
            await bot.send_photo(partner_id, file_id, caption=msg.caption, reply_markup=kb_under)
        elif msg.sticker:
            await bot.send_sticker(partner_id, msg.sticker.file_id, reply_markup=kb_under)
        elif msg.video:
            await bot.send_video(partner_id, msg.video.file_id, caption=msg.caption, reply_markup=kb_under)
        else:
            await bot.send_message(partner_id, msg.text, reply_markup=kb_under)
    
    # -------------- اجرای ربات --------------
    async def main():
        await db.connect()
        await dp.start_polling(bot)
    
    if __name__=="__main__":
        asyncio.run(main())
    

    (توضیح: برای کوتاه شدن، برخی توابع مثل create_session، مدیریت صف، ذخیره‌ی پیام در DB و StateHandler حذف شده‌اند و باید اضافه کنیم.)

    ───────────────────────── ۵) قابلیت‌های حاضر در این نسخه

    ✔️ /start و منوی کیبورد
    ✔️ تولید لینک ناشناس و آغاز چت دوتایی
    ✔️ دکمه‌های «↩️ پاسخ» و «🚫 بلاک» زیر همه‌ی پیام‌ها
    ✔️ فوروارد همه‌ی پیام‌ها به ADMIN_ID
    ✔️ ذخیره‌ی کاربران، لینک‌ها و بلاک‌ها در دیتابیس
    ✔️ پشتیبانی پیام متنی، عکس، ویدیو، استیکر
    ✔️ زیرساخت شروع چت تصادفی و بر اساس یوزرنیم (هنوز کامل نیست)
    ✔️ تمامی دکمه‌ها اینلاین یا ReplyKeyboard

    ───────────────────────── ۶) گام‌های بعدی که می‌توانیم اضافه/اصلاح کنیم

    1. تکمیل صف چت تصادفی + فیلتر بر اساس جنسیت/شهر/سن
    2. مدیریت state‌-ماشین برای هر کاربر (aiogram FSM)
    3. بخش «👤 پروفایل من» (آپلود عکس، ادیت فیلدها)
    4. امکان ارسال پروفایل داخل چت (share profile)
    5. اتمام سشن با /stop یا دکمه‌ی «پایان چت»
    6. اعمال Rate-Limit و آنتی‌اسپم
    7. باتن «گزارش تخلف» برای پیام‌ها
    8. تست واحد + Dockerfile + CI/CD

    ───────────────────────── موفّق باشی! هرجا لازم بود جزئیات بیشتری یا تغییر خواستی خبر بده تا مرحله‌ی بعدی را تکمیل کنیم. 🚀

  3. User

    کل کد رو داخل یک فایل بهم بده

  4. Assistant

    در ادامه یک فایل پایتونی واحد (single-file) به نام anon_chat_bot.py می‌بینی که همان «نسخه‌ی اولیه» است اما تمام قسمت‌ها (Config + DB + Keyboards + Handlerها) را در خود جا داده. کافی است این یک فایل را در پوشه‌‌ی دلخواه قرار دهی، متغیّرهای محیطی یا ثابت‌های بالای فایل را مقدار دهی کنی و اجراش کنی.

    # ─────────────────────────────────────────────
    #  anon_chat_bot.py   (MVP – all-in-one file)
    #  Python 3.10+      aiogram v3
    # ─────────────────────────────────────────────
    """
    ربات چت ناشناس سه‌حالته:
    1) چت با لینک اختصاصی
    2) چت با ارسال یوزرنیم (در آینده)
    3) چت تصادفی فیلترشونده (در آینده)
    
    ویژگی‌ها:
    • فورارد همه‌ی پیام‌ها به ادمین
    • ذخیره‌ی پیام‌ها، کاربران، بلاک‌ها و … در PostgreSQL
    • دکمه‌ی پاسخ ↩️ و بلاک 🚫 زیر هر پیام
    • پشتیبانی متن / عکس / ویدیو / استیکر
    """
    
    import asyncio, logging, os, uuid, textwrap
    from typing import Optional
    
    from aiogram import Bot, Dispatcher, types, F
    from aiogram.filters import CommandStart, Command
    from aiogram.types import (
        InlineKeyboardMarkup, InlineKeyboardButton,
        ReplyKeyboardMarkup, KeyboardButton
    )
    
    import asyncpg
    from dotenv import load_dotenv
    
    # ───────────────────────── CONFIG
    load_dotenv(".env")       # اگر فایل .env موجود بود بخوان
    
    BOT_TOKEN   = os.getenv("BOT_TOKEN",   "PUT_TOKEN_HERE")
    ADMIN_ID    = int(os.getenv("ADMIN_ID", "0"))          # عددی
    DATABASE_URL= os.getenv("DATABASE_URL",
                            "postgres://user:pass@localhost:5432/anonbot")
    
    # ───────────────────────── LOGGING
    logging.basicConfig(level=logging.INFO,
                        format="%(levelname)s | %(name)s | %(message)s")
    log = logging.getLogger("anon-chat")
    
    # ───────────────────────── DATABASE LAYER
    class DB:
        def __init__(self, dsn:str):
            self.dsn = dsn
            self.pool:asyncpg.Pool|None = None
    
        async def connect(self):
            self.pool = await asyncpg.create_pool(dsn=self.dsn, command_timeout=60)
            await self._create_tables()
    
        async def _create_tables(self):
            sql = """
            CREATE TABLE IF NOT EXISTS users(
                tg_id BIGINT PRIMARY KEY,
                username TEXT,
                first_name TEXT,
                last_name TEXT,
                lang TEXT,
                joined_at TIMESTAMP DEFAULT now()
            );
            CREATE TABLE IF NOT EXISTS profiles(
                user_id BIGINT REFERENCES users(tg_id) ON DELETE CASCADE,
                gender TEXT, city TEXT, interests TEXT, photo_id TEXT,
                updated_at TIMESTAMP DEFAULT now(),
                PRIMARY KEY(user_id)
            );
            CREATE TABLE IF NOT EXISTS link_codes(
                code TEXT PRIMARY KEY,
                owner_id BIGINT REFERENCES users(tg_id),
                active BOOLEAN DEFAULT TRUE,
                created_at TIMESTAMP DEFAULT now()
            );
            CREATE TABLE IF NOT EXISTS blocks(
                blocker_id BIGINT,
                blocked_id BIGINT,
                PRIMARY KEY(blocker_id,blocked_id)
            );
            CREATE TABLE IF NOT EXISTS sessions(
                id SERIAL PRIMARY KEY,
                u1 BIGINT REFERENCES users(tg_id),
                u2 BIGINT REFERENCES users(tg_id),
                mode TEXT,        -- link | username | random
                active BOOLEAN DEFAULT TRUE,
                started_at TIMESTAMP DEFAULT now()
            );
            CREATE TABLE IF NOT EXISTS messages(
                id SERIAL PRIMARY KEY,
                session_id INT REFERENCES sessions(id),
                sender_id BIGINT,
                content_type TEXT,
                payload TEXT,
                sent_at TIMESTAMP DEFAULT now()
            );
            """
            await self.pool.execute(sql)
            log.info("Tables ensured.")
    
        # ---------- users
        async def add_user(self, tg:types.User):
            q = """INSERT INTO users(tg_id,username,first_name,last_name,lang)
                   VALUES($1,$2,$3,$4,$5)
                   ON CONFLICT(tg_id) DO UPDATE SET username=EXCLUDED.username"""
            await self.pool.execute(q, tg.id, tg.username,
                                    tg.first_name, tg.last_name, tg.language_code)
    
        # ---------- link codes
        async def new_link(self, uid:int)->str:
            code = uuid.uuid4().hex[:8]
            await self.pool.execute("INSERT INTO link_codes(code,owner_id) VALUES($1,$2)",
                                    code, uid)
            return code
    
        async def resolve_link(self, code:str)->Optional[asyncpg.Record]:
            return await self.pool.fetchrow("SELECT * FROM link_codes WHERE code=$1 AND active", code)
    
        # ---------- blocks
        async def block(self, blocker:int, blocked:int):
            await self.pool.execute(
                "INSERT INTO blocks(blocker_id,blocked_id) VALUES($1,$2) ON CONFLICT DO NOTHING",
                blocker, blocked
            )
    
        async def is_blocked(self, u1:int, u2:int)->bool:
            q="SELECT 1 FROM blocks WHERE blocker_id=$1 AND blocked_id=$2"
            return bool(await self.pool.fetchrow(q, u1, u2))
    
        # ---------- sessions
        async def create_session(self, u1:int, u2:int, mode:str)->int:
            rec = await self.pool.fetchrow(
                "INSERT INTO sessions(u1,u2,mode) VALUES($1,$2,$3) RETURNING id",
                u1, u2, mode
            )
            return rec["id"]
    
        async def close_session(self, sid:int):
            await self.pool.execute("UPDATE sessions SET active=FALSE WHERE id=$1", sid)
    
        # ---------- messages
        async def log_message(self, session_id:int, sender:int, content_type:str, payload:str):
            await self.pool.execute(
                "INSERT INTO messages(session_id,sender_id,content_type,payload) VALUES($1,$2,$3,$4)",
                session_id, sender, content_type, payload
            )
    
    db = DB(DATABASE_URL)
    
    # ─────────────────────────  KEYBOARDS
    def main_kb():
        return ReplyKeyboardMarkup(resize_keyboard=True,row_width=2,keyboard=[
            [KeyboardButton("💬 چت ناشناس با لینک"), KeyboardButton("🔀 چت تصادفی")],
            [KeyboardButton("👤 پروفایل من")]
        ])
    
    def reply_or_block_kb(sender_id:int)->InlineKeyboardMarkup:
        return InlineKeyboardMarkup(inline_keyboard=[
            [InlineKeyboardButton("↩️ پاسخ", callback_data=f"reply_{sender_id}"),
             InlineKeyboardButton("🚫 بلاک",  callback_data=f"block_{sender_id}")]
        ])
    
    # ─────────────────────────  RUNTIME MEMORY (ساده برای MVP)
    active_partner: dict[int,int] = {}   # user_id -> partner_id
    active_session_id: dict[int,int] = {}# user_id -> session_id
    random_queue: set[int] = set()       # user_ids که منتظر چت تصادفی‌اند
    
    # ─────────────────────────  BOT / DISPATCHER
    bot = Bot(BOT_TOKEN, parse_mode="HTML")
    dp  = Dispatcher()
    
    # ─────────────────────────  MIDDLEWARE: forward every msg to ADMIN
    @dp.message()
    async def forward_to_admin(message:types.Message, handler):
        if ADMIN_ID and message.from_user.id != ADMIN_ID:
            try:
                await bot.forward_message(ADMIN_ID, message.chat.id, message.message_id)
            except Exception as e:
                log.warning(f"forward failed: {e}")
        await handler(message)
    
    # ─────────────────────────  HELPERS
    async def start_chat(u1:int, u2:int, mode:str):
        """
        دو کاربر را به هم متصل می‌کند و در دیکشنری active_partner می‌نویسد
        """
        sid = await db.create_session(u1, u2, mode)
        active_partner[u1] = u2
        active_partner[u2] = u1
        active_session_id[u1]=sid
        active_session_id[u2]=sid
    
        await bot.send_message(u1, "✅ ارتباط ناشناس برقرار شد! برای پایان /stop", reply_markup=types.ReplyKeyboardRemove())
        await bot.send_message(u2, "✅ ارتباط ناشناس برقرار شد! برای پایان /stop", reply_markup=types.ReplyKeyboardRemove())
    
    async def stop_chat(uid:int, notify=True):
        if uid not in active_partner: return
        partner = active_partner.pop(uid)
        sid     = active_session_id.pop(uid)
        active_partner.pop(partner, None)
        active_session_id.pop(partner, None)
    
        await db.close_session(sid)
        if notify:
            await bot.send_message(uid, "❌ چت پایان یافت.", reply_markup=main_kb())
            await bot.send_message(partner, "❌ طرف مقابل چت را ترک کرد.", reply_markup=main_kb())
    
    # ─────────────────────────  COMMANDS & MENU
    @dp.message(CommandStart())
    async def cmd_start(m:types.Message):
        await db.add_user(m.from_user)
        # deep-link->code?
        if len(m.text.split())==2:
            code = m.text.split()[1]
            await handle_link_join(m, code)
            return
        await m.answer("سلام! خوش آمدی 👋\nیکی از گزینه‌ها را انتخاب کن:",
                       reply_markup=main_kb())
    
    @dp.message(Command("stop"))
    async def cmd_stop(m:types.Message):
        await stop_chat(m.from_user.id)
    
    # ─────────────────────────  MODE 1 : LINK CHAT
    @dp.message(F.text=="💬 چت ناشناس با لینک")
    async def btn_link(m:types.Message):
        code = await db.new_link(m.from_user.id)
        link = f"https://t.me/{(await bot.me()).username}?start={code}"
        await m.answer(textwrap.dedent(f"""
            🔗 لینک اختصاصی شما:
            {link}
            
            آن را برای دوستانت بفرست. هر کس روی لینک بزند مستقیماً به گفت‌وگوی ناشناس با تو وصل می‌شود.
        """).strip(), disable_web_page_preview=True)
    
    async def handle_link_join(m:types.Message, code:str):
        rec = await db.resolve_link(code)
        if not rec:
            await m.answer("لینک نامعتبر یا منقضی شده است ❌", reply_markup=main_kb())
            return
        owner = rec["owner_id"]
        if owner == m.from_user.id:
            await m.answer("این لینک متعلق به خودت است ☺️", reply_markup=main_kb())
            return
        # چک بلاک‌شدن
        if await db.is_blocked(owner, m.from_user.id) or await db.is_blocked(m.from_user.id, owner):
            await m.answer("متأسفانه نمی‌توان به این کاربر پیام داد.", reply_markup=main_kb())
            return
        # اگر مالک در چت دیگری است؟
        if owner in active_partner:
            await m.answer("کاربر فعلاً مشغول چت است. دوباره حاول کن.", reply_markup=main_kb())
            return
        await start_chat(owner, m.from_user.id, "link")
    
    # ─────────────────────────  MODE 3 : RANDOM (اسکلت)
    @dp.message(F.text=="🔀 چت تصادفی")
    async def btn_random(m:types.Message):
        uid = m.from_user.id
        if uid in random_queue:
            await m.answer("قبلاً در صف هستی. لطفاً منتظر بمان.", reply_markup=types.ReplyKeyboardRemove())
            return
        random_queue.add(uid)
        await m.answer("🔎 در حال جستجو برای پیدا کردن هم‌صحبت ...\n/stop برای لغو", reply_markup=types.ReplyKeyboardRemove())
        await try_match_random()
    
    async def try_match_random():
        if len(random_queue)<2: return
        # دو نفر اول:
        u1 = random_queue.pop()
        u2 = random_queue.pop()
        # TODO: فیلتر جنسیت/شهر و ...
        await start_chat(u1, u2, "random")
    
    # ─────────────────────────  BLOCK / REPLY CALLBACKS
    @dp.callback_query(F.data.startswith("block_"))
    async def cb_block(cq:types.CallbackQuery):
        bad_id = int(cq.data.split("_")[1])
        await db.block(cq.from_user.id, bad_id)
        await cq.answer("✅ کاربر بلاک شد و دیگر نمی‌تواند پیام بدهد.")
        await stop_chat(cq.from_user.id, notify=True)
    
    @dp.callback_query(F.data.startswith("reply_"))
    async def cb_reply(cq:types.CallbackQuery):
        target = int(cq.data.split("_")[1])
        if target not in active_partner.values():
            await cq.answer("چت فعلی موجود نیست.", show_alert=True)
            return
        await cq.message.answer("✉️ پیام پاسخ را بنویس و ارسال کن:",
                                reply_markup=types.ForceReply(selective=True))
        await cq.answer()
    
    # ─────────────────────────  MESSAGE RELAY
    @dp.message(F.reply_to_message.as_("rep") & F.reply_to_message.reply_markup & F.reply_to_message.reply_markup.inline_keyboard)
    async def handle_force_reply(m:types.Message, rep):
        """
        اگر کاربر در ReplyForce چیزی نوشت، به پارتنرش می‌فرستیم.
        """
        uid = m.from_user.id
        if uid not in active_partner:
            await m.answer("فعلاً در چتی نیستی.", reply_markup=main_kb())
            return
        await relay(m)
    
    @dp.message()
    async def ongoing_chat_messages(m:types.Message):
        uid = m.from_user.id
        if uid not in active_partner:
            # در حال چت نیست → نادیده یا پیام راهنما
            return
        await relay(m)
    
    async def relay(msg:types.Message):
        sender = msg.from_user.id
        partner = active_partner.get(sender)
        if not partner:
            return
        sid = active_session_id.get(sender)
        # --------------------------------- فوروارد کاربر → پارتنر
        markup = reply_or_block_kb(sender)
    
        if msg.photo:
            fid = msg.photo[-1].file_id
            await bot.send_photo(partner, fid, caption=msg.caption, reply_markup=markup)
            await db.log_message(sid, sender, "photo", fid)
        elif msg.sticker:
            await bot.send_sticker(partner, msg.sticker.file_id, reply_markup=markup)
            await db.log_message(sid, sender, "sticker", msg.sticker.file_id)
        elif msg.video:
            fid = msg.video.file_id
            await bot.send_video(partner, fid, caption=msg.caption, reply_markup=markup)
            await db.log_message(sid, sender, "video", fid)
        else: # text & others
            await bot.send_message(partner, msg.text.html, reply_markup=markup)
            await db.log_message(sid, sender, "text", msg.html_text)
    
    # ─────────────────────────  RUN
    async def main():
        if BOT_TOKEN=="PUT_TOKEN_HERE":
            print("🙁 لطفاً BOT_TOKEN را تنظیم کنید.")
            return
        await db.connect()
        await dp.start_polling(bot)
    
    if __name__ == "__main__":
        try:
            asyncio.run(main())
        except (KeyboardInterrupt, SystemExit):
            print("Bot stopped.")
    

    راهنمای سریع راه‌اندازی

    1. Python 3.10+ نصب داشته باش.
    2. pip install -U aiogram[fast] asyncpg python-dotenv
    3. یک دیتابیس PostgreSQL بساز (یا DSN مناسب بده).
    4. فایل .env کنار همین اسکریپت بگذار:
      BOT_TOKEN=TOKEN_HERE
      ADMIN_ID=123456789
      DATABASE_URL=postgres://user:pass@localhost:5432/anonbot
      
    5. python anon_chat_bot.py

    همین! 🎉

    نکته: منطق چت تصادفی پیشرفته (فیلتر بر اساس جنسیت/شهر) و چت بر اساس Username هنوز TO-DO است. در نسخه‌های بعدی می‌توانیم اضافه یا بهینه کنیم.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.