# 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 = ( "Welcome to the Alert Bot! 😃\n\n" "User Commands:\n" "• /subscribe - Confirm your subscription or re‑subscribe (cancels any pending unsubscribe request).\n" "• /unsubscribe - Request to unsubscribe (your request will be pending approval).\n" "• /status - Check your current subscription status.\n" "• /myinfo - View your subscription details.\n\n" "Owner‑Only Commands:\n" "• /broadcast <message> - Send an alert to all subscribers.\n" " Example: /broadcast Attention: Server maintenance at 10PM.\n" "• /stats - View subscription statistics.\n" "• /list_subscribers - List all subscribers with detailed info (shows only User ID).\n" "• /list_unsubscribes - List all pending unsubscribe requests (shows only User ID).\n" "• /process_unsubscribes <approve|deny> <all|numbers> - Process unsubscribe requests.\n" " Examples:\n" " • /process_unsubscribes approve all\n" " • /process_unsubscribes deny 2 4\n" "• /clear_chat_logs <chat_id|all> - Clear chat log(s).\n" " Examples:\n" " • /clear_chat_logs all\n" " • /clear_chat_logs 123456789\n" "• /ping - Check if the bot is responsive.\n" ) else: help_text = ( "Welcome to the Alert Bot! 😃\n\n" "User Commands:\n" "• /subscribe - Confirm your subscription or re‑subscribe.\n" "• /unsubscribe - Request to unsubscribe (your request is pending approval).\n" "• /status - Check your current subscription status.\n" "• /myinfo - View your subscription details.\n" "• /ping - 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, "✅ Your subscription has been re‑confirmed! 🎉", 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, "😃 You are already subscribed!", 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, "✅ You have been subscribed to alerts! 🎉", 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, "⚠️ You have already requested to unsubscribe.", 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, "⚠️ Your unsubscribe request has been noted.\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, "ℹ️ You are not in our subscriber list yet!", 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 = "ℹ️ You are not subscribed. Use /subscribe to subscribe." for sub in subscribers: if sub.get("chat_id") == chat_id: if sub.get("unsubscribe_requested"): status_msg = "⚠️ You have requested to unsubscribe. Your request is pending approval." else: status_msg = "✅ You are subscribed to alerts." 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"Your Subscription Info:\n" f"• User ID: {user_info.get('user_id')}\n" f"• Username: @{user_info.get('username')}\n" f"• Name: {user_info.get('first_name')} {user_info.get('last_name')}\n" f"• Subscribed On: {user_info.get('subscription_date')}\n" f"• Unsubscribe Requested: {user_info.get('unsubscribe_requested')}" ) else: info_text = "ℹ️ You are not subscribed. Use /subscribe to subscribe." 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. Usage: /broadcast <message> Example: /broadcast Attention: Server maintenance at 10PM. """ ensure_subscriber(message) if message.from_user.id != OWNER_ID: try: bot.send_message(message.chat.id, "🚫 You are not authorized to broadcast alerts.", 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 = ( "Usage of /broadcast:\n" "• /broadcast <message>\n\n" "Example:\n" "• /broadcast Attention: Server maintenance at 10PM." ) 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, "ℹ️ No subscribers to send alert.", 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, "✅ Broadcast message sent to all subscribers.", 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, "🚫 You are not authorized to view stats.", 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"Total Subscribers: {total}\nActive Subscribers: {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 User ID is shown.) """ ensure_subscriber(message) if message.from_user.id != OWNER_ID: try: bot.send_message(message.chat.id, "🚫 You are not authorized to view subscribers.", 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 = "ℹ️ No subscribers found." else: reply = "Subscribers:\n" for idx, sub in enumerate(subscribers, start=1): reply += ( f"{idx}. User ID: {sub.get('user_id')}, " f"Name: {sub.get('first_name')} {sub.get('last_name')}, " f"Username: @{sub.get('username')}, " f"Subscribed On: {sub.get('subscription_date')}, " f"Unsubscribe Requested: {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 User ID is shown.) """ ensure_subscriber(message) if message.from_user.id != OWNER_ID: try: bot.send_message(message.chat.id, "🚫 You are not authorized to view unsubscribe requests.", 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 = "ℹ️ No unsubscribe requests found." else: reply = "Unsubscribe Requests:\n" for idx, req in enumerate(reqs, start=1): reply += ( f"{idx}. User ID: {req.get('user_id')}, " f"Name: {req.get('first_name')} {req.get('last_name')}, " f"Username: @{req.get('username')}, " f"Requested On: {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. Usage Examples:/process_unsubscribes approve all/process_unsubscribes deny all/process_unsubscribes approve 1 3 5/process_unsubscribes deny 2 4 • If approve is used, the subscriber record is removed (they will no longer receive alerts). • If deny 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, "🚫 You are not authorized to process unsubscribe requests.", 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 = ( "Usage of /process_unsubscribes:\n\n" "To approve unsubscribe requests (remove subscribers):\n" " • /process_unsubscribes approve all - Approve all requests\n" " • /process_unsubscribes approve 1 3 5 - Approve specific requests by their serial numbers\n\n" "To deny unsubscribe requests (cancel requests, keep subscription active):\n" " • /process_unsubscribes deny all - Deny all requests\n" " • /process_unsubscribes deny 2 4 - Deny specific requests by their serial numbers\n\n" "Current Unsubscribe Requests:\n" ) if reqs: for idx, req in enumerate(reqs, start=1): guide_text += (f"{idx}. User ID: {req.get('user_id')}, " f"Name: {req.get('first_name')} {req.get('last_name')}, " f"Username: @{req.get('username')}, " f"Requested On: {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, "ℹ️ Action must be either 'approve' or 'deny'.", 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, "ℹ️ Invalid input. Provide serial numbers or 'all'.", 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 {sub_removed.get('first_name')} {sub_removed.get('last_name')} (@{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 {sub.get('first_name')} {sub.get('last_name')} (@{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 = "Processed Unsubscribe Requests:\n" + "\n".join(processed_details) else: reply = "ℹ️ No valid unsubscribe requests processed." 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. Usage:/clear_chat_logs all - Clear all chat logs. • /clear_chat_logs <chat_id> - 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, "🚫 You are not authorized to clear chat logs.", 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 = ( "Usage of /clear_chat_logs:\n\n" "• /clear_chat_logs all - Clear all chat logs.\n" "• /clear_chat_logs <chat_id> - Clear the chat log for a specific chat.\n\n" "Example:\n" "• /clear_chat_logs all\n" "• /clear_chat_logs 123456789" ) 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 {cleared} 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 {target}." except Exception as e: reply = f"⚠️ Error clearing log for chat {target}: {e}" logging.error(reply) else: reply = f"ℹ️ No log file found for chat {target}." 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, "🏓 pong", 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()