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