Anoar2025 commited on
Commit
b7a406c
ยท
verified ยท
1 Parent(s): 2265302

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +1162 -0
app.py ADDED
@@ -0,0 +1,1162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ )