"""
Sincc.on: Telegram Bot Interfeysi (Matn, Rasm-OCR va Geometrik Chizmalar bilan).
"""
import sys, pathlib, os, threading, time, re, html, datetime
if sys.platform == "win32":
try:
sys.stdout.reconfigure(encoding="utf-8")
except Exception:
pass
PROJECT_ROOT = pathlib.Path(__file__).resolve().parent
sys.path.insert(0, str(PROJECT_ROOT))
import telebot
from telebot.types import InlineKeyboardMarkup, InlineKeyboardButton
from app.pipeline import solve_problem, load_env_file
from app.vision import extract_problem_from_image
from app.geometry_drawer import try_draw_geometry
from app.db import (
record_user_activity,
log_query,
get_statistics,
set_user_admin,
is_user_admin,
get_all_user_ids,
log_feedback,
get_recent_feedbacks,
add_chat_message,
get_recent_chat_history,
clear_chat_history,
ban_user,
unban_user,
is_user_banned,
get_banned_users,
)
from app.security import analyze_message_threat
from app.voice import transcribe_voice
from app.pdf_generator import generate_math_pdf
from chat import universal_local_solve
load_env_file()
raw_token = os.getenv("TELEGRAM_BOT_TOKEN") or os.getenv("BOT_TOKEN") or os.getenv("TOKEN") or ""
TOKEN = str(raw_token).strip().strip("\"'").strip()
ADMIN_IDS = [7759713314]
_env_admin = str(os.getenv("ADMIN_ID") or "").strip().strip("\"'").strip()
if _env_admin:
try:
ADMIN_IDS.append(int(_env_admin))
except Exception:
pass
# Xato xabari kutayotgan foydalanuvchilar (user_id -> tegishli kontekst)
awaiting_bug_report: dict[int, str] = {}
_bug_report_lock = threading.Lock()
# Foydalanuvchining oxirgi yechilgan masalasi (PDF konspekt generatsiyasi uchun)
_last_user_solutions: dict[int, dict] = {}
_last_user_solutions_lock = threading.Lock()
# Matematik belgilar klaviaturasi sessiyalari (user_id -> joriy ifoda)
_math_pad_sessions: dict[int, str] = {}
_math_pad_lock = threading.Lock()
_SUBSCRIPT_MAP = str.maketrans("0123456789nijk", "₀₁₂₃₄₅₆₇₈₉ₙᵢⱼₖ")
_SUPERSCRIPT_MAP = str.maketrans("0123456789n", "⁰¹²³⁴⁵⁶⁷⁸⁹ⁿ")
def check_is_admin(user_id: int) -> bool:
if user_id in ADMIN_IDS:
return True
return is_user_admin(user_id)
if not TOKEN or TOKEN == "your_telegram_bot_token_here":
print("=" * 70)
print("DIQQAT: TELEGRAM_BOT_TOKEN topilmadi!")
print(".env faylida TELEGRAM_BOT_TOKEN=... parametrini sozlang.")
print("=" * 70)
bot = telebot.TeleBot(TOKEN if TOKEN else "dummy_token")
def clean_math_display(text: str) -> str:
"""Raw LaTeX va texnik belgilarni Telegram uchun chiroyli, insonbop ko'rinishga keltiradi."""
if not text:
return ""
s = str(text)
s = re.sub(r"\$\$(.*?)\$\$", r"\1", s, flags=re.DOTALL)
s = re.sub(r"\\\[(.*?)\\\]", r"\1", s, flags=re.DOTALL)
s = re.sub(r"\\\((.*?)\\\)", r"\1", s, flags=re.DOTALL)
s = re.sub(r"(?\"'])(\*\*)(?=\S)([^\n*]*?\S)\2", r"\1*\3*", s)
s = re.sub(r"\n{3,}", "\n\n", s)
return s.strip()
def _strip_markdown(text: str) -> str:
return text.replace("*", "").replace("`", "")
def _strip_html_tags(text: str) -> str:
return html.unescape(re.sub(r"?(?:b|i|code|pre|u|s)>", "", text))
def _render_html_prose(text: str) -> str:
"""Matn ichidagi math * / _ ni buzmasdan, faqat xavfsiz HTML formatiga o'giradi."""
escaped = html.escape(text)
# **qalin** yoki *qalin* faqat so'z/tinish belgisi chegarasida bo'lsa (a*b emas!)
escaped = re.sub(r"(^|[\s(>\"'])\*([^\s*][^\n*]*?[^\s*]|[^\s*])\*(?=$|[\s).,;:!?\"'»])", r"\1\2", escaped)
escaped = re.sub(r"`([^`\n]+)`", r"\1", escaped)
return escaped
def safe_send_reply(target_msg, text: str, reply_markup=None, edit_msg=None, parse_mode: str = "Markdown"):
"""Telegram xabarini Markdown/HTML bilan yuboradi/tahrirlaydi; parse xatosida oddiy matnga o'tadi."""
if len(text) > 4000:
text = text[:3990] + "\n..."
fallback_plain = _strip_html_tags(text) if parse_mode == "HTML" else _strip_markdown(text)
if edit_msg:
try:
bot.edit_message_text(text, chat_id=target_msg.chat.id, message_id=edit_msg.message_id,
parse_mode=parse_mode, reply_markup=reply_markup)
return
except Exception:
try:
bot.edit_message_text(fallback_plain, chat_id=target_msg.chat.id,
message_id=edit_msg.message_id, reply_markup=reply_markup)
return
except Exception:
pass
try:
bot.reply_to(target_msg, text, parse_mode=parse_mode, reply_markup=reply_markup)
except Exception:
bot.reply_to(target_msg, fallback_plain, reply_markup=reply_markup)
def _typing_loop(chat_id: int, stop_event: threading.Event):
while not stop_event.is_set():
try:
bot.send_chat_action(chat_id, "typing")
except Exception:
pass
stop_event.wait(4.0)
def send_bug_report_to_admins(from_user, comment: str, reply_context: str = ""):
"""Foydalanuvchi xato xabari/taklifini bazaga yozadi va barcha adminlarga yuboradi."""
log_feedback(
user_id=from_user.id,
username=from_user.username or "",
first_name=from_user.first_name or "",
message=comment or "(Faqat xabarga reply qilindi)",
reply_context=reply_context
)
sender_name = f"@{from_user.username}" if from_user.username else (from_user.first_name or f"ID:{from_user.id}")
admin_alert_html = (
"🚨 YANGI XATOLIK / FIKR XABARI! 📩\n\n"
f"👤 Yuboruvchi: {html.escape(sender_name)} ({from_user.id})\n"
f"💬 Foydalanuvchi izohi:\n{html.escape(comment or 'Izoh yozilmagan')}\n"
)
if reply_context:
admin_alert_html += f"\n📌 Tegishli xabar matni:\n{html.escape(reply_context[:350])}"
admin_alert_plain = (
"🚨 YANGI XATOLIK / FIKR XABARI! 📩\n\n"
f"👤 Yuboruvchi: {sender_name} (ID: {from_user.id})\n"
f"💬 Foydalanuvchi izohi:\n{comment or 'Izoh yozilmagan'}\n"
)
if reply_context:
admin_alert_plain += f"\n📌 Tegishli xabar matni:\n{reply_context[:350]}"
for admin_id in set(ADMIN_IDS):
try:
bot.send_message(admin_id, admin_alert_html, parse_mode="HTML")
print(f"Admin {admin_id} ga bildirishnoma yuborildi.")
except Exception as e_html:
print(f"HTML yuborishda xatolik ({admin_id}): {e_html}. Oddiy matn sinab ko'rilmoqda...")
try:
bot.send_message(admin_id, admin_alert_plain)
except Exception as e_plain:
print(f"Admin {admin_id} ga yuborib bo'lmadi: {e_plain}")
def alert_admins_threat(from_user, threat_type: str, message_text: str):
"""Xavfli foydalanuvchi aniqlanganda barcha adminlarga tezkor ogohlantirish va Ban tugmasini yuboradi."""
now_str = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
sender_name = f"@{from_user.username}" if from_user.username else (from_user.first_name or f"ID:{from_user.id}")
kb = InlineKeyboardMarkup()
kb.add(InlineKeyboardButton("🚫 Bloklash (Ban)", callback_data=f"ban_user_{from_user.id}"))
alert_html = (
"🚨 XAVFLI HARAKAT / TAHDID ANIQLANDI! ⚠️\n\n"
f"👤 Foydalanuvchi: {html.escape(sender_name)} ({from_user.id})\n"
f"📛 Ismi: {html.escape(from_user.first_name or '')}\n"
f"⚠️ Tahdid turi: {html.escape(threat_type)}\n"
f"📝 Xabar matni:\n{html.escape(message_text[:400])}\n"
f"⏱ Vaqt: {now_str}\n\n"
"Quyidagi tugma orqali ushbu foydalanuvchini botdan zudlik bilan bloklashingiz mumkin:"
)
alert_plain = (
"🚨 XAVFLI HARAKAT / TAHDID ANIQLANDI! ⚠️\n\n"
f"👤 Foydalanuvchi: {sender_name} (ID: {from_user.id})\n"
f"📛 Ismi: {from_user.first_name or ''}\n"
f"⚠️ Tahdid turi: {threat_type}\n"
f"📝 Xabar matni:\n{message_text[:400]}\n"
f"⏱ Vaqt: {now_str}\n\n"
f"Bloklash uchun buyruq: /ban {from_user.id}"
)
for admin_id in set(ADMIN_IDS):
try:
bot.send_message(admin_id, alert_html, parse_mode="HTML", reply_markup=kb)
print(f"Admin {admin_id} ga xavfsizlik signali yuborildi.")
except Exception:
try:
bot.send_message(admin_id, alert_plain, reply_markup=kb)
except Exception as e:
print(f"Admin {admin_id} ga xavfsizlik signalini yuborib bo'lmadi: {e}")
def setup_bot_commands():
"""Telegram ilovasida '/' tugmasi bosilganda chiquvchi buyruqlar menyusini minimalistik va qulay qilib sozlaydi."""
try:
user_commands = [
telebot.types.BotCommand("start", "Botni ishga tushirish"),
telebot.types.BotCommand("yangi", "Yangi suhbat (xotirani tozalash)"),
telebot.types.BotCommand("klaviatura", "Matematik klaviatura & belgilar"),
telebot.types.BotCommand("help", "Qo'llanma va yordam")
]
bot.set_my_commands(user_commands)
admin_commands = user_commands + [
telebot.types.BotCommand("admin", "Admin boshqaruv paneli va statistika"),
telebot.types.BotCommand("broadcast", "Foydalanuvchilarga ommaviy xabar"),
telebot.types.BotCommand("banlar", "Bloklanganlar ro'yxati"),
telebot.types.BotCommand("xatolar", "Kelgan taklif/fikr xabarlari")
]
for aid in set(ADMIN_IDS):
try:
bot.set_my_commands(admin_commands, scope=telebot.types.BotCommandScopeChat(aid))
except Exception:
pass
print("Telegram bot buyruqlari (/ menyusi) muvaffaqiyatli sozlandi.")
except Exception as e:
print(f"Buyruqlar menyusini sozlashda ogohlantirish: {e}")
@bot.message_handler(commands=['yangi', 'new', 'clear', 'reset'])
def new_chat_command(message):
record_user_activity(message.from_user.id, message.from_user.username, message.from_user.first_name)
clear_chat_history(message.from_user.id)
with _bug_report_lock:
awaiting_bug_report.pop(message.from_user.id, None)
with _math_pad_lock:
_math_pad_sessions.pop(message.from_user.id, None)
bot.reply_to(message, "🔄 Suhbat xotirasi tozalandi. Yangi mavzu yoki misolingizni bemalol yozib yuboravering!", parse_mode="HTML")
@bot.message_handler(commands=['konspekt', 'pdf'])
def handle_pdf_command(message):
user_id = message.from_user.id
record_user_activity(user_id, message.from_user.username, message.from_user.first_name)
with _last_user_solutions_lock:
last_info = _last_user_solutions.get(user_id)
if not last_info:
bot.reply_to(
message,
"ℹ️ Hozircha siz yechgan oxirgi masala topilmadi.\n"
"Avval biror masala yuboring (masalan: x^2 - 5x + 6 = 0), so'ngra /konspekt buyrug'ini bering!",
parse_mode="HTML"
)
return
wait_msg = bot.reply_to(message, "📄 A4 PDF konspekt tayyorlanmoqda...", parse_mode="HTML")
def _worker():
try:
q = last_info["question"]
sol = last_info["solution"]
diag = last_info.get("diagram_path")
if not diag or not os.path.exists(diag):
diag = try_draw_geometry(q)
pdf_path = generate_math_pdf(q, sol, diag)
if pdf_path and os.path.exists(pdf_path):
with open(pdf_path, "rb") as pdf_file:
bot.send_document(
message.chat.id,
pdf_file,
caption="📄 Sincc.on: Ushbu masalaning A4 PDF Konspekti\n"
"Chop etish va darsda/imtihonda foydalanish uchun to'liq yechim va chizma.",
parse_mode="HTML"
)
try:
os.unlink(pdf_path)
except Exception:
pass
try:
bot.delete_message(message.chat.id, wait_msg.message_id)
except Exception:
pass
else:
bot.edit_message_text("❌ PDF faylni yaratib bo'lmadi.", chat_id=message.chat.id, message_id=wait_msg.message_id)
except Exception as e_pdf:
print(f"[PDF Command xatosi]: {e_pdf}")
try:
bot.edit_message_text(f"❌ PDF yaratishda xatolik: {e_pdf}", chat_id=message.chat.id, message_id=wait_msg.message_id)
except Exception:
pass
threading.Thread(target=_worker, daemon=True).start()
@bot.message_handler(commands=['id', 'myid'])
def show_my_id(message):
record_user_activity(message.from_user.id, message.from_user.username, message.from_user.first_name)
bot.reply_to(message, f"🆔 Sizning Telegram ID raqamingiz: {message.from_user.id}", parse_mode="HTML")
@bot.message_handler(commands=['admin', 'stat', 'stats'])
def admin_panel(message):
record_user_activity(message.from_user.id, message.from_user.username, message.from_user.first_name)
if not check_is_admin(message.from_user.id):
bot.reply_to(message, "⛔ Bu bo'lim faqat bot administratori uchun mo'ljallangan.")
return
try:
stats = get_statistics()
recent_text = ""
for i, u in enumerate(stats["recent_users"], 1):
uname = f"@{u[1]}" if u[1] else (u[2] or f"ID:{u[0]}")
recent_text += f"{i}. {uname} — {u[3]} ta savol ({u[4][11:16]})\n"
if not recent_text:
recent_text = "Hozircha boshqa faol foydalanuvchilar yo'q.\n"
kb = InlineKeyboardMarkup(row_width=2)
kb.add(
InlineKeyboardButton("🔄 Yangilash", callback_data="admin_refresh"),
InlineKeyboardButton("🚫 Bloklanganlar", callback_data="admin_banlar"),
)
kb.add(
InlineKeyboardButton("📬 Fikrlar/Xatolar", callback_data="admin_xatolar"),
InlineKeyboardButton("📢 Xabar Yuborish", callback_data="admin_broadcast_help"),
)
report = (
"📊 Sincc.on Admin Statistikasi:\n\n"
f"👥 Jami foydalanuvchilar: {stats['total_users']} ta\n"
f"📅 Bugungi faol: {stats['active_today']} ta\n"
f"⚡ Jami yechilgan masalalar: {stats['total_queries']} ta\n"
f" • 📝 Matnli: {stats['text_queries']} ta\n"
f" • 📸 Rasmli: {stats['photo_queries']} ta\n"
f" • 🎙 Ovozli: {stats.get('voice_queries', 0)} ta\n"
f"📩 Xatolik/fikr xabarlari: {stats.get('total_feedbacks', 0)} ta (/xatolar)\n"
f"🚫 Bloklanganlar: {stats.get('total_banned', 0)} ta (/banlar)\n\n"
f"📋 So'nggi foydalanuvchilar:\n{html.escape(recent_text)}\n"
"📢 Admin buyruqlari:\n"
"• /broadcast <matn> — Barcha foydalanuvchilarga xabar\n"
"• /ban <id> [sabab] — Foydalanuvchini bloklash\n"
"• /unban <id> — Blokdan chiqarish\n"
"• /banlar — Bloklanganlar ro'yxati\n"
"• /xatolar — Fikr/takliflar ro'yxati"
)
bot.reply_to(message, report, parse_mode="HTML", reply_markup=kb)
except Exception as e:
bot.reply_to(message, f"❌ Statistikani yuklashda xatolik: {e}")
@bot.message_handler(commands=['ban'])
def handle_ban_command(message):
record_user_activity(message.from_user.id, message.from_user.username, message.from_user.first_name)
if not check_is_admin(message.from_user.id):
bot.reply_to(message, "⛔ Bu buyruq faqat admin uchun!")
return
parts = message.text.split(maxsplit=2)
if len(parts) < 2:
bot.reply_to(message, "Foydalanish: `/ban [sabab]`\nMasalan: `/ban 123456789 spam`", parse_mode="Markdown")
return
try:
target_uid = int(parts[1].strip())
except ValueError:
bot.reply_to(message, "❌ User ID butun son bo'lishi kerak!")
return
reason = parts[2].strip() if len(parts) > 2 else "Admin tomonidan buyruq orqali bloklandi"
ban_user(target_uid, reason=reason, banned_by=message.from_user.id)
bot.reply_to(message, f"✅ Foydalanuvchi `{target_uid}` muvaffaqiyatli bloklandi.\nSabab: {reason}", parse_mode="Markdown")
try:
bot.send_message(target_uid, f"⛔ Siz qoidabuzarlik sababli botdan chetlatildingiz.\nSabab: {reason}")
except Exception:
pass
@bot.message_handler(commands=['unban'])
def handle_unban_command(message):
record_user_activity(message.from_user.id, message.from_user.username, message.from_user.first_name)
if not check_is_admin(message.from_user.id):
bot.reply_to(message, "⛔ Bu buyruq faqat admin uchun!")
return
parts = message.text.split(maxsplit=1)
if len(parts) < 2:
bot.reply_to(message, "Foydalanish: `/unban `\nMasalan: `/unban 123456789`", parse_mode="Markdown")
return
try:
target_uid = int(parts[1].strip())
except ValueError:
bot.reply_to(message, "❌ User ID butun son bo'lishi kerak!")
return
if unban_user(target_uid):
bot.reply_to(message, f"✅ Foydalanuvchi `{target_uid}` blokdan chiqarildi.", parse_mode="Markdown")
try:
bot.send_message(target_uid, "✅ Botingizdan foydalanish huquqi qayta tiklandi. Xush kelibsiz!")
except Exception:
pass
else:
bot.reply_to(message, f"ℹ️ Foydalanuvchi `{target_uid}` bloklanganlar ro'yxatida topilmadi.", parse_mode="Markdown")
@bot.message_handler(commands=['banlar', 'banned'])
def handle_banned_list(message):
record_user_activity(message.from_user.id, message.from_user.username, message.from_user.first_name)
if not check_is_admin(message.from_user.id):
bot.reply_to(message, "⛔ Bu buyruq faqat admin uchun!")
return
banned = get_banned_users(limit=15)
if not banned:
bot.reply_to(message, "✅ Hozircha bloklangan foydalanuvchilar yo'q.")
return
text = "🚫 Bloklangan foydalanuvchilar:\n\n"
for idx, b in enumerate(banned, 1):
uname = f"@{b['username']}" if b['username'] else (b['first_name'] or f"ID:{b['user_id']}")
text += f"{idx}. {html.escape(uname)} ({b['user_id']})\n"
text += f" • Sabab: {html.escape(b['reason'])}\n"
text += f" • Vaqt: {b['banned_at'][:16]}\n"
text += "\nBlokdan chiqarish: /unban <user_id>"
bot.reply_to(message, text, parse_mode="HTML")
@bot.message_handler(commands=['xatolar', 'feedbacks'])
def show_feedbacks(message):
record_user_activity(message.from_user.id, message.from_user.username, message.from_user.first_name)
if not check_is_admin(message.from_user.id):
bot.reply_to(message, "⛔ Bu bo'lim faqat bot administratori uchun mo'ljallangan.")
return
items = get_recent_feedbacks(limit=5)
if not items:
bot.reply_to(message, "📭 Hozircha hech qanday xatolik yoki fikr xabari kelib tushmagan.")
return
text = "📬 So'nggi 5 ta xatolik / fikr xabarlari:\n\n"
for item in items:
fid, uid, uname, fname, fmsg, rcontext, ftime = item
u_str = f"@{html.escape(uname)}" if uname else html.escape(fname or f"ID:{uid}")
text += f"🔹 #{fid} | {u_str} | {ftime[5:16]}\n"
text += f"💬 Fikr: {html.escape(fmsg)}\n"
if rcontext:
text += f"📌 Kontekst: {html.escape(rcontext[:100])}...\n"
text += "------------------------\n"
try:
bot.reply_to(message, text, parse_mode="HTML")
except Exception:
plain_text = text.replace("", "").replace("", "").replace("", "").replace("", "").replace("", "").replace("", "")
bot.reply_to(message, plain_text)
@bot.message_handler(commands=['xato', 'fikr', 'taklif', 'feedback'])
def report_feedback(message):
record_user_activity(message.from_user.id, message.from_user.username, message.from_user.first_name)
parts = message.text.split(maxsplit=1)
comment = parts[1].strip() if len(parts) > 1 else ""
reply_context = ""
if message.reply_to_message and message.reply_to_message.text:
reply_context = message.reply_to_message.text[:400]
if not comment and not reply_context:
with _bug_report_lock:
awaiting_bug_report[message.from_user.id] = ""
instruction = (
"📝 *Qanday xatolik ko'rdingiz yoki taklifingiz bormi?*\n\n"
"Shu xabardan keyingi xabaringizda yozib yuboring — men uni to'g'ridan-to'g'ri loyiha muallifiga yetkazaman.\n"
"_(Bekor qilish uchun /yangi bosing)_"
)
bot.reply_to(message, instruction, parse_mode="Markdown")
return
send_bug_report_to_admins(message.from_user, comment, reply_context)
bot.reply_to(
message,
"✅ *Katta rahmat!* Xabaringiz loyiha muallifiga yetkazildi. 🤝",
parse_mode="Markdown"
)
@bot.message_handler(commands=['broadcast'])
def broadcast_message(message):
record_user_activity(message.from_user.id, message.from_user.username, message.from_user.first_name)
if not check_is_admin(message.from_user.id):
bot.reply_to(message, "⛔ Bu buyruq faqat bot administratori uchun!")
return
text = message.text.replace("/broadcast", "", 1).strip()
if not text:
bot.reply_to(
message,
"📢 Xabar yuborish tartibi:\n"
"/broadcast Hurmatli foydalanuvchilar, botda yangi funksiyalar qo'shildi!",
parse_mode="HTML"
)
return
user_ids = get_all_user_ids()
if not user_ids:
bot.reply_to(message, "Bazada foydalanuvchilar topilmadi.")
return
wait_msg = bot.reply_to(message, f"📢 Xabar {len(user_ids)} ta foydalanuvchiga yuborilmoqda...")
success_count = 0
for uid in user_ids:
try:
bot.send_message(uid, f"📢 Sincc.on E'loni:\n\n{html.escape(text)}", parse_mode="HTML")
success_count += 1
except Exception:
try:
bot.send_message(uid, f"📢 Sincc.on E'loni:\n\n{text}")
success_count += 1
except Exception:
pass
try:
bot.edit_message_text(f"✅ Xabar {success_count}/{len(user_ids)} ta foydalanuvchiga yetkazildi.",
chat_id=message.chat.id, message_id=wait_msg.message_id, parse_mode="HTML")
except Exception:
bot.reply_to(message, f"✅ Xabar {success_count}/{len(user_ids)} ta foydalanuvchiga yetkazildi.")
@bot.message_handler(commands=['start'])
def send_welcome(message):
record_user_activity(message.from_user.id, message.from_user.username, message.from_user.first_name)
with _bug_report_lock:
awaiting_bug_report.pop(message.from_user.id, None)
kb = InlineKeyboardMarkup(row_width=2)
kb.add(
InlineKeyboardButton("🔢 Matematik Klaviatura", callback_data="open_math_pad"),
InlineKeyboardButton("📖 Bot Qo'llanmasi", callback_data="open_help_info"),
)
kb.add(
InlineKeyboardButton("📥 A4 PDF Konspekt", callback_data="get_pdf_solution"),
InlineKeyboardButton("🔄 Yangi Suhbat", callback_data="start_new_chat"),
)
fname = message.from_user.first_name or "do'stim"
text = (
f"Assalomu alaykum, {html.escape(fname)}! Men Sincc.on — matematika bo'yicha milliy AI ustozingizman. 👋📐\n\n"
"Menga xohlagan matematik masalangizni yuborishingiz mumkin:\n"
"• 📝 Matn ko'rinishida: x^2 - 5x + 6 = 0\n"
"• 📸 Rasm ko'rinishida: Kitob yoki daftardagi misolni rasmga olib yuboring\n"
"• 🎙 Ovozli xabar: Masala shartini audio tarzida ayting\n"
"• 🔢 Klaviatura: /klaviatura orqali qulay matematik belgilarni tering\n\n"
"Tizim hisoblashlarni 100% xatosiz (SymPy ramziy yadrosi) tekshiradi va qadam-baqadam yechim, qoidalar va geometrik chizmalar bilan tushuntiradi!\n\n"
"Boshlash uchun quyidagi tugmalardan birini bosing yoki to'g'ridan-to'g'ri misolingizni yozib yuboring: 👇"
)
safe_send_reply(message, text, reply_markup=kb, parse_mode="HTML")
@bot.message_handler(commands=['help', 'yordam', 'info', 'about'])
def send_help(message):
record_user_activity(message.from_user.id, message.from_user.username, message.from_user.first_name)
kb = InlineKeyboardMarkup(row_width=2)
kb.add(
InlineKeyboardButton("🔢 Matematik Klaviatura", callback_data="open_math_pad"),
InlineKeyboardButton("🔄 Yangi Suhbat", callback_data="start_new_chat"),
)
kb.add(
InlineKeyboardButton("📥 PDF Konspekt", callback_data="get_pdf_solution"),
InlineKeyboardButton("🚨 Fikr / Xatolik", callback_data="report_bug"),
)
help_text = (
"📚 Sincc.on Botidan Foydalanish Qo'llanmasi:\n\n"
"1. Masala yuborish usullari:\n"
"• Matn: Algebra, geometriya, matnli masalalar (masalan: «Hovuzni 1-quvur 3 soatda, 2-quvur 6 soatda to'ldiradi...»)\n"
"• Rasm (Vision OCR): Yaxshi yorug'likda daftardagi qo'lyozma yoki darslik rasmini yuboring\n"
"• Ovoz (Whisper): Telegram audio yoki mikrofon orqali gapiring\n\n"
"2. Mavjud Buyruqlar:\n"
"• /start — Botni ishga tushirish va asosiy menyu\n"
"• /klaviatura (yoki /belgilar) — Matematik belgilar inline paneli\n"
"• /konspekt (yoki /pdf) — Oxirgi yechimning chiroyli A4 PDF konspekti\n"
"• /yangi — Suhbat xotirasini tozalash (yangi mavzu boshlash)\n"
"• /help — Ushbu qo'llanma va yordam\n"
"• /xato (yoki /taklif) — Muallifga bevosita fikr/taklif bildirish\n"
"• /id — Telegram ID raqamingizni bilish\n\n"
"3. Savol-javob va chuqur tahlil:\n"
"Har bir yechimdan so'ng tushunmagan joyingizni bemalol qayta so'rashingiz mumkin:\n"
"• «2-qadamni tushunmadim, soddaroq tushuntir»\n"
"• «Boshqa usul bilan yechib ko'rsat»\n"
"• «Shunga o'xshash yangi mashq ber, o'zim yechaman»"
)
safe_send_reply(message, help_text, reply_markup=kb, parse_mode="HTML")
def build_math_pad_keyboard() -> InlineKeyboardMarkup:
"""Matematik formulalar va belgilarni terish uchun qulay inline klaviatura paneli."""
kb = InlineKeyboardMarkup(row_width=5)
kb.row(
InlineKeyboardButton("x", callback_data="pad_add_x"),
InlineKeyboardButton("y", callback_data="pad_add_y"),
InlineKeyboardButton("+", callback_data="pad_add_+"),
InlineKeyboardButton("-", callback_data="pad_add_-"),
InlineKeyboardButton("=", callback_data="pad_add_="),
)
kb.row(
InlineKeyboardButton("x²", callback_data="pad_add_²"),
InlineKeyboardButton("x³", callback_data="pad_add_³"),
InlineKeyboardButton("√", callback_data="pad_add_√("),
InlineKeyboardButton("·", callback_data="pad_add_*"),
InlineKeyboardButton("/", callback_data="pad_add_/"),
)
kb.row(
InlineKeyboardButton("(", callback_data="pad_add_("),
InlineKeyboardButton(")", callback_data="pad_add_)"),
InlineKeyboardButton("^", callback_data="pad_add_^"),
InlineKeyboardButton("π", callback_data="pad_add_π"),
InlineKeyboardButton("±", callback_data="pad_add_±"),
)
kb.row(
InlineKeyboardButton("≤", callback_data="pad_add_≤"),
InlineKeyboardButton("≥", callback_data="pad_add_≥"),
InlineKeyboardButton("≠", callback_data="pad_add_≠"),
InlineKeyboardButton("sin", callback_data="pad_add_sin("),
InlineKeyboardButton("cos", callback_data="pad_add_cos("),
)
kb.row(
InlineKeyboardButton("⌫ O'chirish", callback_data="pad_backspace"),
InlineKeyboardButton("🗑 Tozalash", callback_data="pad_clear"),
)
kb.row(
InlineKeyboardButton("🚀 Masalani Yechish", callback_data="pad_solve"),
InlineKeyboardButton("❌ Yopish", callback_data="pad_close"),
)
return kb
def get_math_pad_text(formula: str) -> str:
display_f = formula if formula else "_(hali belgilar terilmadi)_"
return (
"🔢 Matematik Belgilar & Formula Paneli:\n\n"
f"📝 Joriy ifoda: {html.escape(display_f)}\n\n"
"Quyidagi tugmalar orqali formulangizni shakllantiring va «🚀 Masalani Yechish» tugmasini bosing:"
)
def build_solution_keyboard() -> InlineKeyboardMarkup:
kb = InlineKeyboardMarkup(row_width=2)
kb.add(
InlineKeyboardButton("❓ Tushunmadim", callback_data="explain_simpler"),
InlineKeyboardButton("💡 Boshqa usul", callback_data="alt_method"),
)
kb.add(
InlineKeyboardButton("🔄 O'xshash misol", callback_data="similar_problem"),
InlineKeyboardButton("📥 PDF Konspekt", callback_data="get_pdf_solution"),
)
kb.add(
InlineKeyboardButton("🔢 Matematik Belgilar", callback_data="open_math_pad"),
InlineKeyboardButton("🚨 Xato / Taklif", callback_data="report_bug"),
)
return kb
def format_bot_response(javob: dict) -> tuple[str, InlineKeyboardMarkup | None, str]:
"""AI javobini turiga qarab (suhbat, nazariya yoki yechim) xavfsiz HTML Telegram matniga aylantiradi."""
ans_type = javob.get("type", "solve")
if ans_type == "chat":
reply_raw = clean_math_display(javob.get("reply") or "\n".join(javob.get("steps", [])) or javob.get("final_answer", ""))
if not reply_raw:
reply_raw = "Salom! Matematika bo'yicha qanday savol yoki misolingiz bor?"
return _render_html_prose(reply_raw), None, _strip_markdown(reply_raw)
if ans_type in ("theory", "incomplete"):
raw_reply = javob.get("reply")
if raw_reply:
text_raw = clean_math_display(raw_reply)
else:
chunks = [clean_math_display(s) for s in javob.get("steps", []) if s and str(s).strip()]
fa = clean_math_display(str(javob.get("final_answer", "")).strip())
tip = clean_math_display(javob.get("explanation_tip", ""))
if fa and fa.lower() not in "\n".join(chunks).lower():
chunks.append(f"📌 {fa}")
if tip:
chunks.append(f"💡 {tip}")
text_raw = "\n\n".join(chunks) or "Savolingizni biroz aniqroq yozib bera olasizmi?"
return _render_html_prose(text_raw), None, _strip_markdown(text_raw)
# ans_type == "solve"
if not javob.get("steps") and not str(javob.get("final_answer", "")).strip():
err_text = clean_math_display(javob.get("note") or "") or (
"Uzr, hozir serverda biroz uzilish bo'lib qoldi shekilli, javob ololmadim. "
"Bir necha soniyadan keyin qayta yuborib ko'rasizmi? 🙏"
)
return _render_html_prose(err_text), None, ""
intro_raw = clean_math_display(javob.get("intro", ""))
formatted_steps_html = []
plain_steps = []
for idx, s in enumerate(javob.get("steps", []), 1):
s_clean = clean_math_display(str(s).strip())
if not s_clean:
continue
m = re.match(r"^(?:🔹\s*)?([0-9]+-(?:qadam|bosqich)|[0-9]+\.)[:\s]*(.*)", s_clean, re.IGNORECASE | re.DOTALL)
if m:
hdr = m.group(1).rstrip(":.")
if hdr.isdigit():
hdr = f"{hdr}-qadam"
body = m.group(2).strip()
if body:
formatted_steps_html.append(f"🔹 {html.escape(hdr)}: {_render_html_prose(body)}")
plain_steps.append(f"🔹 {hdr}: {_strip_markdown(body)}")
else:
formatted_steps_html.append(f"🔹 {html.escape(hdr)}")
plain_steps.append(f"🔹 {hdr}")
else:
body = s_clean.lstrip("•- ")
formatted_steps_html.append(f"🔹 {idx}-qadam: {_render_html_prose(body)}")
plain_steps.append(f"🔹 {idx}-qadam: {_strip_markdown(body)}")
formulas = [clean_math_display(str(f).strip()) for f in javob.get("formulas_used", []) if f and str(f).strip()]
formulas_html = ""
formulas_plain = ""
if formulas:
formulas_html = "📐 Ishlatilgan qoidalar:\n" + "\n".join(f"• {html.escape(_strip_markdown(f))}" for f in formulas)
formulas_plain = "📐 Ishlatilgan qoidalar:\n" + "\n".join(f"• {_strip_markdown(f)}" for f in formulas)
raw_ans = str(javob.get("final_answer", "")).strip()
final_ans = clean_math_display(raw_ans)
final_ans_plain = _strip_markdown(final_ans)
ans_html = f"✅ Javob: {html.escape(final_ans_plain)}" if final_ans_plain else ""
ans_plain = f"✅ Javob: {final_ans_plain}" if final_ans_plain else ""
exp_tip = clean_math_display(javob.get("explanation_tip", ""))
exp_tip_plain = _strip_markdown(exp_tip)
tip_html = f"💡 {html.escape(exp_tip_plain)}" if exp_tip_plain else ""
tip_plain = f"💡 {exp_tip_plain}" if exp_tip_plain else ""
html_parts = []
plain_parts = []
if intro_raw:
html_parts.append(_render_html_prose(intro_raw))
plain_parts.append(_strip_markdown(intro_raw))
if formatted_steps_html:
html_parts.append("\n\n".join(formatted_steps_html))
plain_parts.append("\n\n".join(plain_steps))
if formulas_html:
html_parts.append(formulas_html)
plain_parts.append(formulas_plain)
if ans_html:
html_parts.append(ans_html)
plain_parts.append(ans_plain)
if tip_html:
html_parts.append(tip_html)
plain_parts.append(tip_plain)
if javob.get("verified"):
html_parts.append("✓ SymPy da tekshirildi")
plain_parts.append("✓ SymPy da tekshirildi")
return "\n\n".join(html_parts), build_solution_keyboard(), "\n\n".join(plain_parts)
def process_and_reply(message, existing_wait_msg=None, is_photo=False, is_voice=False, override_prompt=None,
bypass_cache=False, history_user_msg=None, actor_user=None):
user_obj = actor_user or message.from_user
user_id = user_obj.id
try:
record_user_activity(user_id, user_obj.username, user_obj.first_name)
except Exception:
pass
savol = (override_prompt if override_prompt is not None else (message.text or "")).strip()
if not savol:
return
wait_msg = existing_wait_msg
if not wait_msg and (len(savol) > 15 or any(k in savol.lower() for k in ["=", ">", "<", "uchburchak", "tenglama", "ildiz", "hisoblang", "yeching"])):
try:
wait_msg = bot.reply_to(message, "⏳ Masala tahlil qilinmoqda va hisob-kitob tekshirilmoqda...", parse_mode="HTML")
except Exception:
pass
stop_typing = threading.Event()
typing_thread = threading.Thread(target=_typing_loop, args=(message.chat.id, stop_typing), daemon=True)
typing_thread.start()
try:
# 1. Suhbat tarixini olamiz va aqlli Router/Dual-Agent pipeline ga yuboramiz
chat_history = get_recent_chat_history(user_id, limit=8)
javob = solve_problem(savol, chat_history=chat_history, bypass_cache=bypass_cache)
# 2. Faqat haqiqiy hisob-kitob masalasi API dan to'liq tasdiq olmasa, lokal dvigatelni sinab ko'ramiz
if javob.get("type", "solve") == "solve" and not javob.get("verified"):
lokal = universal_local_solve(savol)
if lokal and lokal.get("verified"):
javob = lokal
# 3. Statistikaga yozamiz
try:
q_type = "voice" if is_voice else ("photo" if is_photo else "text")
log_query(
user_id,
query_type=q_type,
question=savol,
verified=bool(javob.get("verified"))
)
except Exception:
pass
# 4. Tabiiy va tushunarli javob tuzamiz (HTML rejimida * va _ xavfsiz!)
reply, reply_markup, history_assistant_text = format_bot_response(javob)
stop_typing.set()
safe_send_reply(message, reply, reply_markup=reply_markup, edit_msg=wait_msg, parse_mode="HTML")
# 5. Suhbat xotirasiga saqlaymiz (follow-up savollar uchun)
user_hist = (history_user_msg if history_user_msg is not None else savol).strip()
if user_hist and history_assistant_text:
add_chat_message(user_id, "user", user_hist[:800])
add_chat_message(user_id, "assistant", history_assistant_text[:1500])
# 6. Faqat haqiqiy geometriya masalasida chizma chizib jo'natamiz
saved_diag = None
if javob.get("type", "solve") == "solve" and (javob.get("steps") or javob.get("final_answer")):
diag_path = try_draw_geometry(savol)
if diag_path and os.path.exists(diag_path):
with open(diag_path, "rb") as photo_f:
bot.send_photo(message.chat.id, photo_f, caption="📐 *Geometrik chizma:*", parse_mode="Markdown")
saved_diag = diag_path
# 7. PDF konspekt generatsiyasi uchun so'nggi yechimni xotirada saqlaymiz
if javob.get("type", "solve") == "solve":
with _last_user_solutions_lock:
_last_user_solutions[user_id] = {
"question": savol,
"solution": javob,
"diagram_path": saved_diag
}
except Exception as e:
stop_typing.set()
err_msg = f"❌ Javob tayyorlashda kutilmagan xatolik yuz berdi: {e}"
if wait_msg:
try:
bot.edit_message_text(err_msg, chat_id=message.chat.id, message_id=wait_msg.message_id)
except Exception:
pass
else:
bot.reply_to(message, err_msg)
finally:
stop_typing.set()
if typing_thread and typing_thread.is_alive():
typing_thread.join(timeout=0.5)
@bot.callback_query_handler(func=lambda call: True)
def handle_inline_callbacks(call):
user_id = call.from_user.id
data = call.data or ""
msg = call.message
orig_q = ""
if msg and msg.reply_to_message and msg.reply_to_message.text:
orig_q = msg.reply_to_message.text.strip()
if data.startswith("ban_user_"):
if not check_is_admin(user_id):
bot.answer_callback_query(call.id, "⛔ Faqat bot administratori bloklay oladi!", show_alert=True)
return
target_str = data.replace("ban_user_", "")
try:
target_uid = int(target_str)
ban_user(target_uid, reason="Admin tomonidan xavfsizlik ogohlantirishidagi tugma orqali bloklandi", banned_by=user_id)
bot.answer_callback_query(call.id, f"✅ Foydalanuvchi ({target_uid}) bloklandi!", show_alert=True)
if msg:
bot.edit_message_reply_markup(
chat_id=msg.chat.id,
message_id=msg.message_id,
reply_markup=InlineKeyboardMarkup().add(
InlineKeyboardButton("✅ Bloklangan (Banned)", callback_data="none")
)
)
try:
bot.send_message(target_uid, "⛔ Siz xavfsizlik qoidalarini buzganingiz sababli botdan chetlatildingiz.")
except Exception:
pass
except Exception as e:
bot.answer_callback_query(call.id, f"Xatolik: {e}")
return
if data == "report_bug":
bot.answer_callback_query(call.id, "Izoh yozishingizni kutyapman...")
msg_preview = (msg.text or "")[:300] if msg else ""
context = f"{orig_q[:200]}\n---\n{msg_preview}".strip() if orig_q else msg_preview
with _bug_report_lock:
awaiting_bug_report[user_id] = context
bot.send_message(
msg.chat.id,
"📝 *Nima xato ko'rdingiz yoki qanday taklifingiz bor?*\n"
"Keyingi xabaringizda yozib yuboring — to'g'ridan-to'g'ri loyiha muallifiga yetkazaman.\n"
"_(Bekor qilish uchun /yangi bosing)_",
parse_mode="Markdown"
)
return
if data == "explain_simpler":
bot.answer_callback_query(call.id, "Soddaroq tushuntirish tayyorlayapman...")
prompt = (
f"Oldingi '{orig_q[:300]}' masalasining yechimini tushunmadim. "
"Iltimos, qiyin terminlar va formulalarga ko'mib yubormasdan, eng oddiy tilda bosqichma-bosqich tushuntirib ber."
if orig_q else
"Oxirgi tushuntirgan yechimingizni tushunmadim. Iltimos, juda sodda tilda qayta tushuntirib bering."
)
t = threading.Thread(
target=process_and_reply,
kwargs={
"message": msg,
"override_prompt": prompt,
"bypass_cache": True,
"history_user_msg": "Tushunmadim, soddaroq tushuntirib ber",
"actor_user": call.from_user,
}
)
t.start()
return
if data == "alt_method":
bot.answer_callback_query(call.id, "Boshqa yechim usulini izlayapman...")
prompt = (
f"'{orig_q[:300]}' masalasini avvalgidan BOSHQA usul bilan "
"(boshqa teorema, qisqa formula yoki mantiqiy yo'l orqali) yechib, javobini ham tekshirib ko'rsat."
if orig_q else
"Shu oxirgi masalani boshqa usul bilan yechib ko'rsating."
)
t = threading.Thread(
target=process_and_reply,
kwargs={
"message": msg,
"override_prompt": prompt,
"bypass_cache": True,
"history_user_msg": "Boshqa usul bilan yechib ber",
"actor_user": call.from_user,
}
)
t.start()
return
if data == "similar_problem":
bot.answer_callback_query(call.id, "O'xshash mashq tayyorlanmoqda...")
prompt = (
f"Oldingi '{orig_q[:300]}' masalasiga o'xshash, xuddi shu matematik mavzu va qoidaga doir "
"lekin boshqa sonlar bilan yangi amaliy misol tuzib ber va o'quvchiga uni mustaqil yechishni taklif qil. "
"O'quvchini ruhlantirib, agar qiynalsa yordam berishingni ayt."
if orig_q else
"Oxirgi masalaga o'xshash yangi misol tuzib ber, o'zim yechib ko'raman."
)
t = threading.Thread(
target=process_and_reply,
kwargs={
"message": msg,
"override_prompt": prompt,
"bypass_cache": True,
"history_user_msg": "Shunga o'xshash yangi misol ber",
"actor_user": call.from_user,
}
)
t.start()
return
if data == "get_pdf_solution":
with _last_user_solutions_lock:
last_info = _last_user_solutions.get(user_id)
if not last_info:
bot.answer_callback_query(call.id, "Avval biror masala yuboring, shunda konspekt tayyorlayman!", show_alert=True)
return
bot.answer_callback_query(call.id, "📄 A4 PDF konspekt shakllantirilmoqda...")
def _send_pdf_worker():
try:
q = last_info["question"]
sol = last_info["solution"]
diag = last_info.get("diagram_path")
if not diag or not os.path.exists(diag):
diag = try_draw_geometry(q)
pdf_path = generate_math_pdf(q, sol, diag)
if pdf_path and os.path.exists(pdf_path):
with open(pdf_path, "rb") as pdf_file:
bot.send_document(
msg.chat.id,
pdf_file,
caption="📄 Sincc.on: Ushbu masalaning A4 PDF Konspekti\n"
"Chop etish va darsda/imtihonda foydalanish uchun to'liq yechim va chizma.",
parse_mode="HTML"
)
try:
os.unlink(pdf_path)
except Exception:
pass
except Exception as e_pdf:
print(f"[PDF Telegram xatosi]: {e_pdf}")
bot.send_message(msg.chat.id, f"❌ PDF konspekt yaratishda xatolik: {e_pdf}")
threading.Thread(target=_send_pdf_worker, daemon=True).start()
return
if data == "open_math_pad":
bot.answer_callback_query(call.id, "Matematik klaviatura ochilmoqda...")
with _math_pad_lock:
_math_pad_sessions[user_id] = ""
kb = build_math_pad_keyboard()
txt = get_math_pad_text("")
bot.send_message(msg.chat.id, txt, parse_mode="HTML", reply_markup=kb)
return
if data.startswith("pad_add_"):
sym = data[8:]
with _math_pad_lock:
curr = _math_pad_sessions.get(user_id, "")
if len(curr) < 150:
curr += sym
_math_pad_sessions[user_id] = curr
bot.answer_callback_query(call.id)
kb = build_math_pad_keyboard()
txt = get_math_pad_text(curr)
try:
bot.edit_message_text(txt, chat_id=msg.chat.id, message_id=msg.message_id, parse_mode="HTML", reply_markup=kb)
except Exception:
pass
return
if data == "pad_backspace":
with _math_pad_lock:
curr = _math_pad_sessions.get(user_id, "")
if curr:
for prefix in ("sin(", "cos(", "tan(", "log(", "ln(", "√("):
if curr.endswith(prefix):
curr = curr[:-len(prefix)]
break
else:
curr = curr[:-1]
_math_pad_sessions[user_id] = curr
bot.answer_callback_query(call.id)
kb = build_math_pad_keyboard()
txt = get_math_pad_text(curr)
try:
bot.edit_message_text(txt, chat_id=msg.chat.id, message_id=msg.message_id, parse_mode="HTML", reply_markup=kb)
except Exception:
pass
return
if data == "pad_clear":
with _math_pad_lock:
_math_pad_sessions[user_id] = ""
bot.answer_callback_query(call.id, "Formula tozalandi")
kb = build_math_pad_keyboard()
txt = get_math_pad_text("")
try:
bot.edit_message_text(txt, chat_id=msg.chat.id, message_id=msg.message_id, parse_mode="HTML", reply_markup=kb)
except Exception:
pass
return
if data == "pad_close":
bot.answer_callback_query(call.id, "Klaviatura yopildi")
try:
bot.delete_message(msg.chat.id, msg.message_id)
except Exception:
try:
bot.edit_message_text("🔢 Matematik klaviatura yopildi.", chat_id=msg.chat.id, message_id=msg.message_id, parse_mode="HTML")
except Exception:
pass
return
if data == "pad_solve":
with _math_pad_lock:
formula = _math_pad_sessions.get(user_id, "").strip()
if not formula:
bot.answer_callback_query(call.id, "Formula bo'sh! Avval tugmalarni bosib ifoda tering.", show_alert=True)
return
bot.answer_callback_query(call.id, "Masala yechishga yuborilmoqda! 🚀")
try:
bot.edit_message_text(
f"🚀 Hisoblanmoqda: {html.escape(formula)}",
chat_id=msg.chat.id,
message_id=msg.message_id,
parse_mode="HTML"
)
except Exception:
pass
t = threading.Thread(
target=process_and_reply,
kwargs={
"message": msg,
"override_prompt": formula,
"actor_user": call.from_user,
}
)
t.start()
return
if data == "open_help_info":
bot.answer_callback_query(call.id)
send_help(msg)
return
if data == "start_new_chat":
clear_chat_history(user_id)
with _bug_report_lock:
awaiting_bug_report.pop(user_id, None)
with _math_pad_lock:
_math_pad_sessions.pop(user_id, None)
bot.answer_callback_query(call.id, "Suhbat xotirasi tozalandi!")
bot.send_message(msg.chat.id, "🔄 Suhbat xotirasi yangilandi. Yangi masalangizni yuborishingiz mumkin!", parse_mode="HTML")
return
if data == "admin_refresh":
if not check_is_admin(user_id):
bot.answer_callback_query(call.id, "Faqat admin uchun!", show_alert=True)
return
bot.answer_callback_query(call.id, "Statistika yangilandi!")
admin_panel(msg)
return
if data == "admin_banlar":
if not check_is_admin(user_id):
bot.answer_callback_query(call.id, "Faqat admin uchun!", show_alert=True)
return
bot.answer_callback_query(call.id)
handle_banned_list(msg)
return
if data == "admin_xatolar":
if not check_is_admin(user_id):
bot.answer_callback_query(call.id, "Faqat admin uchun!", show_alert=True)
return
bot.answer_callback_query(call.id)
show_feedbacks(msg)
return
if data == "admin_broadcast_help":
if not check_is_admin(user_id):
bot.answer_callback_query(call.id, "Faqat admin uchun!", show_alert=True)
return
bot.answer_callback_query(call.id)
bot.send_message(msg.chat.id, "📢 Ommaviy xabar yuborish uchun quyidagi formatda yozing:\n/broadcast Xabar matni...", parse_mode="HTML")
return
bot.answer_callback_query(call.id)
@bot.message_handler(commands=['klaviatura', 'belgilar', 'formula', 'pad'])
def math_pad_command(message):
user_id = message.from_user.id
record_user_activity(user_id, message.from_user.username, message.from_user.first_name)
with _math_pad_lock:
_math_pad_sessions[user_id] = ""
kb = build_math_pad_keyboard()
txt = get_math_pad_text("")
safe_send_reply(message, txt, reply_markup=kb, parse_mode="HTML")
@bot.message_handler(content_types=['photo'])
def handle_photo(message):
user_id = message.from_user.id
# 1. Bloklangan foydalanuvchini tekshirish
is_banned, ban_reason = is_user_banned(user_id)
if is_banned:
bot.reply_to(message, f"⛔ Siz qoidabuzarlik sababli botdan chetlatilgansiz.\nSabab: {ban_reason}")
return
# 2. Rasm izohida xavfli so'rovlar bormi?
caption = (message.caption or "").strip()
if caption and not check_is_admin(user_id):
is_threat, threat_title, threat_reason = analyze_message_threat(user_id, caption)
if is_threat:
alert_admins_threat(message.from_user, threat_title, f"[Rasm izohi] {caption}")
bot.reply_to(
message,
"⚠️ Xavfsizlik ogohlantirishi:\n"
"Rasm izohida tizim xavfsizlik qoidalariga zid belgilar aniqlandi. "
"Bu haqda loyiha administratoriga xabar berildi.",
parse_mode="HTML"
)
return
try:
record_user_activity(message.from_user.id, message.from_user.username, message.from_user.first_name)
except Exception:
pass
wait_msg = None
try:
wait_msg = bot.reply_to(message, "📸 _Rasm o'qilmoqda..._", parse_mode="Markdown")
except Exception:
try:
wait_msg = bot.reply_to(message, "📸 Rasm o'qilmoqda...")
except Exception:
pass
try:
file_info = bot.get_file(message.photo[-1].file_id)
downloaded_file = bot.download_file(file_info.file_path)
user_caption = (message.caption or "").strip()
extracted_text = extract_problem_from_image(downloaded_file, user_caption=user_caption)
if not extracted_text:
err = "❌ Rasmdan masala matnini o'qib bo'lmadi. Iltimos, yorug'roq yoki aniqroq rasm yuboring."
if wait_msg:
bot.edit_message_text(err, chat_id=message.chat.id, message_id=wait_msg.message_id)
else:
bot.reply_to(message, err)
return
cleaned_ocr = clean_math_display(extracted_text)
preview = f"📝 Rasmdan o'qildi:\n{_render_html_prose(cleaned_ocr)}\n\n⏳ Yechim tayyorlanmoqda..."
if wait_msg:
safe_send_reply(message, preview, edit_msg=wait_msg, parse_mode="HTML")
message.text = cleaned_ocr
t = threading.Thread(
target=process_and_reply,
kwargs={
"message": message,
"existing_wait_msg": wait_msg,
"is_photo": True,
"history_user_msg": f"[Rasm] {cleaned_ocr}",
}
)
t.start()
except Exception as e:
err = f"❌ Rasmni yuklashda xatolik yuz berdi: {e}"
if wait_msg:
try:
bot.edit_message_text(err, chat_id=message.chat.id, message_id=wait_msg.message_id)
except Exception:
pass
else:
bot.reply_to(message, err)
@bot.message_handler(content_types=['voice', 'audio'])
def handle_voice_message(message):
user_id = message.from_user.id
# 1. Bloklangan foydalanuvchini tekshirish
is_banned, ban_reason = is_user_banned(user_id)
if is_banned:
bot.reply_to(message, f"⛔ Siz qoidabuzarlik sababli botdan chetlatilgansiz.\nSabab: {ban_reason}")
return
try:
record_user_activity(message.from_user.id, message.from_user.username, message.from_user.first_name)
except Exception:
pass
wait_msg = None
try:
wait_msg = bot.reply_to(message, "🎙 Ovoz eshitilmoqda va matnga aylantirilmoqda...", parse_mode="HTML")
except Exception:
pass
try:
file_obj = message.voice or message.audio
if not file_obj:
return
file_info = bot.get_file(file_obj.file_id)
downloaded_file = bot.download_file(file_info.file_path)
ext = "ogg" if message.voice else "mp3"
transcribed_text = transcribe_voice(downloaded_file, filename=f"voice.{ext}")
if not transcribed_text:
err = "❌ Ovozni aniqlab bo'lmadi. Iltimos, aniqroq gapirib qayta yuboring yoki matn ko'rinishida yozing."
if wait_msg:
bot.edit_message_text(err, chat_id=message.chat.id, message_id=wait_msg.message_id)
else:
bot.reply_to(message, err)
return
# 2. Xavfsizlik tahlili
if not check_is_admin(user_id):
is_threat, threat_title, threat_reason = analyze_message_threat(user_id, transcribed_text)
if is_threat:
alert_admins_threat(message.from_user, threat_title, f"[Ovozli xabar] {transcribed_text}")
bot.reply_to(
message,
"⚠️ Xavfsizlik ogohlantirishi:\n"
"Ovozli xabarda tizim xavfsizlik qoidalariga zid belgilar aniqlandi. "
"Bu haqda loyiha administratoriga xabar berildi.",
parse_mode="HTML"
)
return
cleaned_text = clean_math_display(transcribed_text)
preview = f"🎙 Ovozingizdan o'qildi:\n«{_render_html_prose(cleaned_text)}»\n\n⏳ Yechim tayyorlanmoqda..."
if wait_msg:
safe_send_reply(message, preview, edit_msg=wait_msg, parse_mode="HTML")
message.text = cleaned_text
t = threading.Thread(
target=process_and_reply,
kwargs={
"message": message,
"existing_wait_msg": wait_msg,
"is_photo": False,
"is_voice": True,
"history_user_msg": f"[Ovoz] {cleaned_text}",
}
)
t.start()
except Exception as e:
err = f"❌ Ovozli xabarni yuklashda xatolik yuz berdi: {e}"
if wait_msg:
try:
bot.edit_message_text(err, chat_id=message.chat.id, message_id=wait_msg.message_id)
except Exception:
pass
else:
bot.reply_to(message, err)
@bot.message_handler(func=lambda message: True)
def handle_all_messages(message):
text = (message.text or "").strip()
if not text:
return
user_id = message.from_user.id
# 1. Bloklangan foydalanuvchini tekshirish
is_banned, ban_reason = is_user_banned(user_id)
if is_banned:
bot.reply_to(message, f"⛔ Siz qoidabuzarlik sababli botdan chetlatilgansiz.\nSabab: {ban_reason}")
return
# 2. Admin bo'lmagan foydalanuvchilar xabarini xavfsizlik bo'yicha tahlil qilish
if not check_is_admin(user_id):
is_threat, threat_title, threat_reason = analyze_message_threat(user_id, text)
if is_threat:
alert_admins_threat(message.from_user, threat_title, text)
bot.reply_to(
message,
"⚠️ Xavfsizlik ogohlantirishi:\n"
"Yuborgan so'rovingizda tizim xavfsizlik qoidalariga zid belgilar aniqlandi. "
"Bu haqda loyiha administratoriga xabar berildi.",
parse_mode="HTML"
)
return
# Agar foydalanuvchi tasodifan "/ xato" ko'rinishida bo'sh joy bilan buyruq yozsa
if re.match(r"^/\s+(start|help|info|about|yangi|new|clear|reset|id|myid|admin|stat|stats|broadcast|xato|fikr|taklif|feedback|xatolar|feedbacks|ban|unban|banlar)\b", text, re.IGNORECASE):
text = re.sub(r"^/\s+", "/", text)
message.text = text
if text.startswith("/"):
cmd = text.split()[0].lower().split("@")[0]
if cmd in ["/admin", "/stat", "/stats"]:
admin_panel(message)
return
elif cmd in ["/start", "/help", "/info", "/about"]:
send_welcome(message)
return
elif cmd in ["/yangi", "/new", "/clear", "/reset"]:
new_chat_command(message)
return
elif cmd in ["/id", "/myid"]:
show_my_id(message)
return
elif cmd == "/broadcast":
broadcast_message(message)
return
elif cmd in ["/xato", "/fikr", "/taklif", "/feedback"]:
report_feedback(message)
return
elif cmd in ["/xatolar", "/feedbacks"]:
show_feedbacks(message)
return
elif cmd == "/ban":
handle_ban_command(message)
return
elif cmd == "/unban":
handle_unban_command(message)
return
elif cmd in ["/banlar", "/banned"]:
handle_banned_list(message)
return
else:
bot.reply_to(message, "ℹ️ Noma'lum buyruq. Savolingiz yoki misolingizni oddiy matn ko'rinishida yozavering.")
return
# Agar foydalanuvchi /xato yoki 🚨 Xato tugmasidan keyin izoh yozayotgan bo'lsa
user_id = message.from_user.id
with _bug_report_lock:
has_pending_bug = user_id in awaiting_bug_report
bug_ctx = awaiting_bug_report.pop(user_id, "") if has_pending_bug else ""
if has_pending_bug:
record_user_activity(user_id, message.from_user.username, message.from_user.first_name)
send_bug_report_to_admins(message.from_user, text, bug_ctx)
bot.reply_to(message, "✅ *Katta rahmat!* Xabaringiz loyiha muallifiga yetkazildi. 🤝", parse_mode="Markdown")
return
t = threading.Thread(target=process_and_reply, args=(message,))
t.start()
def run_bot():
if not TOKEN or TOKEN == "dummy_token":
print("Iltimos, avval .env fayliga TELEGRAM_BOT_TOKEN ni kiriting!")
return
print("=" * 70)
print("Sincc.on Telegram Boti (Matn + Rasm-OCR + Ovoz-Whisper + Geometriya) ishga tushdi...")
print("=" * 70)
setup_bot_commands()
while True:
try:
bot.infinity_polling(timeout=25, long_polling_timeout=25)
except Exception as e:
print(f"Telegram polling xatoligi: {e}. 3 soniyadan keyin qayta ulanadi...")
time.sleep(3)
if __name__ == "__main__":
run_bot()