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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
# -*- coding: utf-8 -*-
|
| 3 |
+
"""
|
| 4 |
+
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 5 |
+
๐ก Telegram Auto Sender Bot - Gradio Space Edition
|
| 6 |
+
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 7 |
+
- ุฅุฑุณุงู ุฑุณุงุฆู ุฏูุฑูุฉ ุชููุงุฆูุฉ ููู
ุฌู
ูุนุงุช ุจูุงุตู ุฒู
ูู ูุงุจู ููุชุฎุตูุต
|
| 8 |
+
- ูุต ุงูุฑุณุงูุฉ ูุงุจู ููุชุญุฑูุฑ ู
ู ุฏุงุฎู ุงูุจูุช
|
| 9 |
+
- ุฒุฑ ุฅุฑุณุงู ููุฑู ููู ุงูู
ุฌู
ูุนุงุช
|
| 10 |
+
- ุฅุดุนุงุฑ ููุฑู ุนูุฏ ุงูุฑุฏ ุนูู ุฑุณุงุฆู ุงูุจูุช
|
| 11 |
+
- ูุนู
ู ู
ุน Hugging Face Spaces ุจุงุณุชุฎุฏุงู
Gradio SDK
|
| 12 |
+
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
import os
|
| 16 |
+
import logging
|
| 17 |
+
import asyncio
|
| 18 |
+
import sqlite3
|
| 19 |
+
import threading
|
| 20 |
+
import traceback
|
| 21 |
+
from datetime import datetime
|
| 22 |
+
from pathlib import Path
|
| 23 |
+
from typing import Dict, Optional, List, Tuple
|
| 24 |
+
|
| 25 |
+
import gradio as gr
|
| 26 |
+
from telegram import (
|
| 27 |
+
Bot, Update, InlineKeyboardButton, InlineKeyboardMarkup, ParseMode
|
| 28 |
+
)
|
| 29 |
+
from telegram.ext import (
|
| 30 |
+
Updater, CommandHandler, CallbackQueryHandler, MessageHandler, Filters,
|
| 31 |
+
CallbackContext
|
| 32 |
+
)
|
| 33 |
+
from telethon import TelegramClient, events
|
| 34 |
+
from telethon.sessions import StringSession
|
| 35 |
+
from telethon.errors import FloodWaitError
|
| 36 |
+
|
| 37 |
+
# โโโโโโโโโโโโโโโโโโโโโโโ Logging โโโโโโโโโโโโโโโโโโโโโโโ
|
| 38 |
+
logging.basicConfig(
|
| 39 |
+
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
|
| 40 |
+
level=logging.INFO
|
| 41 |
+
)
|
| 42 |
+
logger = logging.getLogger(__name__)
|
| 43 |
+
|
| 44 |
+
# โโโโโโโโโโโโโโโโโโโโโโโ Environment โโโโโโโโโโโโโโโโโโโโโโโ
|
| 45 |
+
BOT_TOKEN = os.environ.get("TELEGRAM_BOT_TOKEN")
|
| 46 |
+
API_ID = int(os.environ.get("TELEGRAM_API_ID", 0))
|
| 47 |
+
API_HASH = os.environ.get("TELEGRAM_API_HASH", "")
|
| 48 |
+
|
| 49 |
+
DATA_DIR = Path("/data")
|
| 50 |
+
DB_PATH = DATA_DIR / "users.db"
|
| 51 |
+
try:
|
| 52 |
+
DATA_DIR.mkdir(exist_ok=True)
|
| 53 |
+
except Exception:
|
| 54 |
+
# ุนูู HF Spaces ูุฏ ูุง ูููู ูุฏูู ุตูุงุญูุฉ ุงููุชุงุจุฉ ูู /dataุ ุงุณุชุฎุฏู
ู
ุฌูุฏ ู
ุญูู
|
| 55 |
+
DATA_DIR = Path("./data")
|
| 56 |
+
DATA_DIR.mkdir(exist_ok=True)
|
| 57 |
+
DB_PATH = DATA_DIR / "users.db"
|
| 58 |
+
|
| 59 |
+
DEFAULT_MESSAGE = (
|
| 60 |
+
"๐ ุนุฑุถ ุฎุงุต!\n"
|
| 61 |
+
"ููุฏู
ุฎุฏู
ุงุช ู
ู
ูุฒุฉ ุจุฃุณุนุงุฑ ู
ูุงุณุจุฉ.\n"
|
| 62 |
+
"ููุชูุงุตู: @username"
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
INTERVAL_OPTIONS = [15, 30, 60, 120, 240, 480, 720, 1440]
|
| 66 |
+
|
| 67 |
+
# โโโโโโโโโโโโโโโโโโโโโโโ Database โโโโโโโโโโโโโโโโโโโโโโโ
|
| 68 |
+
def init_db():
|
| 69 |
+
conn = sqlite3.connect(str(DB_PATH))
|
| 70 |
+
c = conn.cursor()
|
| 71 |
+
c.execute('''
|
| 72 |
+
CREATE TABLE IF NOT EXISTS users (
|
| 73 |
+
user_id INTEGER PRIMARY KEY,
|
| 74 |
+
session_string TEXT,
|
| 75 |
+
phone_number TEXT,
|
| 76 |
+
alert_target TEXT DEFAULT 'private',
|
| 77 |
+
alert_target_id TEXT,
|
| 78 |
+
scheduling_active INTEGER DEFAULT 0,
|
| 79 |
+
interval_minutes INTEGER DEFAULT 60,
|
| 80 |
+
message_text TEXT DEFAULT '',
|
| 81 |
+
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
| 82 |
+
)
|
| 83 |
+
''')
|
| 84 |
+
c.execute('''
|
| 85 |
+
CREATE TABLE IF NOT EXISTS user_groups (
|
| 86 |
+
user_id INTEGER,
|
| 87 |
+
group_id INTEGER,
|
| 88 |
+
group_title TEXT,
|
| 89 |
+
PRIMARY KEY (user_id, group_id)
|
| 90 |
+
)
|
| 91 |
+
''')
|
| 92 |
+
c.execute('''
|
| 93 |
+
CREATE TABLE IF NOT EXISTS sent_messages (
|
| 94 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 95 |
+
user_id INTEGER,
|
| 96 |
+
chat_id INTEGER,
|
| 97 |
+
message_id INTEGER,
|
| 98 |
+
sent_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
| 99 |
+
)
|
| 100 |
+
''')
|
| 101 |
+
c.execute('CREATE INDEX IF NOT EXISTS idx_sent_lookup ON sent_messages (user_id, chat_id, message_id)')
|
| 102 |
+
conn.commit()
|
| 103 |
+
conn.close()
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def _conn():
|
| 107 |
+
return sqlite3.connect(str(DB_PATH))
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def db_get_user(user_id: int):
|
| 111 |
+
conn = _conn()
|
| 112 |
+
c = conn.cursor()
|
| 113 |
+
c.execute("SELECT * FROM users WHERE user_id=?", (user_id,))
|
| 114 |
+
row = c.fetchone()
|
| 115 |
+
conn.close()
|
| 116 |
+
return row
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def db_save_session(user_id: int, session_string: str, phone: str = ""):
|
| 120 |
+
conn = _conn()
|
| 121 |
+
c = conn.cursor()
|
| 122 |
+
c.execute('''
|
| 123 |
+
INSERT INTO users (user_id, session_string, phone_number, message_text)
|
| 124 |
+
VALUES (?, ?, ?, COALESCE((SELECT message_text FROM users WHERE user_id=?), ?))
|
| 125 |
+
ON CONFLICT(user_id) DO UPDATE SET
|
| 126 |
+
session_string=excluded.session_string,
|
| 127 |
+
phone_number=excluded.phone_number
|
| 128 |
+
''', (user_id, session_string, phone, user_id, DEFAULT_MESSAGE))
|
| 129 |
+
conn.commit()
|
| 130 |
+
conn.close()
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def db_update_alert(user_id: int, target: str, target_id: Optional[str] = None):
|
| 134 |
+
conn = _conn()
|
| 135 |
+
c = conn.cursor()
|
| 136 |
+
if target_id is not None:
|
| 137 |
+
c.execute("UPDATE users SET alert_target=?, alert_target_id=? WHERE user_id=?",
|
| 138 |
+
(target, target_id, user_id))
|
| 139 |
+
else:
|
| 140 |
+
c.execute("UPDATE users SET alert_target=? WHERE user_id=?", (target, user_id))
|
| 141 |
+
conn.commit()
|
| 142 |
+
conn.close()
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def db_update_interval(user_id: int, minutes: int):
|
| 146 |
+
conn = _conn()
|
| 147 |
+
c = conn.cursor()
|
| 148 |
+
c.execute("UPDATE users SET interval_minutes=? WHERE user_id=?", (minutes, user_id))
|
| 149 |
+
conn.commit()
|
| 150 |
+
conn.close()
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def db_update_message(user_id: int, text: str):
|
| 154 |
+
conn = _conn()
|
| 155 |
+
c = conn.cursor()
|
| 156 |
+
c.execute("UPDATE users SET message_text=? WHERE user_id=?", (text, user_id))
|
| 157 |
+
conn.commit()
|
| 158 |
+
conn.close()
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def db_set_scheduling(user_id: int, active: bool):
|
| 162 |
+
conn = _conn()
|
| 163 |
+
c = conn.cursor()
|
| 164 |
+
c.execute("UPDATE users SET scheduling_active=? WHERE user_id=?",
|
| 165 |
+
(1 if active else 0, user_id))
|
| 166 |
+
conn.commit()
|
| 167 |
+
conn.close()
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def db_get_user_groups(user_id: int) -> List[Tuple[int, str]]:
|
| 171 |
+
conn = _conn()
|
| 172 |
+
c = conn.cursor()
|
| 173 |
+
c.execute("SELECT group_id, group_title FROM user_groups WHERE user_id=?", (user_id,))
|
| 174 |
+
rows = c.fetchall()
|
| 175 |
+
conn.close()
|
| 176 |
+
return rows
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
def db_save_user_groups(user_id: int, groups: List[Tuple[int, str]]):
|
| 180 |
+
conn = _conn()
|
| 181 |
+
c = conn.cursor()
|
| 182 |
+
c.execute("DELETE FROM user_groups WHERE user_id=?", (user_id,))
|
| 183 |
+
for gid, gtitle in groups:
|
| 184 |
+
c.execute("INSERT INTO user_groups (user_id, group_id, group_title) VALUES (?, ?, ?)",
|
| 185 |
+
(user_id, gid, gtitle))
|
| 186 |
+
conn.commit()
|
| 187 |
+
conn.close()
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
def db_save_sent(user_id: int, chat_id: int, message_id: int):
|
| 191 |
+
conn = _conn()
|
| 192 |
+
c = conn.cursor()
|
| 193 |
+
c.execute("INSERT INTO sent_messages (user_id, chat_id, message_id) VALUES (?, ?, ?)",
|
| 194 |
+
(user_id, chat_id, message_id))
|
| 195 |
+
conn.commit()
|
| 196 |
+
conn.close()
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def db_is_our_message(user_id: int, chat_id: int, message_id: int) -> bool:
|
| 200 |
+
conn = _conn()
|
| 201 |
+
c = conn.cursor()
|
| 202 |
+
c.execute("SELECT 1 FROM sent_messages WHERE user_id=? AND chat_id=? AND message_id=? LIMIT 1",
|
| 203 |
+
(user_id, chat_id, message_id))
|
| 204 |
+
row = c.fetchone()
|
| 205 |
+
conn.close()
|
| 206 |
+
return row is not None
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
def db_cleanup_old_sent(days: int = 14):
|
| 210 |
+
conn = _conn()
|
| 211 |
+
c = conn.cursor()
|
| 212 |
+
c.execute(f"DELETE FROM sent_messages WHERE sent_at < datetime('now', '-{days} days')")
|
| 213 |
+
conn.commit()
|
| 214 |
+
conn.close()
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
def db_all_active_users() -> List[int]:
|
| 218 |
+
conn = _conn()
|
| 219 |
+
c = conn.cursor()
|
| 220 |
+
c.execute("SELECT user_id FROM users WHERE scheduling_active=1 AND session_string IS NOT NULL")
|
| 221 |
+
rows = [r[0] for r in c.fetchall()]
|
| 222 |
+
conn.close()
|
| 223 |
+
return rows
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
init_db()
|
| 227 |
+
|
| 228 |
+
# โโโโโโโโโโโโโโโโโโโโโโโ Session Manager โโโโโโโโโโโโโโโโโโโโโโโ
|
| 229 |
+
class SessionManager:
|
| 230 |
+
def __init__(self):
|
| 231 |
+
self.clients: Dict[int, TelegramClient] = {}
|
| 232 |
+
self.keepalive_tasks: Dict[int, asyncio.Task] = {}
|
| 233 |
+
self.schedule_tasks: Dict[int, asyncio.Future] = {}
|
| 234 |
+
self.loop = asyncio.new_event_loop()
|
| 235 |
+
self.bot: Optional[Bot] = None
|
| 236 |
+
self._lock = threading.Lock()
|
| 237 |
+
|
| 238 |
+
def start_loop(self):
|
| 239 |
+
def run():
|
| 240 |
+
asyncio.set_event_loop(self.loop)
|
| 241 |
+
self.loop.run_forever()
|
| 242 |
+
threading.Thread(target=run, daemon=True, name="telethon-loop").start()
|
| 243 |
+
|
| 244 |
+
def run_coro(self, coro, timeout: float = 60):
|
| 245 |
+
future = asyncio.run_coroutine_threadsafe(coro, self.loop)
|
| 246 |
+
return future.result(timeout=timeout)
|
| 247 |
+
|
| 248 |
+
def set_bot(self, bot: Bot):
|
| 249 |
+
self.bot = bot
|
| 250 |
+
|
| 251 |
+
# โโ Session validation โโ
|
| 252 |
+
async def _validate_session(self, session_string: str):
|
| 253 |
+
client = TelegramClient(StringSession(session_string), API_ID, API_HASH)
|
| 254 |
+
try:
|
| 255 |
+
await asyncio.wait_for(client.connect(), timeout=20)
|
| 256 |
+
if await client.is_user_authorized():
|
| 257 |
+
me = await client.get_me()
|
| 258 |
+
phone = me.phone or ""
|
| 259 |
+
await client.disconnect()
|
| 260 |
+
return True, phone
|
| 261 |
+
await client.disconnect()
|
| 262 |
+
return False, "ุงูุฌูุณุฉ ุบูุฑ ู
ุตุฑุญ ุจูุง"
|
| 263 |
+
except asyncio.TimeoutError:
|
| 264 |
+
return False, "ุงูุชูุช ู
ููุฉ ุงูุงุชุตุงู"
|
| 265 |
+
except Exception as e:
|
| 266 |
+
return False, str(e)
|
| 267 |
+
|
| 268 |
+
def validate_session(self, session_string: str):
|
| 269 |
+
return self.run_coro(self._validate_session(session_string), timeout=30)
|
| 270 |
+
|
| 271 |
+
# โโ Fetch groups โโ
|
| 272 |
+
async def _fetch_groups(self, session_str: str):
|
| 273 |
+
client = TelegramClient(StringSession(session_str), API_ID, API_HASH)
|
| 274 |
+
try:
|
| 275 |
+
await asyncio.wait_for(client.connect(), timeout=20)
|
| 276 |
+
if not await client.is_user_authorized():
|
| 277 |
+
raise Exception("ุงูุฌูุณุฉ ุบูุฑ ุตุงูุญุฉ")
|
| 278 |
+
dialogs = await client.get_dialogs()
|
| 279 |
+
groups = [(d.id, d.title) for d in dialogs if d.is_group or d.is_channel]
|
| 280 |
+
await client.disconnect()
|
| 281 |
+
return groups
|
| 282 |
+
except asyncio.TimeoutError:
|
| 283 |
+
raise Exception("ุงูุชูุช ู
ููุฉ ุงูุงุชุตุงู")
|
| 284 |
+
|
| 285 |
+
def fetch_groups(self, session_str: str):
|
| 286 |
+
return self.run_coro(self._fetch_groups(session_str), timeout=40)
|
| 287 |
+
|
| 288 |
+
# โโ Client lifecycle โโ
|
| 289 |
+
async def _ensure_client(self, user_id: int) -> Optional[TelegramClient]:
|
| 290 |
+
with self._lock:
|
| 291 |
+
client = self.clients.get(user_id)
|
| 292 |
+
if client and client.is_connected():
|
| 293 |
+
return client
|
| 294 |
+
|
| 295 |
+
user = db_get_user(user_id)
|
| 296 |
+
if not user or not user[1]:
|
| 297 |
+
return None
|
| 298 |
+
|
| 299 |
+
client = TelegramClient(StringSession(user[1]), API_ID, API_HASH)
|
| 300 |
+
try:
|
| 301 |
+
await client.start()
|
| 302 |
+
except Exception as e:
|
| 303 |
+
logger.error(f"Start client failed for {user_id}: {e}")
|
| 304 |
+
return None
|
| 305 |
+
|
| 306 |
+
@client.on(events.NewMessage())
|
| 307 |
+
async def _on_new(event):
|
| 308 |
+
try:
|
| 309 |
+
await self._handle_new_message(user_id, event)
|
| 310 |
+
except Exception as e:
|
| 311 |
+
logger.error(f"Reply handler error [{user_id}]: {e}\n{traceback.format_exc()}")
|
| 312 |
+
|
| 313 |
+
with self._lock:
|
| 314 |
+
self.clients[user_id] = client
|
| 315 |
+
if user_id not in self.keepalive_tasks or self.keepalive_tasks[user_id].done():
|
| 316 |
+
self.keepalive_tasks[user_id] = asyncio.create_task(self._keepalive(user_id, client))
|
| 317 |
+
|
| 318 |
+
logger.info(f"โ
Client started for {user_id}")
|
| 319 |
+
return client
|
| 320 |
+
|
| 321 |
+
async def _keepalive(self, user_id: int, client: TelegramClient):
|
| 322 |
+
while True:
|
| 323 |
+
await asyncio.sleep(60)
|
| 324 |
+
try:
|
| 325 |
+
user = db_get_user(user_id)
|
| 326 |
+
if not user:
|
| 327 |
+
break
|
| 328 |
+
if not client.is_connected():
|
| 329 |
+
logger.warning(f"Client {user_id} disconnected, reconnecting...")
|
| 330 |
+
await client.connect()
|
| 331 |
+
except Exception as e:
|
| 332 |
+
logger.error(f"Keepalive error [{user_id}]: {e}")
|
| 333 |
+
await asyncio.sleep(15)
|
| 334 |
+
|
| 335 |
+
# โโ Reply handling โโ
|
| 336 |
+
async def _handle_new_message(self, user_id: int, event):
|
| 337 |
+
msg = event.message
|
| 338 |
+
if not msg or not msg.reply_to_msg_id:
|
| 339 |
+
return
|
| 340 |
+
if not db_is_our_message(user_id, msg.chat_id, msg.reply_to_msg_id):
|
| 341 |
+
return
|
| 342 |
+
await self._notify_reply(user_id, event)
|
| 343 |
+
|
| 344 |
+
async def _notify_reply(self, user_id: int, event):
|
| 345 |
+
user = db_get_user(user_id)
|
| 346 |
+
if not user:
|
| 347 |
+
return
|
| 348 |
+
alert_target = user[3]
|
| 349 |
+
alert_target_id = user[4]
|
| 350 |
+
target = user_id if alert_target == "private" else alert_target_id
|
| 351 |
+
if not target:
|
| 352 |
+
return
|
| 353 |
+
|
| 354 |
+
msg = event.message
|
| 355 |
+
try:
|
| 356 |
+
sender = await event.get_sender()
|
| 357 |
+
except Exception:
|
| 358 |
+
sender = None
|
| 359 |
+
|
| 360 |
+
sender_name = ""
|
| 361 |
+
if sender:
|
| 362 |
+
sender_name = getattr(sender, "first_name", "") or ""
|
| 363 |
+
if getattr(sender, "last_name", None):
|
| 364 |
+
sender_name += f" {sender.last_name}"
|
| 365 |
+
if not sender_name:
|
| 366 |
+
sender_name = getattr(sender, "title", "") or "ุบูุฑ ู
ุนุฑูู"
|
| 367 |
+
uname = f"@{sender.username}" if sender and getattr(sender, "username", None) else "ูุง ููุฌุฏ"
|
| 368 |
+
|
| 369 |
+
try:
|
| 370 |
+
chat = await event.get_chat()
|
| 371 |
+
chat_title = getattr(chat, "title", "ู
ุญุงุฏุซุฉ")
|
| 372 |
+
except Exception:
|
| 373 |
+
chat_title = "ู
ุญุงุฏุซุฉ"
|
| 374 |
+
|
| 375 |
+
original_text = "(ุบูุฑ ู
ุชููุฑุฉ)"
|
| 376 |
+
try:
|
| 377 |
+
orig = await event.client.get_messages(msg.chat_id, ids=msg.reply_to_msg_id)
|
| 378 |
+
if orig and orig.text:
|
| 379 |
+
original_text = orig.text
|
| 380 |
+
except Exception:
|
| 381 |
+
pass
|
| 382 |
+
|
| 383 |
+
time_str = msg.date.strftime("%Y-%m-%d %H:%M:%S") if msg.date else datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
| 384 |
+
reply_text = msg.text or "(ุฑุณุงูุฉ ุบูุฑ ูุตูุฉ)"
|
| 385 |
+
|
| 386 |
+
text = (
|
| 387 |
+
f"๐ <b>ุฑุฏ ุฌุฏูุฏ ุนูู ุฑุณุงูุชู</b>\n"
|
| 388 |
+
f"โโโโโโโโโโโโโโโโโโโโโ\n"
|
| 389 |
+
f"๐ค <b>ุงูุงุณู
:</b> {sender_name}\n"
|
| 390 |
+
f"๐ <b>ุงูููุฒุฑ:</b> {uname}\n"
|
| 391 |
+
f"๐ <b>ุงูู
ุนุฑู:</b> <code>{msg.sender_id}</code>\n"
|
| 392 |
+
f"๐ <b>ุงูู
ุฌู
ูุนุฉ:</b> {chat_title}\n"
|
| 393 |
+
f"โฐ <b>ุงูููุช:</b> <code>{time_str}</code>\n"
|
| 394 |
+
f"โโโโโโโโโโโโโโโโโโโโโ\n"
|
| 395 |
+
f"๐ฌ <b>ุฑุณุงูุชู ุงูุฃุตููุฉ:</b>\n<i>{original_text[:300]}</i>\n\n"
|
| 396 |
+
f"โฉ๏ธ <b>ูุต ุงูุฑุฏ:</b>\n<b>{reply_text[:800]}</b>"
|
| 397 |
+
)
|
| 398 |
+
|
| 399 |
+
try:
|
| 400 |
+
await asyncio.to_thread(
|
| 401 |
+
self.bot.send_message,
|
| 402 |
+
chat_id=target,
|
| 403 |
+
text=text,
|
| 404 |
+
parse_mode=ParseMode.HTML,
|
| 405 |
+
disable_web_page_preview=True
|
| 406 |
+
)
|
| 407 |
+
logger.info(f"๐ฉ Reply notified to {target} for user {user_id}")
|
| 408 |
+
except Exception as e:
|
| 409 |
+
logger.error(f"Failed to notify reply: {e}")
|
| 410 |
+
|
| 411 |
+
# โโ Send to all โโ
|
| 412 |
+
async def _send_to_all_groups(self, user_id: int) -> Tuple[int, int]:
|
| 413 |
+
user = db_get_user(user_id)
|
| 414 |
+
if not user:
|
| 415 |
+
return 0, 0
|
| 416 |
+
message_text = (user[7] or "").strip()
|
| 417 |
+
if not message_text:
|
| 418 |
+
return 0, 0
|
| 419 |
+
|
| 420 |
+
groups = db_get_user_groups(user_id)
|
| 421 |
+
if not groups:
|
| 422 |
+
return 0, 0
|
| 423 |
+
|
| 424 |
+
client = await self._ensure_client(user_id)
|
| 425 |
+
if not client:
|
| 426 |
+
return 0, 0
|
| 427 |
+
|
| 428 |
+
sent = failed = 0
|
| 429 |
+
for gid, gtitle in groups:
|
| 430 |
+
try:
|
| 431 |
+
msg = await client.send_message(gid, message_text)
|
| 432 |
+
db_save_sent(user_id, gid, msg.id)
|
| 433 |
+
sent += 1
|
| 434 |
+
await asyncio.sleep(2.5)
|
| 435 |
+
except FloodWaitError as e:
|
| 436 |
+
wait = e.seconds + 2
|
| 437 |
+
logger.warning(f"FloodWait {wait}s for user {user_id}")
|
| 438 |
+
await asyncio.sleep(wait)
|
| 439 |
+
try:
|
| 440 |
+
msg = await client.send_message(gid, message_text)
|
| 441 |
+
db_save_sent(user_id, gid, msg.id)
|
| 442 |
+
sent += 1
|
| 443 |
+
except Exception as e2:
|
| 444 |
+
logger.error(f"Retry failed [{gid}]: {e2}")
|
| 445 |
+
failed += 1
|
| 446 |
+
except Exception as e:
|
| 447 |
+
logger.error(f"Send failed [{user_id} -> {gid}]: {e}")
|
| 448 |
+
failed += 1
|
| 449 |
+
|
| 450 |
+
logger.info(f"โ
User {user_id}: sent={sent}, failed={failed}")
|
| 451 |
+
return sent, failed
|
| 452 |
+
|
| 453 |
+
# โโ Public API โโ
|
| 454 |
+
def start_scheduling(self, user_id: int) -> Tuple[bool, str]:
|
| 455 |
+
with self._lock:
|
| 456 |
+
task = self.schedule_tasks.get(user_id)
|
| 457 |
+
if task and not task.done():
|
| 458 |
+
return False, "ุงูุฌุฏููุฉ ููุฏ ุงูุชุดุบูู ุจุงููุนู"
|
| 459 |
+
|
| 460 |
+
user = db_get_user(user_id)
|
| 461 |
+
if not user or not user[1]:
|
| 462 |
+
return False, "ูุฌุจ ุชุณุฌูู ุงูุฏุฎูู ุฃููุงู"
|
| 463 |
+
if not (user[7] or "").strip():
|
| 464 |
+
return False, "ูู
ุชุญุฏุฏ ูุต ุงูุฑุณุงูุฉ ุจุนุฏ"
|
| 465 |
+
if not db_get_user_groups(user_id):
|
| 466 |
+
return False, "ูู
ุชุฎุชุฑ ุฃู ู
ุฌู
ูุนุฉ"
|
| 467 |
+
|
| 468 |
+
future = asyncio.run_coroutine_threadsafe(self._scheduler_loop(user_id), self.loop)
|
| 469 |
+
with self._lock:
|
| 470 |
+
self.schedule_tasks[user_id] = future
|
| 471 |
+
db_set_scheduling(user_id, True)
|
| 472 |
+
return True, "โ
ุจุฏุฃ ุงูุฅุฑุณุงู ุงูุฏูุฑู"
|
| 473 |
+
|
| 474 |
+
def stop_scheduling(self, user_id: int) -> Tuple[bool, str]:
|
| 475 |
+
db_set_scheduling(user_id, False)
|
| 476 |
+
with self._lock:
|
| 477 |
+
task = self.schedule_tasks.pop(user_id, None)
|
| 478 |
+
if task and not task.done():
|
| 479 |
+
task.cancel()
|
| 480 |
+
return True, "โน๏ธ ุชู
ุฅููุงู ุงูุฅุฑุณุงู ุงูุฏูุฑู"
|
| 481 |
+
return False, "ุงูุฌุฏููุฉ ุบูุฑ ูุดุทุฉ"
|
| 482 |
+
|
| 483 |
+
def is_scheduling(self, user_id: int) -> bool:
|
| 484 |
+
with self._lock:
|
| 485 |
+
task = self.schedule_tasks.get(user_id)
|
| 486 |
+
return task is not None and not task.done()
|
| 487 |
+
|
| 488 |
+
async def _scheduler_loop(self, user_id: int):
|
| 489 |
+
try:
|
| 490 |
+
while True:
|
| 491 |
+
user = db_get_user(user_id)
|
| 492 |
+
if not user or user[5] == 0:
|
| 493 |
+
break
|
| 494 |
+
|
| 495 |
+
try:
|
| 496 |
+
await self._send_to_all_groups(user_id)
|
| 497 |
+
except Exception as e:
|
| 498 |
+
logger.error(f"Send cycle error [{user_id}]: {e}")
|
| 499 |
+
|
| 500 |
+
user = db_get_user(user_id)
|
| 501 |
+
if not user or user[5] == 0:
|
| 502 |
+
break
|
| 503 |
+
interval = int(user[6] or 60)
|
| 504 |
+
|
| 505 |
+
waited = 0
|
| 506 |
+
while waited < interval * 60:
|
| 507 |
+
await asyncio.sleep(min(30, interval * 60 - waited))
|
| 508 |
+
waited += 30
|
| 509 |
+
u = db_get_user(user_id)
|
| 510 |
+
if not u or u[5] == 0:
|
| 511 |
+
return
|
| 512 |
+
if int(u[6] or 60) != interval:
|
| 513 |
+
break
|
| 514 |
+
except asyncio.CancelledError:
|
| 515 |
+
logger.info(f"Scheduler cancelled for {user_id}")
|
| 516 |
+
except Exception as e:
|
| 517 |
+
logger.error(f"Scheduler crashed [{user_id}]: {e}\n{traceback.format_exc()}")
|
| 518 |
+
db_set_scheduling(user_id, False)
|
| 519 |
+
finally:
|
| 520 |
+
with self._lock:
|
| 521 |
+
self.schedule_tasks.pop(user_id, None)
|
| 522 |
+
|
| 523 |
+
def send_now(self, user_id: int) -> Tuple[bool, str]:
|
| 524 |
+
user = db_get_user(user_id)
|
| 525 |
+
if not user or not user[1]:
|
| 526 |
+
return False, "ูุฌุจ ุชุณุฌูู ุงูุฏุฎูู ุฃููุงู"
|
| 527 |
+
if not (user[7] or "").strip():
|
| 528 |
+
return False, "ูู
ุชุญุฏุฏ ูุต ุงูุฑุณุงูุฉ"
|
| 529 |
+
if not db_get_user_groups(user_id):
|
| 530 |
+
return False, "ูู
ุชุฎุชุฑ ุฃู ู
ุฌู
ูุนุฉ"
|
| 531 |
+
try:
|
| 532 |
+
fut = asyncio.run_coroutine_threadsafe(self._send_to_all_groups(user_id), self.loop)
|
| 533 |
+
sent, failed = fut.result(timeout=180)
|
| 534 |
+
return True, f"โ
ุชู
ุงูุฅุฑุณุงู:\nโข ูุฌุญ: {sent}\nโข ูุดู: {failed}"
|
| 535 |
+
except Exception as e:
|
| 536 |
+
return False, f"โ ุฎุทุฃ: {e}"
|
| 537 |
+
|
| 538 |
+
def resume_all(self):
|
| 539 |
+
for uid in db_all_active_users():
|
| 540 |
+
try:
|
| 541 |
+
asyncio.run_coroutine_threadsafe(self._ensure_client(uid), self.loop)
|
| 542 |
+
fut = asyncio.run_coroutine_threadsafe(self._scheduler_loop(uid), self.loop)
|
| 543 |
+
with self._lock:
|
| 544 |
+
self.schedule_tasks[uid] = fut
|
| 545 |
+
logger.info(f"โป๏ธ Resumed scheduler for {uid}")
|
| 546 |
+
except Exception as e:
|
| 547 |
+
logger.error(f"Resume failed [{uid}]: {e}")
|
| 548 |
+
|
| 549 |
+
|
| 550 |
+
session_manager = SessionManager()
|
| 551 |
+
|
| 552 |
+
# โโโโโโโโโโโโโโโโโโโโโโโ Bot helpers โโโโโโโโโโโโโโโโโโโโโโโ
|
| 553 |
+
def is_logged(user_id: int) -> bool:
|
| 554 |
+
u = db_get_user(user_id)
|
| 555 |
+
return bool(u and u[1])
|
| 556 |
+
|
| 557 |
+
|
| 558 |
+
def fmt_interval(m: int) -> str:
|
| 559 |
+
if m < 60:
|
| 560 |
+
return f"{m} ุฏูููุฉ"
|
| 561 |
+
if m == 60:
|
| 562 |
+
return "ุณุงุนุฉ"
|
| 563 |
+
if m < 1440:
|
| 564 |
+
h = m / 60
|
| 565 |
+
return f"{h:g} ุณุงุนุฉ"
|
| 566 |
+
d = m / 1440
|
| 567 |
+
return f"{d:g} ููู
"
|
| 568 |
+
|
| 569 |
+
|
| 570 |
+
# โโโโโโโโโโโโโโโโโโโโโโโ Main menu โโโโโโโโโโโโโโโโโโโโโโโ
|
| 571 |
+
def main_menu_kb(user_id: int) -> InlineKeyboardMarkup:
|
| 572 |
+
logged = is_logged(user_id)
|
| 573 |
+
rows = []
|
| 574 |
+
if not logged:
|
| 575 |
+
rows.append([InlineKeyboardButton("๐ ุชุณุฌูู ุงูุฏุฎูู", callback_data="menu_login")])
|
| 576 |
+
else:
|
| 577 |
+
rows.append([InlineKeyboardButton("๐ฅ ุงุฎุชูุงุฑ ุงูู
ุฌู
ูุนุงุช", callback_data="menu_groups")])
|
| 578 |
+
rows.append([InlineKeyboardButton("โ๏ธ ุงูุฅุนุฏุงุฏุงุช", callback_data="menu_settings")])
|
| 579 |
+
if session_manager.is_scheduling(user_id):
|
| 580 |
+
rows.append([InlineKeyboardButton("โน๏ธ ุฅููุงู ุงูุฅุฑุณุงู ุงูุฏูุฑู", callback_data="menu_stop")])
|
| 581 |
+
else:
|
| 582 |
+
rows.append([InlineKeyboardButton("โถ๏ธ ุจุฏุก ุงูุฅุฑุณุงู ุงูุฏูุฑู", callback_data="menu_start")])
|
| 583 |
+
rows.append([InlineKeyboardButton("๐ ุฅุฑุณุงู ุงูุขู ููู ุงูู
ุฌู
ูุนุงุช", callback_data="menu_send_now")])
|
| 584 |
+
rows.append([InlineKeyboardButton("๐ ุงูุญุงูุฉ", callback_data="menu_status")])
|
| 585 |
+
rows.append([InlineKeyboardButton("๐ช ุชุณุฌูู ุงูุฎุฑูุฌ", callback_data="menu_logout")])
|
| 586 |
+
return InlineKeyboardMarkup(rows)
|
| 587 |
+
|
| 588 |
+
|
| 589 |
+
def show_main_menu(update: Update, context: CallbackContext, edit: bool = True):
|
| 590 |
+
user = update.effective_user
|
| 591 |
+
user_id = user.id
|
| 592 |
+
logged = is_logged(user_id)
|
| 593 |
+
if logged:
|
| 594 |
+
u = db_get_user(user_id)
|
| 595 |
+
interval = fmt_interval(u[6] or 60)
|
| 596 |
+
status = "๐ข ูุนู
ู" if session_manager.is_scheduling(user_id) else "๐ด ู
ุชููู"
|
| 597 |
+
msg_preview = (u[7] or "").strip()[:60].replace("\n", " ") or "(ูู
ูุชู
ุงูุชุนููู)"
|
| 598 |
+
text = (
|
| 599 |
+
f"๐ ุฃููุงู <b>{user.first_name}</b>\n\n"
|
| 600 |
+
f"โ๏ธ <b>ุงูุฅุนุฏุงุฏุงุช ุงูุญุงููุฉ:</b>\n"
|
| 601 |
+
f"โข ุงููุงุตู ุงูุฒู
ูู: <b>{interval}</b>\n"
|
| 602 |
+
f"โข ุญุงูุฉ ุงูุฌุฏููุฉ: <b>{status}</b>\n"
|
| 603 |
+
f"โข ูุต ุงูุฑุณุงูุฉ: <i>{msg_preview}...</i>\n"
|
| 604 |
+
)
|
| 605 |
+
else:
|
| 606 |
+
text = (
|
| 607 |
+
f"๐ ุฃููุงู <b>{user.first_name}</b>\n\n"
|
| 608 |
+
f"ููุจุฏุกุ ุณุฌูู ุงูุฏุฎูู ุจููุฏ ุงูุฌูุณุฉ (StringSession)."
|
| 609 |
+
)
|
| 610 |
+
kb = main_menu_kb(user_id)
|
| 611 |
+
if edit and update.callback_query:
|
| 612 |
+
try:
|
| 613 |
+
update.callback_query.edit_message_text(text, parse_mode=ParseMode.HTML, reply_markup=kb)
|
| 614 |
+
except Exception:
|
| 615 |
+
pass
|
| 616 |
+
else:
|
| 617 |
+
update.message.reply_text(text, parse_mode=ParseMode.HTML, reply_markup=kb)
|
| 618 |
+
|
| 619 |
+
|
| 620 |
+
def cmd_start(update: Update, context: CallbackContext):
|
| 621 |
+
context.user_data.pop('state', None)
|
| 622 |
+
show_main_menu(update, context, edit=False)
|
| 623 |
+
|
| 624 |
+
|
| 625 |
+
def cmd_help(update: Update, context: CallbackContext):
|
| 626 |
+
update.message.reply_text(
|
| 627 |
+
"๐ <b>ุงูุฃูุงู
ุฑ ุงูู
ุชุงุญุฉ:</b>\n"
|
| 628 |
+
"/start - ุงููุงุฆู
ุฉ ุงูุฑุฆูุณูุฉ\n"
|
| 629 |
+
"/login - ุชุณุฌูู ุงูุฏุฎูู ุจููุฏ ุงูุฌูุณุฉ\n"
|
| 630 |
+
"/status - ุญุงูุฉ ุงูุญุณุงุจ\n"
|
| 631 |
+
"/ping - ูุญุต ุญุงูุฉ ุงูุจูุช\n"
|
| 632 |
+
"/cancel - ุฅูุบุงุก ุงูุนู
ููุฉ ุงูุญุงููุฉ",
|
| 633 |
+
parse_mode=ParseMode.HTML
|
| 634 |
+
)
|
| 635 |
+
|
| 636 |
+
|
| 637 |
+
# โโโโโโโโโโโโโโโโโโโโโโโ Menu callbacks โโโโโโโโโโโโโโโโโโโโโโโ
|
| 638 |
+
def menu_callback(update: Update, context: CallbackContext):
|
| 639 |
+
q = update.callback_query
|
| 640 |
+
q.answer()
|
| 641 |
+
data = q.data
|
| 642 |
+
user_id = update.effective_user.id
|
| 643 |
+
|
| 644 |
+
if data == "menu_login":
|
| 645 |
+
context.user_data['state'] = 'session'
|
| 646 |
+
q.edit_message_text(
|
| 647 |
+
"๐ <b>ุชุณุฌูู ุงูุฏุฎูู ุจููุฏ ุงูุฌูุณุฉ</b>\n\n"
|
| 648 |
+
"ุฃุฑุณู ููุฏ ุงูุฌูุณุฉ (StringSession) ุงูุฎุงุต ุจุญุณุงุจู.\n"
|
| 649 |
+
"ููุฅูุบุงุก ุฃุฑุณู /cancel",
|
| 650 |
+
parse_mode=ParseMode.HTML
|
| 651 |
+
)
|
| 652 |
+
return
|
| 653 |
+
|
| 654 |
+
if not is_logged(user_id):
|
| 655 |
+
q.answer("ูุฌุจ ุชุณุฌูู ุงูุฏุฎูู ุฃููุงู", show_alert=True)
|
| 656 |
+
return
|
| 657 |
+
|
| 658 |
+
if data == "menu_groups":
|
| 659 |
+
show_groups(update, context)
|
| 660 |
+
elif data == "menu_settings":
|
| 661 |
+
show_settings(update, context)
|
| 662 |
+
elif data == "menu_start":
|
| 663 |
+
ok, msg = session_manager.start_scheduling(user_id)
|
| 664 |
+
q.answer(msg, show_alert=True)
|
| 665 |
+
show_main_menu(update, context)
|
| 666 |
+
elif data == "menu_stop":
|
| 667 |
+
ok, msg = session_manager.stop_scheduling(user_id)
|
| 668 |
+
q.answer(msg, show_alert=True)
|
| 669 |
+
show_main_menu(update, context)
|
| 670 |
+
elif data == "menu_send_now":
|
| 671 |
+
q.edit_message_text("โณ ุฌุงุฑู ุฅุฑุณุงู ุงูุฑุณุงูุฉ ููู ุงูู
ุฌู
ูุนุงุช...")
|
| 672 |
+
ok, msg = session_manager.send_now(user_id)
|
| 673 |
+
q.edit_message_text(
|
| 674 |
+
msg,
|
| 675 |
+
parse_mode=ParseMode.HTML,
|
| 676 |
+
reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("๐ ุฑุฌูุน", callback_data="menu_back")]])
|
| 677 |
+
)
|
| 678 |
+
elif data == "menu_status":
|
| 679 |
+
show_status(update, context)
|
| 680 |
+
elif data == "menu_logout":
|
| 681 |
+
session_manager.stop_scheduling(user_id)
|
| 682 |
+
conn = _conn()
|
| 683 |
+
c = conn.cursor()
|
| 684 |
+
c.execute("UPDATE users SET session_string=NULL, scheduling_active=0 WHERE user_id=?", (user_id,))
|
| 685 |
+
conn.commit()
|
| 686 |
+
conn.close()
|
| 687 |
+
q.answer("ุชู
ุชุณุฌูู ุงูุฎุฑูุฌ", show_alert=True)
|
| 688 |
+
show_main_menu(update, context)
|
| 689 |
+
elif data == "menu_back":
|
| 690 |
+
show_main_menu(update, context)
|
| 691 |
+
|
| 692 |
+
|
| 693 |
+
# โโโโโโโโโโโโโโโโโโโโโโโ Login โโโโโโโโโโโโโโโโโโโโโโโ
|
| 694 |
+
def handle_session_input(update: Update, context: CallbackContext):
|
| 695 |
+
user_id = update.effective_user.id
|
| 696 |
+
session_string = update.message.text.strip()
|
| 697 |
+
msg = update.message.reply_text("โณ ุฌุงุฑู ุงูุชุญูู ู
ู ุงูุฌูุณุฉ...")
|
| 698 |
+
try:
|
| 699 |
+
ok, result = session_manager.validate_session(session_string)
|
| 700 |
+
except Exception as e:
|
| 701 |
+
ok, result = False, str(e)
|
| 702 |
+
try:
|
| 703 |
+
msg.delete()
|
| 704 |
+
except Exception:
|
| 705 |
+
pass
|
| 706 |
+
|
| 707 |
+
if ok:
|
| 708 |
+
db_save_session(user_id, session_string, result if isinstance(result, str) else "")
|
| 709 |
+
try:
|
| 710 |
+
asyncio.run_coroutine_threadsafe(session_manager._ensure_client(user_id), session_manager.loop)
|
| 711 |
+
except Exception as e:
|
| 712 |
+
logger.error(f"Failed to start client background: {e}")
|
| 713 |
+
update.message.reply_text("โ
<b>ุชู
ุชุณุฌูู ุงูุฏุฎูู ุจูุฌุงุญ!</b>", parse_mode=ParseMode.HTML)
|
| 714 |
+
else:
|
| 715 |
+
update.message.reply_text(f"โ ูุดู: {result}\n\nุญุงูู ู
ุฑุฉ ุฃุฎุฑู ุฃู ุฃุฑุณู /cancel.")
|
| 716 |
+
|
| 717 |
+
context.user_data.pop('state', None)
|
| 718 |
+
show_main_menu(update, context, edit=False)
|
| 719 |
+
|
| 720 |
+
|
| 721 |
+
# โโโโโโโโโโโโโโโโโโโโโโโ Groups โโโโโโโโโโโโโโโโโโโโโโโ
|
| 722 |
+
def show_groups(update: Update, context: CallbackContext, page: int = 0, refresh: bool = False):
|
| 723 |
+
q = update.callback_query
|
| 724 |
+
user_id = update.effective_user.id
|
| 725 |
+
user = db_get_user(user_id)
|
| 726 |
+
if not user or not user[1]:
|
| 727 |
+
q.edit_message_text("โ ุงูุฌูุณุฉ ุบูุฑ ุตุงูุญุฉ. ุงูุฑุฌุงุก ุชุณุฌูู ุงูุฏุฎูู.")
|
| 728 |
+
return
|
| 729 |
+
|
| 730 |
+
if refresh or 'groups_list' not in context.user_data:
|
| 731 |
+
q.edit_message_text("โณ ุฌุงุฑู ุฌูุจ ุงูู
ุฌู
ูุนุงุช ู
ู ุชูููุฌุฑุงู
...")
|
| 732 |
+
try:
|
| 733 |
+
groups = session_manager.fetch_groups(user[1])
|
| 734 |
+
except Exception as e:
|
| 735 |
+
q.edit_message_text(
|
| 736 |
+
f"โ ูุดู ุงูุฌูุจ:\n{e}",
|
| 737 |
+
reply_markup=InlineKeyboardMarkup([
|
| 738 |
+
[InlineKeyboardButton("๐ ุฅุนุงุฏุฉ ุงูู
ุญุงููุฉ", callback_data="grp_refresh")],
|
| 739 |
+
[InlineKeyboardButton("๐ ุฑุฌูุน", callback_data="menu_back")],
|
| 740 |
+
])
|
| 741 |
+
)
|
| 742 |
+
return
|
| 743 |
+
groups.sort(key=lambda x: x[1].lower())
|
| 744 |
+
context.user_data['groups_list'] = groups
|
| 745 |
+
context.user_data['temp_selected'] = {g[0] for g in db_get_user_groups(user_id)}
|
| 746 |
+
|
| 747 |
+
groups_list: List[Tuple[int, str]] = context.user_data['groups_list']
|
| 748 |
+
selected: set = context.user_data['temp_selected']
|
| 749 |
+
|
| 750 |
+
if not groups_list:
|
| 751 |
+
q.edit_message_text("โ ูุง ุชูุฌุฏ ู
ุฌู
ูุนุงุช.")
|
| 752 |
+
return
|
| 753 |
+
|
| 754 |
+
per_page = 8
|
| 755 |
+
total_pages = max(1, (len(groups_list) + per_page - 1) // per_page)
|
| 756 |
+
page = max(0, min(page, total_pages - 1))
|
| 757 |
+
start = page * per_page
|
| 758 |
+
end = start + per_page
|
| 759 |
+
|
| 760 |
+
rows = []
|
| 761 |
+
for gid, gtitle in groups_list[start:end]:
|
| 762 |
+
prefix = "โ
" if gid in selected else "โฌ๏ธ"
|
| 763 |
+
rows.append([InlineKeyboardButton(f"{prefix} {gtitle[:40]}", callback_data=f"tog_{gid}")])
|
| 764 |
+
|
| 765 |
+
nav = []
|
| 766 |
+
if page > 0:
|
| 767 |
+
nav.append(InlineKeyboardButton("โ๏ธ", callback_data=f"grp_page_{page-1}"))
|
| 768 |
+
nav.append(InlineKeyboardButton(f"{page+1}/{total_pages}", callback_data="noop"))
|
| 769 |
+
if page < total_pages - 1:
|
| 770 |
+
nav.append(InlineKeyboardButton("โถ๏ธ", callback_data=f"grp_page_{page+1}"))
|
| 771 |
+
if nav:
|
| 772 |
+
rows.append(nav)
|
| 773 |
+
|
| 774 |
+
rows.append([InlineKeyboardButton(f"๐พ ุญูุธ ({len(selected)} ู
ุฎุชุงุฑุฉ)", callback_data="grp_save")])
|
| 775 |
+
rows.append([InlineKeyboardButton("๐ ุชุญุฏูุซ", callback_data="grp_refresh")])
|
| 776 |
+
rows.append([InlineKeyboardButton("๐ ุฑุฌูุน", callback_data="menu_back")])
|
| 777 |
+
|
| 778 |
+
q.edit_message_text(
|
| 779 |
+
f"๐ <b>ุงุฎุชุฑ ุงูู
ุฌู
ูุนุงุช ููุฅุฑุณุงู</b>\n"
|
| 780 |
+
f"ุฅุฌู
ุงูู: {len(groups_list)} | ู
ุฎุชุงุฑ: {len(selected)}",
|
| 781 |
+
parse_mode=ParseMode.HTML,
|
| 782 |
+
reply_markup=InlineKeyboardMarkup(rows)
|
| 783 |
+
)
|
| 784 |
+
|
| 785 |
+
|
| 786 |
+
def groups_callback(update: Update, context: CallbackContext):
|
| 787 |
+
q = update.callback_query
|
| 788 |
+
data = q.data
|
| 789 |
+
user_id = update.effective_user.id
|
| 790 |
+
|
| 791 |
+
if data == "noop":
|
| 792 |
+
q.answer()
|
| 793 |
+
return
|
| 794 |
+
|
| 795 |
+
if data == "grp_refresh":
|
| 796 |
+
q.answer("ุฌุงุฑู ุงูุชุญุฏูุซ...")
|
| 797 |
+
show_groups(update, context, page=0, refresh=True)
|
| 798 |
+
return
|
| 799 |
+
|
| 800 |
+
if data == "grp_save":
|
| 801 |
+
groups_list = context.user_data.get('groups_list', [])
|
| 802 |
+
selected = context.user_data.get('temp_selected', set())
|
| 803 |
+
to_save = [(gid, t) for gid, t in groups_list if gid in selected]
|
| 804 |
+
db_save_user_groups(user_id, to_save)
|
| 805 |
+
context.user_data.pop('groups_list', None)
|
| 806 |
+
context.user_data.pop('temp_selected', None)
|
| 807 |
+
q.answer(f"ุชู
ุญูุธ {len(to_save)} ู
ุฌู
ูุนุฉ โ
", show_alert=True)
|
| 808 |
+
show_main_menu(update, context)
|
| 809 |
+
return
|
| 810 |
+
|
| 811 |
+
if data.startswith("grp_page_"):
|
| 812 |
+
page = int(data.split("_")[2])
|
| 813 |
+
q.answer()
|
| 814 |
+
show_groups(update, context, page=page)
|
| 815 |
+
return
|
| 816 |
+
|
| 817 |
+
if data.startswith("tog_"):
|
| 818 |
+
try:
|
| 819 |
+
gid = int(data.split("_", 1)[1])
|
| 820 |
+
except ValueError:
|
| 821 |
+
q.answer()
|
| 822 |
+
return
|
| 823 |
+
selected: set = context.user_data.get('temp_selected', set())
|
| 824 |
+
if gid in selected:
|
| 825 |
+
selected.discard(gid)
|
| 826 |
+
else:
|
| 827 |
+
selected.add(gid)
|
| 828 |
+
context.user_data['temp_selected'] = selected
|
| 829 |
+
page = 0
|
| 830 |
+
try:
|
| 831 |
+
import re as _re
|
| 832 |
+
m = _re.search(r'(\d+)/(\d+)', q.message.text or "")
|
| 833 |
+
if m:
|
| 834 |
+
page = int(m.group(1)) - 1
|
| 835 |
+
except Exception:
|
| 836 |
+
pass
|
| 837 |
+
q.answer()
|
| 838 |
+
show_groups(update, context, page=page)
|
| 839 |
+
|
| 840 |
+
|
| 841 |
+
# โโโโโโโโโโโโโโโโโโโโโโโ Settings โโโโโโโโโโโโโโโโโโโโโโโ
|
| 842 |
+
def show_settings(update: Update, context: CallbackContext):
|
| 843 |
+
q = update.callback_query
|
| 844 |
+
user_id = update.effective_user.id
|
| 845 |
+
u = db_get_user(user_id)
|
| 846 |
+
interval = fmt_interval(u[6] or 60)
|
| 847 |
+
msg_text = (u[7] or "").strip()
|
| 848 |
+
preview = msg_text[:80].replace("\n", " ") + ("..." if len(msg_text) > 80 else "")
|
| 849 |
+
if not preview:
|
| 850 |
+
preview = "(ูู
ูุชู
ุงูุชุนููู)"
|
| 851 |
+
target = "๐ฑ ุญุณุงุจู ุงูุฎุงุต" if u[3] == "private" else f"๐ข {u[4] or 'ุบูุฑ ู
ุญุฏุฏ'}"
|
| 852 |
+
|
| 853 |
+
text = (
|
| 854 |
+
f"โ๏ธ <b>ุงูุฅุนุฏุงุฏุงุช</b>\n"
|
| 855 |
+
f"โโโโโโโโโโโโโโโโโโโโโ\n"
|
| 856 |
+
f"โฑ๏ธ ุงููุงุตู ุงูุฒู
ูู: <b>{interval}</b>\n"
|
| 857 |
+
f"๐ข ูุฌูุฉ ุงูุชูุจููุงุช: <b>{target}</b>\n"
|
| 858 |
+
f"โโโโโโโโโโโโโโโโโโโโโ\n"
|
| 859 |
+
f"๐ <b>ูุต ุงูุฑุณุงูุฉ:</b>\n<i>{preview}</i>"
|
| 860 |
+
)
|
| 861 |
+
kb = InlineKeyboardMarkup([
|
| 862 |
+
[InlineKeyboardButton("โฑ๏ธ ุชุบููุฑ ุงููุงุตู ุงูุฒู
ูู", callback_data="set_interval_menu")],
|
| 863 |
+
[InlineKeyboardButton("๐ ุชุนุฏูู ูุต ุงูุฑุณุงูุฉ", callback_data="set_message")],
|
| 864 |
+
[InlineKeyboardButton("๐ข ูุฌูุฉ ุงูุชูุจููุงุช", callback_data="set_alert_menu")],
|
| 865 |
+
[InlineKeyboardButton("๐ ุฑุฌูุน", callback_data="menu_back")],
|
| 866 |
+
])
|
| 867 |
+
q.edit_message_text(text, parse_mode=ParseMode.HTML, reply_markup=kb)
|
| 868 |
+
|
| 869 |
+
|
| 870 |
+
def settings_callback(update: Update, context: CallbackContext):
|
| 871 |
+
q = update.callback_query
|
| 872 |
+
user_id = update.effective_user.id
|
| 873 |
+
data = q.data
|
| 874 |
+
|
| 875 |
+
if data == "set_interval_menu":
|
| 876 |
+
rows = []
|
| 877 |
+
row = []
|
| 878 |
+
for i, m in enumerate(INTERVAL_OPTIONS):
|
| 879 |
+
row.append(InlineKeyboardButton(fmt_interval(m), callback_data=f"set_int_{m}"))
|
| 880 |
+
if len(row) == 3:
|
| 881 |
+
rows.append(row)
|
| 882 |
+
row = []
|
| 883 |
+
if row:
|
| 884 |
+
rows.append(row)
|
| 885 |
+
rows.append([InlineKeyboardButton("โ๏ธ ู
ุฎุตุต (ุจุงูุฏูุงุฆู)", callback_data="set_int_custom")])
|
| 886 |
+
rows.append([InlineKeyboardButton("๐ ุฑุฌูุน", callback_data="menu_settings")])
|
| 887 |
+
q.edit_message_text(
|
| 888 |
+
"โฑ๏ธ ุงุฎุชุฑ ุงููุงุตู ุงูุฒู
ูู ุจูู ูู ุฅุฑุณุงู ูุขุฎุฑ:",
|
| 889 |
+
reply_markup=InlineKeyboardMarkup(rows)
|
| 890 |
+
)
|
| 891 |
+
elif data.startswith("set_int_"):
|
| 892 |
+
val = data.split("_")[2]
|
| 893 |
+
if val == "custom":
|
| 894 |
+
context.user_data['state'] = 'custom_interval'
|
| 895 |
+
q.edit_message_text("โ๏ธ ุฃุฑุณู ุงููุงุตู ุงูุฒู
ูู ุจุงูุฏูุงุฆู (ุฑูู
ุจูู 1 ู 10080):")
|
| 896 |
+
else:
|
| 897 |
+
m = int(val)
|
| 898 |
+
db_update_interval(user_id, m)
|
| 899 |
+
q.answer(f"โ
ุชู
ุงูุชุนููู: {fmt_interval(m)}", show_alert=True)
|
| 900 |
+
show_settings(update, context)
|
| 901 |
+
elif data == "set_message":
|
| 902 |
+
context.user_data['state'] = 'message'
|
| 903 |
+
u = db_get_user(user_id)
|
| 904 |
+
current = (u[7] or "").strip() or "(ูุงุฑุบุฉ)"
|
| 905 |
+
q.edit_message_text(
|
| 906 |
+
f"๐ <b>ุชุนุฏูู ูุต ุงูุฑุณุงูุฉ</b>\n\n"
|
| 907 |
+
f"<b>ุงููุต ุงูุญุงูู:</b>\n<i>{current[:500]}</i>\n\n"
|
| 908 |
+
f"ุฃุฑุณู ุงููุต ุงูุฌุฏูุฏ ุงูุขู (ูุฏุนู
ุฃุณุทุฑ ู
ุชุนุฏุฏุฉ).",
|
| 909 |
+
parse_mode=ParseMode.HTML
|
| 910 |
+
)
|
| 911 |
+
elif data == "set_alert_menu":
|
| 912 |
+
kb = InlineKeyboardMarkup([
|
| 913 |
+
[InlineKeyboardButton("๐ฑ ุญุณุงุจู ุงูุฎุงุต", callback_data="set_alert_private")],
|
| 914 |
+
[InlineKeyboardButton("๐ข ููุงุฉ/ู
ุฌู
ูุนุฉ (ID ุฃู @username)", callback_data="set_alert_channel")],
|
| 915 |
+
[InlineKeyboardButton("๐ ุฑุฌูุน", callback_data="menu_settings")],
|
| 916 |
+
])
|
| 917 |
+
q.edit_message_text("๐ข ุงุฎุชุฑ ูุฌูุฉ ุฅุดุนุงุฑุงุช ุงูุฑุฏูุฏ:", reply_markup=kb)
|
| 918 |
+
elif data == "set_alert_private":
|
| 919 |
+
db_update_alert(user_id, "private", "")
|
| 920 |
+
q.answer("โ
ุชู
ุงูุชุนููู ุฅูู ุญุณุงุจู ุงูุฎุงุต", show_alert=True)
|
| 921 |
+
show_settings(update, context)
|
| 922 |
+
elif data == "set_alert_channel":
|
| 923 |
+
context.user_data['state'] = 'channel'
|
| 924 |
+
q.edit_message_text(
|
| 925 |
+
"๐ข ุฃุฑุณู ู
ุนุฑู ุงูููุงุฉ/ุงูู
ุฌู
ูุนุฉ:\n"
|
| 926 |
+
"โข ูู
ููู ุฅุฑุณุงู <code>@username</code>\n"
|
| 927 |
+
"โข ุฃู ุงูู
ุนุฑู ุงูุฑูู
ู ู
ุซู <code>-1001234567890</code>\n\n"
|
| 928 |
+
"โ ๏ธ ุชุฃูุฏ ู
ู ุฃู ุงูุจูุช ู
ุดุฑู ูู ุงูููุงุฉ.",
|
| 929 |
+
parse_mode=ParseMode.HTML
|
| 930 |
+
)
|
| 931 |
+
|
| 932 |
+
|
| 933 |
+
# โโโโโโโโโโโโโโโโโโโโโโโ Status โโโโโโโโโโโโโโโโโโโโโโโ
|
| 934 |
+
def show_status(update: Update, context: CallbackContext):
|
| 935 |
+
q = update.callback_query
|
| 936 |
+
user_id = update.effective_user.id
|
| 937 |
+
u = db_get_user(user_id)
|
| 938 |
+
if not u:
|
| 939 |
+
q.edit_message_text("ูุง ุชูุฌุฏ ุจูุงูุงุช.")
|
| 940 |
+
return
|
| 941 |
+
groups = db_get_user_groups(user_id)
|
| 942 |
+
interval = fmt_interval(u[6] or 60)
|
| 943 |
+
sched = "๐ข ูุนู
ู" if session_manager.is_scheduling(user_id) else "๐ด ู
ุชููู"
|
| 944 |
+
client_ok = session_manager.clients.get(user_id)
|
| 945 |
+
client_status = "๐ข ู
ุชุตู" if (client_ok and client_ok.is_connected()) else "๐ด ุบูุฑ ู
ุชุตู"
|
| 946 |
+
target = "๐ฑ ุญุณุงุจู" if u[3] == "private" else f"๐ข {u[4] or 'โ'}"
|
| 947 |
+
|
| 948 |
+
msg_text = (u[7] or "").strip()
|
| 949 |
+
preview = msg_text[:120].replace("\n", " ") + ("..." if len(msg_text) > 120 else "")
|
| 950 |
+
if not preview:
|
| 951 |
+
preview = "(ูู
ูุชู
ุงูุชุนููู)"
|
| 952 |
+
|
| 953 |
+
text = (
|
| 954 |
+
f"๐ <b>ุญุงูุฉ ุงูุญุณุงุจ</b>\n"
|
| 955 |
+
f"โโโโโโโโโโโโโโโโโโโโโ\n"
|
| 956 |
+
f"๐ค ุงูู
ุณุชุฎุฏู
: <code>{user_id}</code>\n"
|
| 957 |
+
f"๐ ุงููุงุชู: <code>{u[2] or 'โ'}</code>\n"
|
| 958 |
+
f"๐ ุงูุงุชุตุงู: {client_status}\n"
|
| 959 |
+
f"โถ๏ธ ุงูุฌุฏููุฉ: {sched}\n"
|
| 960 |
+
f"โฑ๏ธ ุงููุงุตู: <b>{interval}</b>\n"
|
| 961 |
+
f"๐ฅ ุงูู
ุฌู
ูุนุงุช: <b>{len(groups)}</b>\n"
|
| 962 |
+
f"๐ข ูุฌูุฉ ุงูุชูุจููุงุช: {target}\n"
|
| 963 |
+
f"โโโโโโโโโโโโโโโโโโโโโ\n"
|
| 964 |
+
f"๐ <b>ูุต ุงูุฑุณุงูุฉ:</b>\n<i>{preview}</i>"
|
| 965 |
+
)
|
| 966 |
+
q.edit_message_text(
|
| 967 |
+
text,
|
| 968 |
+
parse_mode=ParseMode.HTML,
|
| 969 |
+
reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("๐ ุฑุฌูุน", callback_data="menu_back")]])
|
| 970 |
+
)
|
| 971 |
+
|
| 972 |
+
|
| 973 |
+
# โโโโโโโโโโโโโโโโโโโโโโโ Text router โโโโโโโโโโโโโโโโโโโโโโโ
|
| 974 |
+
def text_router(update: Update, context: CallbackContext):
|
| 975 |
+
state = context.user_data.get('state')
|
| 976 |
+
if not state:
|
| 977 |
+
return
|
| 978 |
+
user_id = update.effective_user.id
|
| 979 |
+
text = update.message.text
|
| 980 |
+
|
| 981 |
+
if state == 'session':
|
| 982 |
+
handle_session_input(update, context)
|
| 983 |
+
|
| 984 |
+
elif state == 'message':
|
| 985 |
+
if len(text) > 4000:
|
| 986 |
+
update.message.reply_text("โ ุงููุต ุทููู ุฌุฏุงู (ุงูุญุฏ 4000 ุญุฑู).")
|
| 987 |
+
return
|
| 988 |
+
db_update_message(user_id, text)
|
| 989 |
+
context.user_data.pop('state', None)
|
| 990 |
+
update.message.reply_text(f"โ
ุชู
ุญูุธ ูุต ุงูุฑุณุงูุฉ ({len(text)} ุญุฑู).")
|
| 991 |
+
show_main_menu(update, context, edit=False)
|
| 992 |
+
|
| 993 |
+
elif state == 'custom_interval':
|
| 994 |
+
try:
|
| 995 |
+
n = int(text.strip())
|
| 996 |
+
if n < 1 or n > 10080:
|
| 997 |
+
raise ValueError
|
| 998 |
+
except ValueError:
|
| 999 |
+
update.message.reply_text("โ ุฃุฏุฎู ุฑูู
ุงู ุตุญูุญุงู ุจูู 1 ู 10080.")
|
| 1000 |
+
return
|
| 1001 |
+
db_update_interval(user_id, n)
|
| 1002 |
+
context.user_data.pop('state', None)
|
| 1003 |
+
update.message.reply_text(f"โ
ุชู
ุชุนููู ุงููุงุตู: {fmt_interval(n)}")
|
| 1004 |
+
|
| 1005 |
+
elif state == 'channel':
|
| 1006 |
+
target = text.strip()
|
| 1007 |
+
if not target:
|
| 1008 |
+
update.message.reply_text("โ ุฃุฏุฎู ู
ุนุฑูุงู ุตุงูุญุงู.")
|
| 1009 |
+
return
|
| 1010 |
+
db_update_alert(user_id, "channel", target)
|
| 1011 |
+
context.user_data.pop('state', None)
|
| 1012 |
+
update.message.reply_text(f"โ
ุชู
ุญูุธ ูุฌูุฉ ุงูุชูุจููุงุช: <code>{target}</code>", parse_mode=ParseMode.HTML)
|
| 1013 |
+
|
| 1014 |
+
|
| 1015 |
+
def cmd_cancel(update: Update, context: CallbackContext):
|
| 1016 |
+
context.user_data.pop('state', None)
|
| 1017 |
+
update.message.reply_text("โ ุชู
ุงูุฅูุบุงุก.")
|
| 1018 |
+
show_main_menu(update, context, edit=False)
|
| 1019 |
+
|
| 1020 |
+
|
| 1021 |
+
def cmd_ping(update: Update, context: CallbackContext):
|
| 1022 |
+
update.message.reply_text("๐ข ุงูุจูุช ูุนู
ู.")
|
| 1023 |
+
|
| 1024 |
+
|
| 1025 |
+
def cmd_status(update: Update, context: CallbackContext):
|
| 1026 |
+
user_id = update.effective_user.id
|
| 1027 |
+
u = db_get_user(user_id)
|
| 1028 |
+
if not u:
|
| 1029 |
+
update.message.reply_text("โ ูู
ุชุณุฌู ุงูุฏุฎูู.")
|
| 1030 |
+
return
|
| 1031 |
+
groups = db_get_user_groups(user_id)
|
| 1032 |
+
sched = "๐ข ูุนู
ู" if session_manager.is_scheduling(user_id) else "๐ด ู
ุชููู"
|
| 1033 |
+
update.message.reply_text(
|
| 1034 |
+
f"๐ <b>ุงูุญุงูุฉ</b>\n"
|
| 1035 |
+
f"โถ๏ธ ุงูุฌุฏููุฉ: {sched}\n"
|
| 1036 |
+
f"โฑ๏ธ ุงููุงุตู: {fmt_interval(u[6] or 60)}\n"
|
| 1037 |
+
f"๐ฅ ุงูู
ุฌู
ูุนุงุช: {len(groups)}",
|
| 1038 |
+
parse_mode=ParseMode.HTML
|
| 1039 |
+
)
|
| 1040 |
+
|
| 1041 |
+
|
| 1042 |
+
def cmd_login(update: Update, context: CallbackContext):
|
| 1043 |
+
context.user_data['state'] = 'session'
|
| 1044 |
+
update.message.reply_text(
|
| 1045 |
+
"๐ <b>ุชุณุฌูู ุงูุฏุฎูู</b>\n\nุฃุฑุณู ููุฏ ุงูุฌูุณุฉ (StringSession):",
|
| 1046 |
+
parse_mode=ParseMode.HTML
|
| 1047 |
+
)
|
| 1048 |
+
|
| 1049 |
+
|
| 1050 |
+
# โโโโโโโโโโโโโโโโโโโโโโโ Cleanup loop โโโโโโโโโโโโโโโโโโโโโโโ
|
| 1051 |
+
def start_cleanup_loop():
|
| 1052 |
+
async def _loop():
|
| 1053 |
+
while True:
|
| 1054 |
+
try:
|
| 1055 |
+
db_cleanup_old_sent(14)
|
| 1056 |
+
except Exception as e:
|
| 1057 |
+
logger.error(f"Cleanup error: {e}")
|
| 1058 |
+
await asyncio.sleep(6 * 3600)
|
| 1059 |
+
asyncio.run_coroutine_threadsafe(_loop(), session_manager.loop)
|
| 1060 |
+
|
| 1061 |
+
|
| 1062 |
+
# โโโโโโโโโโโโโโโโโโโโโโโ Run bot in background โโโโโโโโโโโโโโโโโโโโโโโ
|
| 1063 |
+
def run_bot_in_background():
|
| 1064 |
+
"""ุชุดุบูู ุจูุช ุชูููุฌุฑุงู
ูู ุฎูุท ู
ููุตู."""
|
| 1065 |
+
if not BOT_TOKEN or not API_ID or not API_HASH:
|
| 1066 |
+
logger.error("โ Missing env vars: TELEGRAM_BOT_TOKEN / TELEGRAM_API_ID / TELEGRAM_API_HASH")
|
| 1067 |
+
return
|
| 1068 |
+
|
| 1069 |
+
session_manager.start_loop()
|
| 1070 |
+
|
| 1071 |
+
updater = Updater(BOT_TOKEN, use_context=True)
|
| 1072 |
+
dp = updater.dispatcher
|
| 1073 |
+
session_manager.set_bot(updater.bot)
|
| 1074 |
+
|
| 1075 |
+
# Handlers
|
| 1076 |
+
dp.add_handler(CommandHandler("start", cmd_start))
|
| 1077 |
+
dp.add_handler(CommandHandler("help", cmd_help))
|
| 1078 |
+
dp.add_handler(CommandHandler("cancel", cmd_cancel))
|
| 1079 |
+
dp.add_handler(CommandHandler("ping", cmd_ping))
|
| 1080 |
+
dp.add_handler(CommandHandler("status", cmd_status))
|
| 1081 |
+
dp.add_handler(CommandHandler("login", cmd_login))
|
| 1082 |
+
|
| 1083 |
+
dp.add_handler(CallbackQueryHandler(menu_callback, pattern=r'^menu_'))
|
| 1084 |
+
dp.add_handler(CallbackQueryHandler(groups_callback, pattern=r'^(tog_|grp_|noop)'))
|
| 1085 |
+
dp.add_handler(CallbackQueryHandler(settings_callback, pattern=r'^set_'))
|
| 1086 |
+
|
| 1087 |
+
dp.add_handler(MessageHandler(Filters.text & ~Filters.command, text_router))
|
| 1088 |
+
|
| 1089 |
+
session_manager.resume_all()
|
| 1090 |
+
start_cleanup_loop()
|
| 1091 |
+
|
| 1092 |
+
logger.info("๐ค Bot starting in background thread...")
|
| 1093 |
+
updater.start_polling()
|
| 1094 |
+
logger.info("โ
Bot polling started.")
|
| 1095 |
+
updater.idle()
|
| 1096 |
+
|
| 1097 |
+
|
| 1098 |
+
# โโโโโโโโโโโโโโโโโโโโโโโ Gradio UI โโโโโโโโโโโโโโโโโโโโโโโ
|
| 1099 |
+
def gradio_status():
|
| 1100 |
+
"""ุนุฑุถ ุญุงูุฉ ุงูุจูุช ุนูู ุตูุญุฉ Gradio."""
|
| 1101 |
+
try:
|
| 1102 |
+
active_users = len(db_all_active_users())
|
| 1103 |
+
clients = len(session_manager.clients)
|
| 1104 |
+
schedules = len(session_manager.schedule_tasks)
|
| 1105 |
+
return (
|
| 1106 |
+
f"๐ค ุงูุจูุช ูุนู
ู ุจูุฌุงุญ!\n"
|
| 1107 |
+
f"โโโโโโโโโโโโโโโโโโโโโโ\n"
|
| 1108 |
+
f"๐ฅ ุงูู
ุณุชุฎุฏู
ูู ุงููุดุทูู: {active_users}\n"
|
| 1109 |
+
f"๐ ุนู
ูุงุก Telethon ุงูู
ุชุตููู: {clients}\n"
|
| 1110 |
+
f"โฑ๏ธ ุงูุฌุฏุงูู ุงููุดุทุฉ: {schedules}\n"
|
| 1111 |
+
f"โโโโโโโโโโโโโโโโโโโโโโ\n"
|
| 1112 |
+
f"ุงูุชุญ ุงูุจูุช ุนูู ุชูููุฌุฑุงู
ูุฃุฑุณู /start ููุจุฏุก."
|
| 1113 |
+
)
|
| 1114 |
+
except Exception as e:
|
| 1115 |
+
return f"โ ๏ธ ุญุงูุฉ ุบูุฑ ู
ุนุฑููุฉ: {e}"
|
| 1116 |
+
|
| 1117 |
+
|
| 1118 |
+
def build_gradio_ui():
|
| 1119 |
+
with gr.Blocks(title="Telegram Auto Sender Bot", theme=gr.themes.Soft()) as demo:
|
| 1120 |
+
gr.Markdown(
|
| 1121 |
+
"""
|
| 1122 |
+
# ๐ค Telegram Auto Sender Bot
|
| 1123 |
+
### ุงูุจูุช ูุนู
ู ูู ุงูุฎูููุฉ ุนูู ูุฐุง ุงูู Space
|
| 1124 |
+
ูุฐู ุงูุตูุญุฉ ููุท ููุชุฃูุฏ ู
ู ุฃู ุงูู Space ูุดุท. **ูุง ุชุบูู** ูุฐู ุงูุตูุญุฉ.
|
| 1125 |
+
ุงูุชุญ ุงูุจูุช ุนูู ุชูููุฌุฑุงู
ูุฃุฑุณู `/start` ููุจุฏุก.
|
| 1126 |
+
"""
|
| 1127 |
+
)
|
| 1128 |
+
with gr.Row():
|
| 1129 |
+
status_btn = gr.Button("๐ ุชุญุฏูุซ ุงูุญุงูุฉ", variant="primary")
|
| 1130 |
+
status_out = gr.Textbox(label="ุญุงูุฉ ุงูุจูุช", lines=8, interactive=False)
|
| 1131 |
+
status_btn.click(fn=gradio_status, inputs=[], outputs=status_out)
|
| 1132 |
+
demo.load(fn=gradio_status, inputs=[], outputs=status_out)
|
| 1133 |
+
gr.Markdown(
|
| 1134 |
+
"""
|
| 1135 |
+
---
|
| 1136 |
+
### ๐ ุฎุทูุงุช ุงูุงุณุชุฎุฏุงู
|
| 1137 |
+
1. ุงูุชุญ ุงูุจูุช ุนูู ุชูููุฌุฑุงู
ูุฃุฑุณู `/start`
|
| 1138 |
+
2. ุงุถุบุท **๐ ุชุณุฌูู ุงูุฏุฎูู** ูุฃุฑุณู ููุฏ ุงูุฌูุณุฉ (StringSession)
|
| 1139 |
+
3. ุงุฎุชุฑ ุงูู
ุฌู
ูุนุงุช ู
ู **๐ฅ ุงุฎุชูุงุฑ ุงูู
ุฌู
ูุนุงุช**
|
| 1140 |
+
4. ุนุฏูู ุงูุฑุณุงูุฉ ูุงููุงุตู ู
ู **โ๏ธ ุงูุฅุนุฏุงุฏุงุช**
|
| 1141 |
+
5. ุงุจุฏุฃ ุงูุฅุฑุณุงู ุงูุฏูุฑู ุจู **โถ๏ธ ุจุฏุก ุงูุฅุฑุณุงู ุงูุฏูุฑู**
|
| 1142 |
+
6. ููุฅุฑุณุงู ุงูููุฑู ุงุถุบุท **๐ ุฅุฑุณุงู ุงูุขู**
|
| 1143 |
+
"""
|
| 1144 |
+
)
|
| 1145 |
+
return demo
|
| 1146 |
+
|
| 1147 |
+
|
| 1148 |
+
# โโโโโโโโโโโโโโโโโโโโโโโ Main โโโโโโโโโโโโโโโโโโโโโโโ
|
| 1149 |
+
if __name__ == "__main__":
|
| 1150 |
+
# 1. ุดุบูู ุงูุจูุช ูู ุฎูุท ู
ููุตู
|
| 1151 |
+
bot_thread = threading.Thread(target=run_bot_in_background, daemon=True, name="bot-thread")
|
| 1152 |
+
bot_thread.start()
|
| 1153 |
+
|
| 1154 |
+
# 2. ุฃุทูู ูุงุฌูุฉ Gradio
|
| 1155 |
+
logger.info("๐ Starting Gradio interface on 0.0.0.0:7860")
|
| 1156 |
+
demo = build_gradio_ui()
|
| 1157 |
+
demo.queue().launch(
|
| 1158 |
+
server_name="0.0.0.0",
|
| 1159 |
+
server_port=7860,
|
| 1160 |
+
show_error=True,
|
| 1161 |
+
quiet=False
|
| 1162 |
+
)
|