import logging
import sqlite3
import random
import string
from datetime import datetime
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup, KeyboardButton, ReplyKeyboardMarkup
from telegram.ext import Application, CommandHandler, MessageHandler, CallbackQueryHandler, filters, ContextTypes
import asyncio
# تنظیمات لاگینگ
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
logger = logging.getLogger(__name__)
# توکن ربات و آیدی ادمین
BOT_TOKEN = "YOUR_BOT_TOKEN_HERE"
ADMIN_ID = 123456789 # آیدی عددی ادمین را اینجا قرار دهید
# ایجاد دیتابیس
def init_db():
conn = sqlite3.connect('anonymous_chat.db')
c = conn.cursor()
# جدول کاربران
c.execute('''CREATE TABLE IF NOT EXISTS users
(user_id INTEGER PRIMARY KEY,
username TEXT,
first_name TEXT,
last_name TEXT,
gender TEXT,
city TEXT,
age INTEGER,
bio TEXT,
profile_pic TEXT,
interests TEXT,
created_at TIMESTAMP,
is_active INTEGER DEFAULT 1)''')
# جدول چتها
c.execute('''CREATE TABLE IF NOT EXISTS chats
(chat_id INTEGER PRIMARY KEY AUTOINCREMENT,
user1_id INTEGER,
user2_id INTEGER,
chat_type TEXT,
link_code TEXT,
started_at TIMESTAMP,
ended_at TIMESTAMP,
is_active INTEGER DEFAULT 1)''')
# جدول پیامها
c.execute('''CREATE TABLE IF NOT EXISTS messages
(message_id INTEGER PRIMARY KEY AUTOINCREMENT,
chat_id INTEGER,
sender_id INTEGER,
receiver_id INTEGER,
message_text TEXT,
message_type TEXT,
file_id TEXT,
sent_at TIMESTAMP)''')
# جدول بلاکها
c.execute('''CREATE TABLE IF NOT EXISTS blocks
(blocker_id INTEGER,
blocked_id INTEGER,
blocked_at TIMESTAMP,
PRIMARY KEY (blocker_id, blocked_id))''')
# جدول صف چت تصادفی
c.execute('''CREATE TABLE IF NOT EXISTS random_queue
(user_id INTEGER PRIMARY KEY,
gender_preference TEXT,
city_preference TEXT,
joined_at TIMESTAMP)''')
conn.commit()
conn.close()
# تولید کد لینک
def generate_link_code():
return ''.join(random.choices(string.ascii_letters + string.digits, k=8))
# دکمههای منوی اصلی
def get_main_menu():
keyboard = [
[KeyboardButton("🔗 ساخت لینک چت"), KeyboardButton("👤 پروفایل من")],
[KeyboardButton("🎲 چت تصادفی"), KeyboardButton("✉️ چت با یوزرنیم")],
[KeyboardButton("📊 آمار من"), KeyboardButton("❓ راهنما")]
]
return ReplyKeyboardMarkup(keyboard, resize_keyboard=True)
# شروع ربات
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
user = update.effective_user
user_id = user.id
# ذخیره کاربر در دیتابیس
conn = sqlite3.connect('anonymous_chat.db')
c = conn.cursor()
c.execute("INSERT OR IGNORE INTO users (user_id, username, first_name, last_name, created_at) VALUES (?, ?, ?, ?, ?)",
(user_id, user.username, user.first_name, user.last_name, datetime.now()))
conn.commit()
conn.close()
# ارسال اطلاعات کاربر جدید به ادمین
if user_id != ADMIN_ID:
admin_message = f"👤 کاربر جدید:\nID: {user_id}\nUsername: @{user.username}\nName: {user.first_name} {user.last_name}"
await context.bot.send_message(chat_id=ADMIN_ID, text=admin_message)
welcome_message = f"""سلام {user.first_name} عزیز! 👋
به ربات چت ناشناس خوش آمدید! 🎭
از منوی زیر گزینه مورد نظر خود را انتخاب کنید:"""
await update.message.reply_text(welcome_message, reply_markup=get_main_menu())
# ساخت لینک چت
async def create_chat_link(update: Update, context: ContextTypes.DEFAULT_TYPE):
user_id = update.effective_user.id
link_code = generate_link_code()
# ذخیره در دیتابیس
conn = sqlite3.connect('anonymous_chat.db')
c = conn.cursor()
c.execute("INSERT INTO chats (user1_id, chat_type, link_code, started_at) VALUES (?, ?, ?, ?)",
(user_id, 'link', link_code, datetime.now()))
conn.commit()
conn.close()
bot_username = (await context.bot.get_me()).username
link = f"https://t.me/{bot_username}?start={link_code}"
message = f"""🔗 لینک چت ناشناس شما آماده است!
{link}
این لینک را برای دوستتان ارسال کنید تا چت ناشناس شروع شود.
⚠️ توجه: این لینک فقط برای یک نفر قابل استفاده است."""
await update.message.reply_text(message)
# مدیریت پروفایل
async def profile_menu(update: Update, context: ContextTypes.DEFAULT_TYPE):
keyboard = [
[InlineKeyboardButton("📝 ویرایش نام", callback_data="edit_name")],
[InlineKeyboardButton("👤 تنظیم جنسیت", callback_data="edit_gender")],
[InlineKeyboardButton("🏙 تنظیم شهر", callback_data="edit_city")],
[InlineKeyboardButton("📸 تنظیم عکس پروفایل", callback_data="edit_photo")],
[InlineKeyboardButton("💬 درباره من", callback_data="edit_bio")],
[InlineKeyboardButton("🎯 علاقهمندیها", callback_data="edit_interests")],
[InlineKeyboardButton("👁 مشاهده پروفایل", callback_data="view_profile")]
]
reply_markup = InlineKeyboardMarkup(keyboard)
await update.message.reply_text("🔧 تنظیمات پروفایل:", reply_markup=reply_markup)
# چت تصادفی
async def random_chat(update: Update, context: ContextTypes.DEFAULT_TYPE):
user_id = update.effective_user.id
keyboard = [
[InlineKeyboardButton("👥 همه", callback_data="random_all")],
[InlineKeyboardButton("👨 پسر", callback_data="random_male"),
InlineKeyboardButton("👩 دختر", callback_data="random_female")],
[InlineKeyboardButton("🏙 همشهری", callback_data="random_city")]
]
reply_markup = InlineKeyboardMarkup(keyboard)
await update.message.reply_text("🎲 فیلتر چت تصادفی را انتخاب کنید:", reply_markup=reply_markup)
# ارسال پیام ناشناس
async def send_anonymous_message(sender_id, receiver_id, message_text, context):
# بررسی بلاک
conn = sqlite3.connect('anonymous_chat.db')
c = conn.cursor()
c.execute("SELECT * FROM blocks WHERE blocker_id = ? AND blocked_id = ?", (receiver_id, sender_id))
if c.fetchone():
await context.bot.send_message(chat_id=sender_id, text="❌ متأسفانه این کاربر شما را بلاک کرده است.")
conn.close()
return
# ذخیره پیام
c.execute("INSERT INTO messages (sender_id, receiver_id, message_text, message_type, sent_at) VALUES (?, ?, ?, ?, ?)",
(sender_id, receiver_id, message_text, 'text', datetime.now()))
conn.commit()
conn.close()
# ارسال پیام به گیرنده
keyboard = [
[InlineKeyboardButton("💬 پاسخ", callback_data=f"reply_{sender_id}"),
InlineKeyboardButton("🚫 بلاک", callback_data=f"block_{sender_id}")]
]
reply_markup = InlineKeyboardMarkup(keyboard)
await context.bot.send_message(
chat_id=receiver_id,
text=f"💌 پیام ناشناس:\n\n{message_text}",
reply_markup=reply_markup
)
# ارسال کپی به ادمین
admin_message = f"""📨 پیام جدید:
از: {sender_id}
به: {receiver_id}
متن: {message_text}"""
await context.bot.send_message(chat_id=ADMIN_ID, text=admin_message)
# مدیریت callback ها
async def button_callback(update: Update, context: ContextTypes.DEFAULT_TYPE):
query = update.callback_query
await query.answer()
data = query.data
user_id = query.from_user.id
if data.startswith("reply_"):
target_id = int(data.split("_")[1])
context.user_data['reply_to'] = target_id
await query.message.reply_text("💬 پیام خود را بنویسید:")
elif data.startswith("block_"):
blocked_id = int(data.split("_")[1])
conn = sqlite3.connect('anonymous_chat.db')
c = conn.cursor()
c.execute("INSERT OR IGNORE INTO blocks (blocker_id, blocked_id, blocked_at) VALUES (?, ?, ?)",
(user_id, blocked_id, datetime.now()))
conn.commit()
conn.close()
await query.message.reply_text("✅ کاربر بلاک شد.")
elif data.startswith("random_"):
# اضافه کردن به صف چت تصادفی
preference = data.split("_")[1]
conn = sqlite3.connect('anonymous_chat.db')
c = conn.cursor()
c.execute("INSERT OR REPLACE INTO random_queue (user_id, gender_preference, joined_at) VALUES (?, ?, ?)",
(user_id, preference, datetime.now()))
conn.commit()
# جستجوی جفت
if preference == "all":
c.execute("SELECT user_id FROM random_queue WHERE user_id != ? LIMIT 1", (user_id,))
else:
# پیادهسازی فیلترها در نسخههای بعدی
c.execute("SELECT user_id FROM random_queue WHERE user_id != ? LIMIT 1", (user_id,))
match = c.fetchone()
if match:
match_id = match[0]
# حذف از صف
c.execute("DELETE FROM random_queue WHERE user_id IN (?, ?)", (user_id, match_id))
# ایجاد چت
c.execute("INSERT INTO chats (user1_id, user2_id, chat_type, started_at) VALUES (?, ?, ?, ?)",
(user_id, match_id, 'random', datetime.now()))
conn.commit()
# اطلاع به هر دو کاربر
await context.bot.send_message(chat_id=user_id, text="✅ چت شروع شد! پیام خود را ارسال کنید.")
await context.bot.send_message(chat_id=match_id, text="✅ چت شروع شد! پیام خود را ارسال کنید.")
context.user_data['active_chat'] = match_id
else:
await query.message.reply_text("⏳ در صف انتظار قرار گرفتید...")
conn.close()
# مدیریت پیامهای متنی
async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
user_id = update.effective_user.id
message_text = update.message.text
# بررسی دکمههای منو
if message_text == "🔗 ساخت لینک چت":
await create_chat_link(update, context)
elif message_text == "👤 پروفایل من":
await profile_menu(update, context)
elif message_text == "🎲 چت تصادفی":
await random_chat(update, context)
elif message_text == "✉️ چت با یوزرنیم":
await update.message.reply_text("یوزرنیم کاربر مورد نظر را بدون @ ارسال کنید:")
context.user_data['waiting_username'] = True
elif message_text == "❓ راهنما":
help_text = """📖 راهنمای استفاده:
1️⃣ ساخت لینک چت: لینکی بسازید و به دوستتان بدهید
2️⃣ چت تصادفی: با افراد ناشناس چت کنید
3️⃣ چت با یوزرنیم: با وارد کردن یوزرنیم چت کنید
4️⃣ پروفایل: اطلاعات خود را تکمیل کنید
⚠️ قوانین: احترام به دیگران الزامی است!"""
await update.message.reply_text(help_text)
else:
# بررسی وضعیتهای مختلف
if context.user_data.get('reply_to'):
target_id = context.user_data['reply_to']
await send_anonymous_message(user_id, target_id, message_text, context