Spaces:
Running
Running
File size: 38,972 Bytes
cfd7b39 c448d07 cfd7b39 |
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 |
# import filesystem
import json
import time
import threading
import logging
import telebot
import os
from fastapi import FastAPI
import fs
from fs import path
# filesystem = fs.open_fs("mem://") # Use "mem://" for in-memory
# # ------------------------------------------------------------------------------
# # Directories and File Paths
# # ------------------------------------------------------------------------------
# BOT_INFO_DIR = "bot_info"
# CHAT_LOGS_DIR = path.join(BOT_INFO_DIR, "chat_logs")
# SUBSCRIBERS_FILE = path.join(BOT_INFO_DIR, "subscribers.json")
# UNSUBSCRIBE_REQUESTS_FILE = path.join(BOT_INFO_DIR, "request_unsubscribe.json")
# LOG_FILE = path.join(BOT_INFO_DIR, "bot.log")
# # Create required directories if not present.
# for directory in [BOT_INFO_DIR, CHAT_LOGS_DIR]:
# if not filesystem.exists(directory):
# try:
# filesystem.makedirs(directory)
# print(f"Created directory: {directory}")
# except Exception as e:
# print(f"Error creating directory {directory}: {e}")
from fs import open_fs # pip install fs
from fs.errors import ResourceError
import json
# -------------------------------------------------------------------
# Pick the filesystem you want to use.
# • "mem://" → in‑memory (discarded when the process exits)
# • "osfs://." → the real working‑directory on disk
# • "zip://bot_bundle.zip" → a zip file you can ship around
# -------------------------------------------------------------------
filesystem = open_fs("mem://") # ⭐ change me if you want another backend
# Logical paths inside that filesystem
BOT_INFO_DIR = "bot_info"
CHAT_LOGS_DIR = f"{BOT_INFO_DIR}/chat_logs"
SUBSCRIBERS_FILE = f"{BOT_INFO_DIR}/subscribers.json"
UNSUBSCRIBE_REQUESTS_FILE = f"{BOT_INFO_DIR}/request_unsubscribe.json"
LOG_FILE = f"{BOT_INFO_DIR}/bot.log"
# -------------------------------------------------------------------
# Create the directory tree (recreate=True ⇒ no error if it exists)
# -------------------------------------------------------------------
filesystem.makedirs(CHAT_LOGS_DIR, recreate=True)
# -------------------------------------------------------------------
# Touch the files if they don’t exist yet
# (You can skip this if you plan to open() them in 'a' or 'w' mode later)
# -------------------------------------------------------------------
for path, initial in [
(SUBSCRIBERS_FILE, []), # start with an empty dict
(UNSUBSCRIBE_REQUESTS_FILE, []), # start with an empty list
(LOG_FILE, ""), # plain‑text log
]:
if not filesystem.exists(path):
with filesystem.open(path, "w") as fh:
# Serialise JSON files, or just write a blank string for the log
if path.endswith(".json"):
json.dump(initial, fh, indent=2)
else:
fh.write(str(initial))
print("Filesystem contents:")
print(filesystem.tree()) # pretty‑print the virtual tree
# ------------------------------------------------------------------------------
# Logging Configuration: Console and File Logging
# ------------------------------------------------------------------------------
# logging.basicConfig(
# level=logging.DEBUG,
# format='%(asctime)s [%(levelname)s] %(message)s',
# datefmt='%Y-%m-%d %H:%M:%S'
# )
# try:
# file_handler = logging.FileHandler(LOG_FILE)
# file_handler.setLevel(logging.DEBUG)
# formatter = logging.Formatter('%(asctime)s [%(levelname)s] %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
# file_handler.setFormatter(formatter)
# logging.getLogger().addHandler(file_handler)
# except Exception as e:
# logging.error(f"Error setting up file logging: {e}")
# ----------------------------------------------------------------------
# Logging Configuration → Smart Auto-Switching Handler (mem:// realtime)
# ----------------------------------------------------------------------
import logging
import time
from collections import deque
from fs import path as fspath
class SmartFSLogHandler(logging.Handler):
"""
Logs to a PyFilesystem file (e.g., mem:// or osfs).
Automatically switches between open-per-record and keep-open mode
based on log frequency (adaptive throttling).
"""
def __init__(self, fs, file_path, rate_window=5, rate_threshold=10):
super().__init__()
self.fs = fs
self.file_path = file_path
self._timestamps = deque(maxlen=rate_window * rate_threshold * 2)
self._fh = None
self.rate_window = rate_window
self.rate_threshold = rate_threshold
self._last_check = 0
parent = fspath.dirname(file_path)
fs.makedirs(parent, recreate=True)
def emit(self, record):
try:
msg = self.format(record) + "\n"
now = time.time()
self._timestamps.append(now)
# Every second, re-evaluate mode
if now - self._last_check > 1:
self._adjust_mode()
self._last_check = now
if self._fh:
self._fh.write(msg)
self._fh.flush()
else:
with self.fs.open(self.file_path, "a") as fh:
fh.write(msg)
except Exception:
self.handleError(record)
def _adjust_mode(self):
now = time.time()
recent = [ts for ts in self._timestamps if now - ts <= self.rate_window]
rate = len(recent) / self.rate_window
if rate >= self.rate_threshold and self._fh is None:
self._fh = self.fs.open(self.file_path, "a")
elif rate < self.rate_threshold and self._fh:
self._fh.close()
self._fh = None
def close(self):
if self._fh:
try:
self._fh.close()
finally:
self._fh = None
super().close()
# ─── Apply smart log handler ─────────────────────────────────────────
log_format = "%(asctime)s [%(levelname)s] %(message)s"
log_datefmt = "%Y-%m-%d %H:%M:%S"
logging.basicConfig(
level=logging.DEBUG,
format=log_format,
datefmt=log_datefmt,
handlers=[
SmartFSLogHandler(filesystem, LOG_FILE, rate_window=5, rate_threshold=10),
logging.StreamHandler() # Console output (optional)
],
)
# ------------------------------------------------------------------------------
# Bot Initialization and Owner Configuration
# ------------------------------------------------------------------------------
TOKEN = os.environ["BOT_TOKEN"]
bot = telebot.TeleBot(TOKEN)
OWNER_ID = int(os.getenv("CHAT_IDS")) # Replace with your Telegram user ID (owner-only commands).
# ------------------------------------------------------------------------------
# Utility Functions: Subscribers, Unsubscribe Requests, and Chat Logging
# ------------------------------------------------------------------------------
def load_subscribers():
"""Load subscribers from file; create if missing."""
if not filesystem.exists(SUBSCRIBERS_FILE):
logging.info(f"{SUBSCRIBERS_FILE} not found. Creating a new one.")
save_subscribers([])
return []
try:
with filesystem.open(SUBSCRIBERS_FILE, "r") as f:
subscribers = json.load(f)
logging.debug(f"Loaded subscribers: {subscribers}")
return subscribers
except Exception as e:
logging.error(f"Error loading subscribers: {e}")
return []
def save_subscribers(subscribers):
"""Save the subscribers list to file."""
try:
with filesystem.open(SUBSCRIBERS_FILE, "w") as f:
json.dump(subscribers, f, indent=4)
logging.debug("Saved subscribers.")
except Exception as e:
logging.error(f"Error saving subscribers: {e}")
def load_unsubscribe_requests():
"""Load unsubscribe requests from file; create if missing."""
if not filesystem.exists(UNSUBSCRIBE_REQUESTS_FILE):
save_unsubscribe_requests([])
return []
try:
with filesystem.open(UNSUBSCRIBE_REQUESTS_FILE, "r") as f:
reqs = json.load(f)
return reqs
except Exception as e:
logging.error(f"Error loading unsubscribe requests: {e}")
return []
def save_unsubscribe_requests(reqs):
"""Save unsubscribe requests to file."""
try:
with filesystem.open(UNSUBSCRIBE_REQUESTS_FILE, "w") as f:
json.dump(reqs, f, indent=4)
logging.debug("Saved unsubscribe requests.")
except Exception as e:
logging.error(f"Error saving unsubscribe requests: {e}")
def log_chat_message(message):
"""Append each incoming message (in JSON Lines format) to its chat log file."""
chat_id = message.chat.id
log_file_path = path.join(CHAT_LOGS_DIR, f"{chat_id}.log")
log_entry = {
"timestamp": time.strftime("%Y-%m-%d %H:%M:%S"),
"message_id": message.message_id,
"user_id": message.from_user.id if message.from_user else None,
"username": message.from_user.username if message.from_user else None,
"first_name": message.from_user.first_name if message.from_user else None,
"last_name": message.from_user.last_name if message.from_user else None,
"text": message.text,
"chat_id": chat_id,
"chat_type": message.chat.type
}
try:
with filesystem.open(log_file_path, "a") as f:
f.write(json.dumps(log_entry) + "\n")
logging.debug(f"Logged message for chat {chat_id}.")
except Exception as e:
logging.error(f"Error logging message for chat {chat_id}: {e}")
def ensure_subscriber(message):
"""
Automatically add the user to subscribers if not already present.
Each record contains basic info plus an 'unsubscribe_requested' flag.
"""
chat_id = message.chat.id
subscribers = load_subscribers()
if not any(sub.get("chat_id") == chat_id for sub in subscribers):
new_sub = {
"chat_id": chat_id,
"user_id": message.from_user.id if message.from_user else None,
"username": message.from_user.username if message.from_user else "",
"first_name": message.from_user.first_name if message.from_user else "",
"last_name": message.from_user.last_name if message.from_user else "",
"subscription_date": time.strftime("%Y-%m-%d %H:%M:%S"),
"unsubscribe_requested": False
}
subscribers.append(new_sub)
save_subscribers(subscribers)
logging.info(f"Auto-added subscriber: {new_sub}")
# ------------------------------------------------------------------------------
# Update Listener: Log Raw Updates and Auto-Subscribe
# ------------------------------------------------------------------------------
def update_listener(updates):
"""Log raw update data and auto-subscribe users from incoming messages."""
for update in updates:
try:
update_data = update.to_dict()
except Exception:
update_data = update.__dict__
logging.debug(f"Received update: {update_data}")
# Auto-subscribe if update contains a message.
if hasattr(update, "message") and update.message is not None:
ensure_subscriber(update.message)
bot.set_update_listener(update_listener)
# ------------------------------------------------------------------------------
# Retrieve Bot Information
# ------------------------------------------------------------------------------
try:
bot_info = bot.get_me()
logging.info(f"Bot info: id={bot_info.id}, username={bot_info.username}")
except Exception as e:
logging.error(f"Error retrieving bot info: {e}")
raise
# ------------------------------------------------------------------------------
# Command Handlers (All call ensure_subscriber explicitly)
# ------------------------------------------------------------------------------
@bot.message_handler(commands=['start', 'help'])
def send_help(message):
"""Send a help message with detailed usage instructions for every command."""
ensure_subscriber(message)
if message.from_user.id == OWNER_ID:
help_text = (
"<b>Welcome to the Alert Bot! 😃</b>\n\n"
"<b>User Commands:</b>\n"
"• <b>/subscribe</b> - Confirm your subscription or re‑subscribe (cancels any pending unsubscribe request).\n"
"• <b>/unsubscribe</b> - Request to unsubscribe (your request will be pending approval).\n"
"• <b>/status</b> - Check your current subscription status.\n"
"• <b>/myinfo</b> - View your subscription details.\n\n"
"<b>Owner‑Only Commands:</b>\n"
"• <b>/broadcast <message></b> - <i>Send an alert</i> to all subscribers.\n"
" <i>Example:</i> <code>/broadcast Attention: Server maintenance at 10PM.</code>\n"
"• <b>/stats</b> - View subscription statistics.\n"
"• <b>/list_subscribers</b> - List all subscribers with detailed info (shows only User ID).\n"
"• <b>/list_unsubscribes</b> - List all pending unsubscribe requests (shows only User ID).\n"
"• <b>/process_unsubscribes <approve|deny> <all|numbers></b> - Process unsubscribe requests.\n"
" <i>Examples:</i>\n"
" • <code>/process_unsubscribes approve all</code>\n"
" • <code>/process_unsubscribes deny 2 4</code>\n"
"• <b>/clear_chat_logs <chat_id|all></b> - Clear chat log(s).\n"
" <i>Examples:</i>\n"
" • <code>/clear_chat_logs all</code>\n"
" • <code>/clear_chat_logs 123456789</code>\n"
"• <b>/ping</b> - Check if the bot is responsive.\n"
)
else:
help_text = (
"<b>Welcome to the Alert Bot! 😃</b>\n\n"
"<b>User Commands:</b>\n"
"• <b>/subscribe</b> - Confirm your subscription or re‑subscribe.\n"
"• <b>/unsubscribe</b> - Request to unsubscribe (your request is pending approval).\n"
"• <b>/status</b> - Check your current subscription status.\n"
"• <b>/myinfo</b> - View your subscription details.\n"
"• <b>/ping</b> - Check if the bot is responsive.\n"
)
try:
bot.send_message(message.chat.id, help_text, parse_mode="HTML")
logging.info(f"Sent help message to chat {message.chat.id}.")
except Exception as e:
logging.error(f"Error sending help message: {e}")
@bot.message_handler(commands=['subscribe'])
def subscribe(message):
"""(Re)confirm a user's subscription and auto-subscribe if needed."""
ensure_subscriber(message)
chat_id = message.chat.id
subscribers = load_subscribers()
found = False
for sub in subscribers:
if sub.get("chat_id") == chat_id:
found = True
if sub.get("unsubscribe_requested"):
sub["unsubscribe_requested"] = False
save_subscribers(subscribers)
reqs = load_unsubscribe_requests()
new_reqs = [req for req in reqs if req.get("chat_id") != chat_id]
if len(new_reqs) < len(reqs):
save_unsubscribe_requests(new_reqs)
try:
bot.send_message(chat_id, "✅ <b>Your subscription has been re‑confirmed! 🎉</b>", parse_mode="HTML")
logging.info(f"Subscription re‑confirmed for chat {chat_id}.")
except Exception as e:
logging.error(f"Error sending re‑confirmation: {e}")
else:
try:
bot.send_message(chat_id, "😃 <b>You are already subscribed!</b>", parse_mode="HTML")
logging.info(f"Chat {chat_id} is already subscribed.")
except Exception as e:
logging.error(f"Error sending subscription message: {e}")
break
if not found:
new_sub = {
"chat_id": chat_id,
"user_id": message.from_user.id if message.from_user else None,
"username": message.from_user.username if message.from_user else "",
"first_name": message.from_user.first_name if message.from_user else "",
"last_name": message.from_user.last_name if message.from_user else "",
"subscription_date": time.strftime("%Y-%m-%d %H:%M:%S"),
"unsubscribe_requested": False
}
subscribers.append(new_sub)
save_subscribers(subscribers)
try:
bot.send_message(chat_id, "✅ <b>You have been subscribed to alerts! 🎉</b>", parse_mode="HTML")
logging.info(f"New subscriber added: {new_sub}")
except Exception as e:
logging.error(f"Error sending subscription confirmation: {e}")
@bot.message_handler(commands=['unsubscribe'])
def unsubscribe(message):
"""Mark the user as having requested unsubscription and record the request."""
ensure_subscriber(message)
chat_id = message.chat.id
subscribers = load_subscribers()
found = False
for sub in subscribers:
if sub.get("chat_id") == chat_id:
if sub.get("unsubscribe_requested"):
try:
bot.send_message(chat_id, "⚠️ <b>You have already requested to unsubscribe.</b>", parse_mode="HTML")
except Exception as e:
logging.error(f"Error sending message: {e}")
return
else:
sub["unsubscribe_requested"] = True
found = True
break
if found:
save_subscribers(subscribers)
reqs = load_unsubscribe_requests()
if not any(req.get("chat_id") == chat_id for req in reqs):
new_req = {
"chat_id": chat_id,
"user_id": message.from_user.id if message.from_user else None,
"username": message.from_user.username if message.from_user else "",
"first_name": message.from_user.first_name if message.from_user else "",
"last_name": message.from_user.last_name if message.from_user else "",
"request_date": time.strftime("%Y-%m-%d %H:%M:%S")
}
reqs.append(new_req)
save_unsubscribe_requests(reqs)
try:
bot.send_message(chat_id,
"⚠️ <b>Your unsubscribe request has been noted.</b>\nYou will continue to receive alerts until approved.",
parse_mode="HTML")
logging.info(f"Unsubscribe request noted for chat {chat_id}.")
except Exception as e:
logging.error(f"Error sending unsubscribe confirmation: {e}")
else:
try:
bot.send_message(chat_id, "ℹ️ <b>You are not in our subscriber list yet!</b>", parse_mode="HTML")
except Exception as e:
logging.error(f"Error sending not-subscribed message: {e}")
@bot.message_handler(commands=['status'])
def status(message):
"""Provide the subscription status of the user."""
ensure_subscriber(message)
chat_id = message.chat.id
subscribers = load_subscribers()
status_msg = "ℹ️ <b>You are not subscribed. Use /subscribe to subscribe.</b>"
for sub in subscribers:
if sub.get("chat_id") == chat_id:
if sub.get("unsubscribe_requested"):
status_msg = "⚠️ <b>You have requested to unsubscribe. Your request is pending approval.</b>"
else:
status_msg = "✅ <b>You are subscribed to alerts.</b>"
break
try:
bot.send_message(chat_id, status_msg, parse_mode="HTML")
logging.info(f"Sent subscription status to chat {chat_id}.")
except Exception as e:
logging.error(f"Error sending status: {e}")
@bot.message_handler(commands=['myinfo'])
def myinfo(message):
"""Send the stored subscriber info for the current user (showing only User ID)."""
ensure_subscriber(message)
chat_id = message.chat.id
subscribers = load_subscribers()
user_info = next((sub for sub in subscribers if sub.get("chat_id") == chat_id), None)
if user_info:
info_text = (
f"<b>Your Subscription Info:</b>\n"
f"• <b>User ID:</b> {user_info.get('user_id')}\n"
f"• <b>Username:</b> @{user_info.get('username')}\n"
f"• <b>Name:</b> {user_info.get('first_name')} {user_info.get('last_name')}\n"
f"• <b>Subscribed On:</b> {user_info.get('subscription_date')}\n"
f"• <b>Unsubscribe Requested:</b> {user_info.get('unsubscribe_requested')}"
)
else:
info_text = "ℹ️ <b>You are not subscribed. Use /subscribe to subscribe.</b>"
try:
bot.send_message(chat_id, info_text, parse_mode="HTML")
logging.info(f"Sent subscription info to chat {chat_id}.")
except Exception as e:
logging.error(f"Error sending myinfo: {e}")
@bot.message_handler(commands=['broadcast'])
def broadcast(message):
"""
Owner‑only command to broadcast an alert message.
<b>Usage:</b> <code>/broadcast <message></code>
<i>Example:</i> <code>/broadcast Attention: Server maintenance at 10PM.</code>
"""
ensure_subscriber(message)
if message.from_user.id != OWNER_ID:
try:
bot.send_message(message.chat.id, "🚫 <b>You are not authorized to broadcast alerts.</b>", parse_mode="HTML")
except Exception as e:
logging.error(f"Error sending unauthorized message: {e}")
return
broadcast_text = message.text[len('/broadcast'):].strip()
if not broadcast_text:
usage = (
"<b>Usage of /broadcast:</b>\n"
"• <code>/broadcast <message></code>\n\n"
"Example:\n"
"• <code>/broadcast Attention: Server maintenance at 10PM.</code>"
)
try:
bot.send_message(message.chat.id, usage, parse_mode="HTML")
except Exception as e:
logging.error(f"Error sending broadcast usage guide: {e}")
return
subscribers = load_subscribers()
if not subscribers:
try:
bot.send_message(message.chat.id, "ℹ️ <b>No subscribers to send alert.</b>", parse_mode="HTML")
except Exception as e:
logging.error(f"Error sending no-subscriber message: {e}")
return
for sub in subscribers:
chat_id = sub.get("chat_id")
try:
response = bot.send_message(chat_id, broadcast_text, parse_mode="HTML")
logging.info(f"Broadcast sent to chat {chat_id} (message_id={response.message_id}).")
except Exception as e:
logging.error(f"Error sending broadcast to chat {chat_id}: {e}")
try:
bot.send_message(message.chat.id, "✅ <b>Broadcast message sent to all subscribers.</b>", parse_mode="HTML")
except Exception as e:
logging.error(f"Error sending broadcast confirmation: {e}")
@bot.message_handler(commands=['stats'])
def stats(message):
"""
Owner‑only command to display subscription statistics.
"""
ensure_subscriber(message)
if message.from_user.id != OWNER_ID:
try:
bot.send_message(message.chat.id, "🚫 <b>You are not authorized to view stats.</b>", parse_mode="HTML")
except Exception as e:
logging.error(f"Error sending unauthorized stats message: {e}")
return
subscribers = load_subscribers()
total = len(subscribers)
active = len(subscribers)
stats_text = f"<b>Total Subscribers:</b> {total}\n<b>Active Subscribers:</b> {active}"
try:
bot.send_message(message.chat.id, stats_text, parse_mode="HTML")
logging.info(f"Sent stats to owner: {stats_text}")
except Exception as e:
logging.error(f"Error sending stats: {e}")
@bot.message_handler(commands=['list_subscribers'])
def list_subscribers(message):
"""
Owner‑only command to list detailed subscriber info.
(Only <b>User ID</b> is shown.)
"""
ensure_subscriber(message)
if message.from_user.id != OWNER_ID:
try:
bot.send_message(message.chat.id, "🚫 <b>You are not authorized to view subscribers.</b>", parse_mode="HTML")
except Exception as e:
logging.error(f"Error sending unauthorized list_subscribers message: {e}")
return
subscribers = load_subscribers()
if not subscribers:
reply = "ℹ️ <b>No subscribers found.</b>"
else:
reply = "<b>Subscribers:</b>\n"
for idx, sub in enumerate(subscribers, start=1):
reply += (
f"{idx}. <b>User ID:</b> {sub.get('user_id')}, "
f"<b>Name:</b> {sub.get('first_name')} {sub.get('last_name')}, "
f"<b>Username:</b> @{sub.get('username')}, "
f"<b>Subscribed On:</b> {sub.get('subscription_date')}, "
f"<b>Unsubscribe Requested:</b> {sub.get('unsubscribe_requested')}\n"
)
try:
bot.send_message(message.chat.id, reply, parse_mode="HTML")
logging.info("Sent detailed subscriber list to owner.")
except Exception as e:
logging.error(f"Error sending subscribers list: {e}")
@bot.message_handler(commands=['list_unsubscribes'])
def list_unsubscribes(message):
"""
Owner‑only command to list all pending unsubscribe requests.
(Only <b>User ID</b> is shown.)
"""
ensure_subscriber(message)
if message.from_user.id != OWNER_ID:
try:
bot.send_message(message.chat.id, "🚫 <b>You are not authorized to view unsubscribe requests.</b>", parse_mode="HTML")
except Exception as e:
logging.error(f"Error sending unauthorized list_unsubscribes message: {e}")
return
reqs = load_unsubscribe_requests()
if not reqs:
reply = "ℹ️ <b>No unsubscribe requests found.</b>"
else:
reply = "<b>Unsubscribe Requests:</b>\n"
for idx, req in enumerate(reqs, start=1):
reply += (
f"{idx}. <b>User ID:</b> {req.get('user_id')}, "
f"<b>Name:</b> {req.get('first_name')} {req.get('last_name')}, "
f"<b>Username:</b> @{req.get('username')}, "
f"<b>Requested On:</b> {req.get('request_date')}\n"
)
try:
bot.send_message(message.chat.id, reply, parse_mode="HTML")
logging.info("Sent unsubscribe requests list to owner.")
except Exception as e:
logging.error(f"Error sending unsubscribe requests list: {e}")
@bot.message_handler(commands=['process_unsubscribes'])
def process_unsubscribes(message):
"""
Owner‑only command to process unsubscribe requests.
<b>Usage Examples:</b>
• <code>/process_unsubscribes approve all</code>
• <code>/process_unsubscribes deny all</code>
• <code>/process_unsubscribes approve 1 3 5</code>
• <code>/process_unsubscribes deny 2 4</code>
• If <b>approve</b> is used, the subscriber record is removed (they will no longer receive alerts).
• If <b>deny</b> is used, the unsubscribe request is canceled (the subscription remains active).
If insufficient parameters are provided, a detailed guide with current pending requests is shown.
"""
ensure_subscriber(message)
if message.from_user.id != OWNER_ID:
try:
bot.send_message(message.chat.id, "🚫 <b>You are not authorized to process unsubscribe requests.</b>", parse_mode="HTML")
except Exception as e:
logging.error(f"Error sending unauthorized process_unsubscribes message: {e}")
return
args = message.text.split()
reqs = load_unsubscribe_requests()
if len(args) < 3:
guide_text = (
"<b>Usage of /process_unsubscribes:</b>\n\n"
"<b>To <u>approve</u> unsubscribe requests (remove subscribers):</b>\n"
" • <code>/process_unsubscribes approve all</code> - Approve all requests\n"
" • <code>/process_unsubscribes approve 1 3 5</code> - Approve specific requests by their serial numbers\n\n"
"<b>To <u>deny</u> unsubscribe requests (cancel requests, keep subscription active):</b>\n"
" • <code>/process_unsubscribes deny all</code> - Deny all requests\n"
" • <code>/process_unsubscribes deny 2 4</code> - Deny specific requests by their serial numbers\n\n"
"<b>Current Unsubscribe Requests:</b>\n"
)
if reqs:
for idx, req in enumerate(reqs, start=1):
guide_text += (f"{idx}. <b>User ID:</b> {req.get('user_id')}, "
f"<b>Name:</b> {req.get('first_name')} {req.get('last_name')}, "
f"<b>Username:</b> @{req.get('username')}, "
f"<b>Requested On:</b> {req.get('request_date')}\n")
else:
guide_text += "ℹ️ No unsubscribe requests pending."
try:
bot.send_message(message.chat.id, guide_text, parse_mode="HTML")
except Exception as e:
logging.error(f"Error sending process_unsubscribes guide: {e}")
return
action = args[1].lower()
if action not in ("approve", "deny"):
try:
bot.send_message(message.chat.id, "ℹ️ <b>Action must be either 'approve' or 'deny'.</b>", parse_mode="HTML")
except Exception as e:
logging.error(f"Error sending action message: {e}")
return
targets = args[2:]
if len(targets) == 1 and targets[0].lower() == "all":
indices = list(range(len(reqs)))
else:
try:
indices = [int(x) - 1 for x in targets if x.isdigit()]
except Exception as e:
try:
bot.send_message(message.chat.id, "ℹ️ <b>Invalid input. Provide serial numbers or 'all'.</b>", parse_mode="HTML")
except Exception as ex:
logging.error(f"Error sending invalid input message: {ex}")
return
indices = sorted(set(indices))
subscribers = load_subscribers()
processed_details = []
if action == "approve":
for i in indices:
if i < 0 or i >= len(reqs):
continue
req = reqs[i]
chat_id = req.get("chat_id")
sub_removed = None
for sub in subscribers:
if sub.get("chat_id") == chat_id:
sub_removed = sub
break
if sub_removed:
subscribers.remove(sub_removed)
processed_details.append(f"✅ Approved unsubscribe for <b>{sub_removed.get('first_name')} {sub_removed.get('last_name')}</b> (@{sub_removed.get('username')}) (User ID: {sub_removed.get('user_id')})")
new_reqs = [req for j, req in enumerate(reqs) if j not in indices]
elif action == "deny":
for i in indices:
if i < 0 or i >= len(reqs):
continue
req = reqs[i]
chat_id = req.get("chat_id")
for sub in subscribers:
if sub.get("chat_id") == chat_id:
sub["unsubscribe_requested"] = False
processed_details.append(f"❌ Denied unsubscribe for <b>{sub.get('first_name')} {sub.get('last_name')}</b> (@{sub.get('username')}) (User ID: {sub.get('user_id')})")
break
new_reqs = [req for j, req in enumerate(reqs) if j not in indices]
else:
new_reqs = reqs
save_subscribers(subscribers)
save_unsubscribe_requests(new_reqs)
if processed_details:
reply = "<b>Processed Unsubscribe Requests:</b>\n" + "\n".join(processed_details)
else:
reply = "ℹ️ <b>No valid unsubscribe requests processed.</b>"
try:
bot.send_message(message.chat.id, reply, parse_mode="HTML")
logging.info(f"Processed unsubscribe requests: {reply}")
except Exception as e:
logging.error(f"Error sending process_unsubscribes confirmation: {e}")
@bot.message_handler(commands=['clear_chat_logs'])
def clear_chat_logs(message):
"""
Owner‑only command to clear chat logs.
<b>Usage:</b>
• <code>/clear_chat_logs all</code> - Clear all chat logs.
• <code>/clear_chat_logs <chat_id></code> - Clear the chat log for a specific chat.
If the required parameter is missing, a detailed usage guide is shown.
"""
ensure_subscriber(message)
if message.from_user.id != OWNER_ID:
try:
bot.send_message(message.chat.id, "🚫 <b>You are not authorized to clear chat logs.</b>", parse_mode="HTML")
except Exception as e:
logging.error(f"Error sending unauthorized clear_chat_logs message: {e}")
return
args = message.text.split()
if len(args) < 2:
usage = (
"<b>Usage of /clear_chat_logs:</b>\n\n"
"• <code>/clear_chat_logs all</code> - Clear all chat logs.\n"
"• <code>/clear_chat_logs <chat_id></code> - Clear the chat log for a specific chat.\n\n"
"Example:\n"
"• <code>/clear_chat_logs all</code>\n"
"• <code>/clear_chat_logs 123456789</code>"
)
try:
bot.send_message(message.chat.id, usage, parse_mode="HTML")
except Exception as e:
logging.error(f"Error sending clear_chat_logs usage guide: {e}")
return
target = args[1].lower()
if target == "all":
cleared = 0
for file in filesystem.listdir(CHAT_LOGS_DIR):
file_path = path.join(CHAT_LOGS_DIR, file)
try:
filesystem.remove(file_path)
cleared += 1
except Exception as e:
logging.error(f"Error removing file {file_path}: {e}")
reply = f"✅ Cleared <b>{cleared}</b> chat log file(s)."
else:
file_path = path.join(CHAT_LOGS_DIR, f"{target}.log")
if filesystem.exists(file_path):
try:
filesystem.remove(file_path)
reply = f"✅ Cleared chat log for chat <b>{target}</b>."
except Exception as e:
reply = f"⚠️ Error clearing log for chat <b>{target}</b>: {e}"
logging.error(reply)
else:
reply = f"ℹ️ No log file found for chat <b>{target}</b>."
try:
bot.send_message(message.chat.id, reply, parse_mode="HTML")
logging.info(f"clear_chat_logs: {reply}")
except Exception as e:
logging.error(f"Error sending clear_chat_logs confirmation: {e}")
@bot.message_handler(commands=['ping'])
def ping(message):
"""Simple command to check if the bot is responsive."""
ensure_subscriber(message)
try:
bot.send_message(message.chat.id, "🏓 <b>pong</b>", parse_mode="HTML")
logging.info(f"Ping response sent to chat {message.chat.id}.")
except Exception as e:
logging.error(f"Error sending ping response: {e}")
# ------------------------------------------------------------------------------
# Default Handler: Log Incoming Messages and Ensure Subscriber Record
# ------------------------------------------------------------------------------
@bot.message_handler(func=lambda message: True)
def default_message_handler(message):
"""
For every incoming message:
1. Auto-subscribe the user (if not already in the list).
2. Log the message in a per‑chat log file.
"""
try:
ensure_subscriber(message)
except Exception as e:
logging.error(f"Error ensuring subscriber for chat {message.chat.id}: {e}")
try:
log_chat_message(message)
except Exception as e:
logging.error(f"Error logging message from chat {message.chat.id}: {e}")
logging.debug(f"Received message in chat {message.chat.id}: from: {message.from_user.username if message.from_user else 'N/A'} | text: {message.text}")
# ------------------------------------------------------------------------------
# Asynchronous Owner Alert Input (Console)
# ------------------------------------------------------------------------------
# def alert_input_listener():
# """
# Continuously prompt the owner (via the console) for an alert message.
# Upon input (unless 'exit' is typed), broadcast the alert to all subscribers.
# """
# while True:
# try:
# alert_message = input("Enter alert message to broadcast (or type 'exit' to stop): ").strip()
# if alert_message.lower() == 'exit':
# logging.info("Exiting console alert input listener.")
# break
# if not alert_message:
# continue # Skip empty input.
# subscribers = load_subscribers()
# if not subscribers:
# logging.warning("No subscribers found. Alert not sent.")
# continue
# for sub in subscribers:
# chat_id = sub.get("chat_id")
# try:
# response = bot.send_message(chat_id, alert_message, parse_mode="HTML")
# logging.info(f"Console alert sent to chat {chat_id} (message_id={response.message_id}).")
# except Exception as e:
# logging.error(f"Error sending console alert to chat {chat_id}: {e}")
# except Exception as e:
# logging.error(f"Error in alert input listener: {e}")
# Start the asynchronous alert input listener in a daemon thread.
# alert_input_thread = threading.Thread(target=alert_input_listener, daemon=True)
# alert_input_thread.start()
# logging.info("Started asynchronous alert input listener thread.")
# ------------------------------------------------------------------------------
# Start Bot Polling
# ------------------------------------------------------------------------------
# try:
# logging.info("Starting bot polling...")
# bot.polling(none_stop=True)
# except Exception as e:
# logging.error(f"Bot polling error: {e}")
# ─────────────────────────────────────────────────── FastAPI ───
app = FastAPI()
@app.get("/")
def root(): # ② health‑check hits this → must return 200 quickly
return {"status": "ok"}
@app.on_event("startup")
def startup():
# Launch the bot *after* Uvicorn has started
threading.Thread(target=bot.infinity_polling, daemon=True).start() |