import logging
import sqlite3
import base64
import json
from uuid import uuid4
from telegram import (
Update, InlineKeyboardButton, InlineKeyboardMarkup, ReplyKeyboardMarkup, KeyboardButton,
InputMediaPhoto, InputMediaVideo
)
from telegram.ext import (
ApplicationBuilder, CommandHandler, MessageHandler, filters, CallbackQueryHandler, ContextTypes
)
# تنظیمات اولیه
TOKEN = "YOUR_BOT_TOKEN"
ADMIN_ID = 123456789 # شناسه ادمین تلگرام
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO
)
# دیتابیس
conn = sqlite3.connect("chatbot.db", check_same_thread=False)
cursor = conn.cursor()
# ساخت جداول
cursor.execute('''
CREATE TABLE IF NOT EXISTS users (
user_id INTEGER PRIMARY KEY,
username TEXT,
gender TEXT,
city TEXT,
profile TEXT,
blocked_users TEXT DEFAULT ''
)
''')
cursor.execute('''
CREATE TABLE IF NOT EXISTS chats (
chat_id TEXT PRIMARY KEY,
user1 INTEGER,
user2 INTEGER,
FOREIGN KEY(user1) REFERENCES users(user_id),
FOREIGN KEY(user2) REFERENCES users(user_id)
)
''')
cursor.execute('''
CREATE TABLE IF NOT EXISTS messages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
chat_id TEXT,
sender INTEGER,
message_type TEXT,
content TEXT,
FOREIGN KEY(chat_id) REFERENCES chats(chat_id),
FOREIGN KEY(sender) REFERENCES users(user_id)
)
''')
conn.commit()
# کمک برای ارسال پیام به ادمین
async def send_to_admin(context: ContextTypes.DEFAULT_TYPE, text: str):
await context.bot.send_message(ADMIN_ID, text)
# ساخت لینک کدینگ شده
def encode_chat_link(user1, user2):
data = json.dumps({"u1": user1, "u2": user2})
return base64.urlsafe_b64encode(data.encode()).decode()
def decode_chat_link(link):
try:
data = base64.urlsafe_b64decode(link.encode()).decode()
obj = json.loads(data)
return obj["u1"], obj["u2"]
except Exception:
return None, None
# ذخیره یا آپدیت پروفایل کاربر
def save_profile(user_id, username, gender=None, city=None, profile=None):
cursor.execute("SELECT * FROM users WHERE user_id=?", (user_id,))
if cursor.fetchone():
cursor.execute("UPDATE users SET username=?, gender=?, city=?, profile=? WHERE user_id=?",
(username, gender, city, profile, user_id))
else:
cursor.execute("INSERT INTO users (user_id, username, gender, city, profile) VALUES (?, ?, ?, ?, ?)",
(user_id, username, gender, city, profile))
conn.commit()
# بررسی بلاک بودن
def is_blocked(user_id, target_id):
cursor.execute("SELECT blocked_users FROM users WHERE user_id=?", (user_id,))
row = cursor.fetchone()
if row:
blocked = row[0].split(",") if row[0] else []
return str(target_id) in blocked
return False
# بلاک کردن کاربر
def block_user(user_id, target_id):
cursor.execute("SELECT blocked_users FROM users WHERE user_id=?", (user_id,))
row = cursor.fetchone()
if row:
blocked = row[0].split(",") if row[0] else []
if str(target_id) not in blocked:
blocked.append(str(target_id))
cursor.execute("UPDATE users SET blocked_users=? WHERE user_id=?", (",".join(blocked), user_id))
conn.commit()
# ساخت چت جدید
def create_chat(user1, user2):
chat_id = str(uuid4())
cursor.execute("INSERT INTO chats (chat_id, user1, user2) VALUES (?, ?, ?)", (chat_id, user1, user2))
conn.commit()
return chat_id
# پیدا کردن چت بین دو کاربر
def find_chat(user1, user2):
cursor.execute("SELECT chat_id FROM chats WHERE (user1=? AND user2=?) OR (user1=? AND user2=?)",
(user1, user2, user2, user1))
row = cursor.fetchone()
return row[0] if row else None
# ذخیره پیام
def save_message(chat_id, sender, message_type, content):
cursor.execute("INSERT INTO messages (chat_id, sender, message_type, content) VALUES (?, ?, ?, ?)",
(chat_id, sender, message_type, content))
conn.commit()
# دکمههای پاسخ و بلاک
def get_reply_block_buttons(sender_id):
buttons = [
InlineKeyboardButton("پاسخ", callback_data=f"reply_{sender_id}"),
InlineKeyboardButton("بلاک", callback_data=f"block_{sender_id}")
]
return InlineKeyboardMarkup([buttons])
# استارت و خوش آمدگویی
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
user = update.effective_user
save_profile(user.id, user.username or "")
keyboard = [
[KeyboardButton("شروع چت با لینک"), KeyboardButton("شروع چت با یوزرنیم")],
[KeyboardButton("شروع چت تصادفی"), KeyboardButton("پروفایل من")]
]
await update.message.reply_text(
"سلام! لطفا یکی از روشهای چت ناشناس را انتخاب کنید:",
reply_markup=ReplyKeyboardMarkup(keyboard, resize_keyboard=True)
)
# دریافت پیام متنی
async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
user = update.effective_user
text = update.message.text
# بررسی دستورات ساده
if text == "شروع چت با لینک":
# ساخت لینک جدید با کاربر فعلی و یک کاربر تصادفی (مثلا ادمین برای تست)
chat_id = create_chat(user.id, ADMIN_ID)
link = encode_chat_link(user.id, ADMIN_ID)
await update.message.reply_text(f"لینک چت شما:\nhttps://t.me/YourBotUsername?start={link}")
return
elif text == "شروع چت با یوزرنیم":
await update.message.reply_text("لطفا یوزرنیم کاربر مورد نظر را ارسال کنید (بدون @):")
context.user_data["awaiting_username"] = True
return
elif text == "شروع چت تصادفی":
await update.message.reply_text("در نسخه اولیه این بخش فعال نیست. به زودی اضافه میشود.")
return
elif text == "پروفایل من":
cursor.execute("SELECT gender, city, profile FROM users WHERE user_id=?", (user.id,))
row = cursor.fetchone()
if row:
gender, city, profile = row
await update.message.reply_text(f"پروفایل شما:\nجنسیت: {gender}\nشهر: {city}\nدرباره من: {profile}")
else:
await update.message.reply_text("شما هنوز پروفایل خود را ثبت نکردهاید.")
return
# اگر منتظر یوزرنیم بودیم
if context.user_data.get("awaiting_username"):
username = text.strip().lstrip("@")
cursor.execute("SELECT user_id FROM users WHERE username=?", (username,))
row = cursor.fetchone()
if row:
target_id = row[0]
if is_blocked(target_id, user.id):
await update.message.reply_text("شما توسط این کاربر بلاک شدهاید.")
return
chat_id = find_chat(user.id, target_id)
if not chat_id:
chat_id = create_chat(user.id, target_id)
context.user_data["chat_id"] = chat_id
context.user_data["chat_partner"] = target_id
await update.message.reply_text("چت با کاربر شروع شد. پیام خود را ارسال کنید.")
else:
await update.message.reply_text("کاربری با این یوزرنیم یافت نشد.")
context.user_data["awaiting_username"] = False
return
# اگر در چت هستیم پیام را ارسال کنیم
chat_id = context.user_data.get("chat_id")
partner = context.user_data.get("chat_partner")
if chat_id and partner:
if is_blocked(partner, user.id):
await update.message.reply_text("شما توسط این کاربر بلاک شدهاید.")
return
# ذخیره پیام
save_message(chat_id, user.id, "text", text)
# ارسال پیام به طرف مقابل
try:
await context.bot.send_message(partner, f"پیام ناشناس:\n{text}", reply_markup=get_reply_block_buttons(user.id))
except Exception as e:
await update.message.reply_text("ارسال پیام به کاربر مقابل با خطا مواجه شد.")
# ارسال به ادمین
await send_to_admin(context, f"پیام از {user.id} به {partner}:\n{text}")
else:
await update.message.reply_text("شما در هیچ چتی نیستید. لطفا ابتدا چت را شروع کنید.")
# هندلر دکمههای پاسخ و بلاک
async def button_handler(update: Update, context: ContextTypes.DEFAULT_TYPE):
query = update.callback_query
await query.answer()
data = query.data
user = query.from_user
if data.startswith("reply_"):
sender_id = int(data.split("_")[1])
context.user_data["reply_to"] = sender_id
await query.message.reply_text("پیام خود را برای پاسخ ارسال کنید:")
elif data.startswith("block_"):
block_id = int(data.split("_")[1])
block_user(user.id, block_id)
await query.message.reply_text("کاربر بلاک شد. دیگر پیامهای او را دریافت نخواهید کرد.")
# پاسخ به پیام ناشناس
async def reply_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
user = update.effective_user
reply_to = context.user_data.get("reply_to")
if reply_to:
text = update.message.text
chat_id = find_chat(user.id, reply_to)
if not chat_id:
chat_id = create_chat(user.id, reply_to)
if is_blocked(reply_to, user.id):
await update.message.reply_text("شما توسط این کاربر بلاک شدهاید.")
return
save_message(chat_id, user.id, "text", text)
try:
await context.bot.send_message(reply_to, f"پیام ناشناس:\n{text}", reply_markup=get_reply_block_buttons(user.id))
except Exception:
await update.message.reply_text("ارسال پیام به کاربر مقابل با خطا مواجه شد.")
await send_to_admin(context, f"پیام پاسخ از {user.id} به {reply_to}:\n{text}")
context.user_data["reply_to"] = None
else:
await handle_message(update, context)
# هندلر پیامهای غیر متنی (عکس، ویدیو، استیکر)
async def media_handler(update: Update, context: ContextTypes.DEFAULT_TYPE):
user = update.effective_user
chat_id = context.user_data.get("chat_id")
partner = context.user_data.get("chat_partner")
if not chat_id or not partner:
await update.message.reply_text("شما در هیچ چتی نیستید. لطفا ابتدا چت را شروع کنید.")
return
if is_blocked(partner, user.id):
await update.message.reply_text("شما توسط این کاربر بلاک شدهاید.")
return
msg = update.message
content = None
msg_type = None
if msg.photo:
file_id = msg.photo[-1].file_id
content = file_id
msg_type = "photo"
elif msg.video:
file_id = msg.video.file_id
content = file_id
msg_type = "video"
elif msg.sticker:
file_id = msg.sticker.file_id
content = file_id
msg_type = "sticker"
else:
await update.message.reply_text("نوع پیام پشتیبانی نمیشود.")
return
save_message(chat_id, user.id, msg_type, content)
# ارسال به طرف مقابل
try:
if msg_type == "photo":
await context.bot.send_photo(partner, content, caption="پیام ناشناس", reply_markup=get_reply_block_buttons(user.id))
elif msg_type == "video":
await context.bot.send_video(partner, content, caption="پیام ناشناس", reply_markup=get_reply_block_buttons(user.id))
elif msg_type == "sticker":
await context.bot.send_sticker(partner, content)
except Exception:
await update.message.reply_text("ارسال پیام به کاربر مقابل با خطا مواجه شد.")
# ارسال به ادمین
await send_to_admin(context, f"پیام {msg_type} از {user.id} به {partner}")
# هندلر استارت با پارامتر (لینک کدینگ شده)
async def start_with_param(update: Update, context: ContextTypes.DEFAULT_TYPE):
user = update.effective_user
args = context.args
if not args:
await start(update, context)
return
link = args[0]
u1, u2 = decode_chat_link(link)
if not u1 or not u2:
await update.message.reply_text("لینک نامعتبر است.")
return
# اگر کاربر در لینک نیست، اجازه ندهیم
if user.id not in (u1, u2):
await update.message.reply_text("شما اجازه دسترسی به این چت را ندارید.")
return
chat_id = find_chat(u1, u2)
if not chat_id:
chat_id = create_chat(u1, u2)
partner = u2 if user.id == u1 else u1
context.user_data["chat_id"] = chat_id
context.user_data["chat_partner"] = partner
await update.message.reply_text("چت ناشناس با لینک شروع شد. پیام خود را ارسال کنید.")
# ثبت پروفایل (مثال ساده)
async def set_profile(update: Update, context: ContextTypes.DEFAULT_TYPE):
user = update.effective_user
args = context.args
if len(args) < 3:
await update.message.reply_text("برای ثبت پروفایل از دستور زیر استفاده کنید:\n/setprofile جنسیت شهر درباره_من")
return
gender, city, *profile = args
profile_text = " ".join(profile)
save_profile(user.id, user.username or "", gender, city, profile_text)
await update.message.reply_text("پروفایل شما ثبت شد.")
# main
async def main():
app = ApplicationBuilder().token(TOKEN).build()
app.add_handler(CommandHandler("start", start_with_param))
app.add_handler(CommandHandler("setprofile", set_profile))
app.add_handler(CallbackQueryHandler(button_handler))
app.add_handler(MessageHandler(filters.PHOTO | filters.VIDEO | filters.STICKER, media_handler))
app.add_handler(MessageHandler(filters.TEXT & (~filters.COMMAND), reply_message))
await app.run_polling()
if __name__ == "__main__":
import asyncio
asyncio.run(main())