Download bot.py from Shaptoli/Sinccon: direct link, hf CLI and curl.
- Browser
- Download file 63.3 kB
-
https://huggingface.co/spaces/Shaptoli/Sinccon/resolve/main/bot.py
- Command line
-
hf download hf://spaces/Shaptoli/Sinccon/bot.py
-
curl -L -o bot.py https://huggingface.co/spaces/Shaptoli/Sinccon/resolve/main/bot.py
63.3 kB
"""
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"(?<!\d)\$([^\n$]+?)\$(?!\d)", r"\1", s)
s = re.sub(r"\\(?:text|mathrm|mathbf|mathit)\{([^{}]*)\}", r"\1", s)
s = s.replace("\\left", "").replace("\\right", "")
replacements = [
("\\times", "Γ"), ("\\cdot", "Β·"), ("\\div", "Γ·"), ("\\pm", "Β±"), ("\\mp", "β"),
("\\leq", "β€"), ("\\le", "β€"), ("\\geq", "β₯"), ("\\ge", "β₯"),
("\\neq", "β "), ("\\ne", "β "), ("\\approx", "β"), ("\\infty", "β"),
("\\pi", "Ο"), ("\\alpha", "Ξ±"), ("\\beta", "Ξ²"), ("\\gamma", "Ξ³"),
("\\theta", "ΞΈ"), ("\\Delta", "Ξ"), ("\\degree", "Β°"), ("^\\circ", "Β°"),
("\\Rightarrow", "β"), ("\\rightarrow", "β"), ("\\to", "β"),
]
for old, new in replacements:
s = s.replace(old, new)
s = s.replace("^{2}", "Β²").replace("^{3}", "Β³")
s = re.sub(r"([A-Za-z0-9\)])\*\*([0-9]+)\b", lambda m: m.group(1) + m.group(2).translate(_SUPERSCRIPT_MAP), s)
s = re.sub(r"([A-Za-z0-9\)])\^([0-9]+)\b", lambda m: m.group(1) + m.group(2).translate(_SUPERSCRIPT_MAP), s)
s = re.sub(r"\b([A-Za-zΠ-Π―Π°-Ρ])_\{?([0-9nijk]+)\}?(?=$|[^A-Za-z0-9_])",
lambda m: m.group(1) + m.group(2).translate(_SUBSCRIPT_MAP), s)
for _ in range(2):
s = re.sub(r"\\frac\{([^{}]+)\}\{([^{}]+)\}", lambda m: (
f"{m.group(1)}/{m.group(2)}"
if re.fullmatch(r"[A-Za-z0-9ΟβΒ²Β³β°ΒΉβ΄β΅βΆβ·βΈβΉββββββ
ββββ]+", m.group(1).strip())
and re.fullmatch(r"[A-Za-z0-9ΟβΒ²Β³β°ΒΉβ΄β΅βΆβ·βΈβΉββββββ
ββββ]+", m.group(2).strip())
else f"({m.group(1)})/({m.group(2)})"
), s)
s = re.sub(r"\\sqrt\{([^{}]+)\}", r"β(\1)", s)
s = re.sub(r"\\sqrt\s+([A-Za-z0-9]+)", r"β\1", s)
s = re.sub(r"\bsqrt\(", "β(", s)
s = re.sub(r"(?<![A-Za-z])(-?)oo(?![A-Za-z])", lambda m: f"{m.group(1)}β", s)
s = re.sub(r"(?<!\*)(?<=[A-Za-z0-9\)ΟΒ²Β³β΄β΅βΆβ·βΈβΉβ°])\*(?!\*)(?=[A-Za-z0-9\(βΟ])", "Β·", s)
# **qalin** CommonMark yozuvini Telegram Markdown *qalin* ga aylantirish
s = re.sub(r"(^|[\s(>\"'])(\*\*)(?=\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<b>\2</b>", escaped)
escaped = re.sub(r"`([^`\n]+)`", r"<code>\1</code>", 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 = (
"π¨ <b>YANGI XATOLIK / FIKR XABARI!</b> π©\n\n"
f"π€ <b>Yuboruvchi:</b> {html.escape(sender_name)} (<code>{from_user.id}</code>)\n"
f"π¬ <b>Foydalanuvchi izohi:</b>\n<i>{html.escape(comment or 'Izoh yozilmagan')}</i>\n"
)
if reply_context:
admin_alert_html += f"\nπ <b>Tegishli xabar matni:</b>\n<code>{html.escape(reply_context[:350])}</code>"
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 = (
"π¨ <b>XAVFLI HARAKAT / TAHDID ANIQLANDI!</b> β οΈ\n\n"
f"π€ <b>Foydalanuvchi:</b> {html.escape(sender_name)} (<code>{from_user.id}</code>)\n"
f"π <b>Ismi:</b> {html.escape(from_user.first_name or '')}\n"
f"β οΈ <b>Tahdid turi:</b> <b>{html.escape(threat_type)}</b>\n"
f"π <b>Xabar matni:</b>\n<code>{html.escape(message_text[:400])}</code>\n"
f"β± <b>Vaqt:</b> {now_str}\n\n"
"<i>Quyidagi tugma orqali ushbu foydalanuvchini botdan zudlik bilan bloklashingiz mumkin:</i>"
)
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, "π <b>Suhbat xotirasi tozalandi.</b> 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,
"βΉοΈ <b>Hozircha siz yechgan oxirgi masala topilmadi.</b>\n"
"Avval biror masala yuboring (masalan: <code>x^2 - 5x + 6 = 0</code>), so'ngra <b>/konspekt</b> buyrug'ini bering!",
parse_mode="HTML"
)
return
wait_msg = bot.reply_to(message, "π <i>A4 PDF konspekt tayyorlanmoqda...</i>", 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="π <b>Sincc.on: Ushbu masalaning A4 PDF Konspekti</b>\n"
"<i>Chop etish va darsda/imtihonda foydalanish uchun to'liq yechim va chizma.</i>",
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: <code>{message.from_user.id}</code>", 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 = (
"π <b>Sincc.on Admin Statistikasi:</b>\n\n"
f"π₯ <b>Jami foydalanuvchilar:</b> {stats['total_users']} ta\n"
f"π
<b>Bugungi faol:</b> {stats['active_today']} ta\n"
f"β‘ <b>Jami yechilgan masalalar:</b> {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"π© <b>Xatolik/fikr xabarlari:</b> {stats.get('total_feedbacks', 0)} ta (/xatolar)\n"
f"π« <b>Bloklanganlar:</b> {stats.get('total_banned', 0)} ta (/banlar)\n\n"
f"π <b>So'nggi foydalanuvchilar:</b>\n<code>{html.escape(recent_text)}</code>\n"
"π’ <b>Admin buyruqlari:</b>\n"
"β’ <code>/broadcast <matn></code> β Barcha foydalanuvchilarga xabar\n"
"β’ <code>/ban <id> [sabab]</code> β Foydalanuvchini bloklash\n"
"β’ <code>/unban <id></code> β Blokdan chiqarish\n"
"β’ <code>/banlar</code> β Bloklanganlar ro'yxati\n"
"β’ <code>/xatolar</code> β 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 <user_id> [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 <user_id>`\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 = "π« <b>Bloklangan foydalanuvchilar:</b>\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}. <b>{html.escape(uname)}</b> (<code>{b['user_id']}</code>)\n"
text += f" β’ Sabab: <i>{html.escape(b['reason'])}</i>\n"
text += f" β’ Vaqt: {b['banned_at'][:16]}\n"
text += "\n<i>Blokdan chiqarish: /unban <user_id></i>"
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 = "π¬ <b>So'nggi 5 ta xatolik / fikr xabarlari:</b>\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"πΉ <b>#{fid}</b> | {u_str} | <i>{ftime[5:16]}</i>\n"
text += f"π¬ <b>Fikr:</b> {html.escape(fmsg)}\n"
if rcontext:
text += f"π <b>Kontekst:</b> <code>{html.escape(rcontext[:100])}...</code>\n"
text += "------------------------\n"
try:
bot.reply_to(message, text, parse_mode="HTML")
except Exception:
plain_text = text.replace("<b>", "").replace("</b>", "").replace("<i>", "").replace("</i>", "").replace("<code>", "").replace("</code>", "")
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,
"π’ <b>Xabar yuborish tartibi:</b>\n"
"<code>/broadcast Hurmatli foydalanuvchilar, botda yangi funksiyalar qo'shildi!</code>",
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"π’ <b>Sincc.on E'loni:</b>\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 <b>{success_count}/{len(user_ids)}</b> 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, <b>{html.escape(fname)}</b>! Men <b>Sincc.on</b> β matematika bo'yicha milliy AI ustozingizman. ππ\n\n"
"Menga xohlagan matematik masalangizni yuborishingiz mumkin:\n"
"β’ π <b>Matn ko'rinishida:</b> <code>x^2 - 5x + 6 = 0</code>\n"
"β’ πΈ <b>Rasm ko'rinishida:</b> Kitob yoki daftardagi misolni rasmga olib yuboring\n"
"β’ π <b>Ovozli xabar:</b> Masala shartini audio tarzida ayting\n"
"β’ π’ <b>Klaviatura:</b> /klaviatura orqali qulay matematik belgilarni tering\n\n"
"Tizim hisoblashlarni <b>100% xatosiz (SymPy ramziy yadrosi)</b> tekshiradi va qadam-baqadam yechim, qoidalar va geometrik chizmalar bilan tushuntiradi!\n\n"
"<i>Boshlash uchun quyidagi tugmalardan birini bosing yoki to'g'ridan-to'g'ri misolingizni yozib yuboring:</i> π"
)
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 = (
"π <b>Sincc.on Botidan Foydalanish Qo'llanmasi:</b>\n\n"
"<b>1. Masala yuborish usullari:</b>\n"
"β’ <b>Matn:</b> Algebra, geometriya, matnli masalalar (masalan: <i>Β«Hovuzni 1-quvur 3 soatda, 2-quvur 6 soatda to'ldiradi...Β»</i>)\n"
"β’ <b>Rasm (Vision OCR):</b> Yaxshi yorug'likda daftardagi qo'lyozma yoki darslik rasmini yuboring\n"
"β’ <b>Ovoz (Whisper):</b> Telegram audio yoki mikrofon orqali gapiring\n\n"
"<b>2. Mavjud Buyruqlar:</b>\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"
"<b>3. Savol-javob va chuqur tahlil:</b>\n"
"Har bir yechimdan so'ng tushunmagan joyingizni bemalol qayta so'rashingiz mumkin:\n"
"β’ <i>Β«2-qadamni tushunmadim, soddaroq tushuntirΒ»</i>\n"
"β’ <i>Β«Boshqa usul bilan yechib ko'rsatΒ»</i>\n"
"β’ <i>Β«Shunga o'xshash yangi mashq ber, o'zim yechamanΒ»</i>"
)
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 (
"π’ <b>Matematik Belgilar & Formula Paneli:</b>\n\n"
f"π <b>Joriy ifoda:</b> <code>{html.escape(display_f)}</code>\n\n"
"<i>Quyidagi tugmalar orqali formulangizni shakllantiring va <b>Β«π Masalani YechishΒ»</b> tugmasini bosing:</i>"
)
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"πΉ <b>{html.escape(hdr)}:</b> {_render_html_prose(body)}")
plain_steps.append(f"πΉ {hdr}: {_strip_markdown(body)}")
else:
formatted_steps_html.append(f"πΉ <b>{html.escape(hdr)}</b>")
plain_steps.append(f"πΉ {hdr}")
else:
body = s_clean.lstrip("β’- ")
formatted_steps_html.append(f"πΉ <b>{idx}-qadam:</b> {_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 = "π <b>Ishlatilgan qoidalar:</b>\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"β
<b>Javob:</b> <b>{html.escape(final_ans_plain)}</b>" 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"π‘ <i>{html.escape(exp_tip_plain)}</i>" 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("β <i>SymPy da tekshirildi</i>")
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, "β³ <i>Masala tahlil qilinmoqda va hisob-kitob tekshirilmoqda...</i>", 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="π <b>Sincc.on: Ushbu masalaning A4 PDF Konspekti</b>\n"
"<i>Chop etish va darsda/imtihonda foydalanish uchun to'liq yechim va chizma.</i>",
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("π’ <i>Matematik klaviatura yopildi.</i>", 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"π <b>Hisoblanmoqda:</b> <code>{html.escape(formula)}</code>",
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, "π <b>Suhbat xotirasi yangilandi.</b> 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<code>/broadcast Xabar matni...</code>", 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,
"β οΈ <b>Xavfsizlik ogohlantirishi:</b>\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"π <b>Rasmdan o'qildi:</b>\n{_render_html_prose(cleaned_ocr)}\n\nβ³ <i>Yechim tayyorlanmoqda...</i>"
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, "π <i>Ovoz eshitilmoqda va matnga aylantirilmoqda...</i>", 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,
"β οΈ <b>Xavfsizlik ogohlantirishi:</b>\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"π <b>Ovozingizdan o'qildi:</b>\nΒ«<i>{_render_html_prose(cleaned_text)}</i>Β»\n\nβ³ <i>Yechim tayyorlanmoqda...</i>"
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,
"β οΈ <b>Xavfsizlik ogohlantirishi:</b>\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()
"""
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"(?<!\d)\$([^\n$]+?)\$(?!\d)", r"\1", s)
s = re.sub(r"\\(?:text|mathrm|mathbf|mathit)\{([^{}]*)\}", r"\1", s)
s = s.replace("\\left", "").replace("\\right", "")
replacements = [
("\\times", "Γ"), ("\\cdot", "Β·"), ("\\div", "Γ·"), ("\\pm", "Β±"), ("\\mp", "β"),
("\\leq", "β€"), ("\\le", "β€"), ("\\geq", "β₯"), ("\\ge", "β₯"),
("\\neq", "β "), ("\\ne", "β "), ("\\approx", "β"), ("\\infty", "β"),
("\\pi", "Ο"), ("\\alpha", "Ξ±"), ("\\beta", "Ξ²"), ("\\gamma", "Ξ³"),
("\\theta", "ΞΈ"), ("\\Delta", "Ξ"), ("\\degree", "Β°"), ("^\\circ", "Β°"),