broadcast_bot / app.py
AstraOS's picture
Update app.py
c448d07 verified
# 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 &lt;message&gt;</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 &lt;approve|deny&gt; &lt;all|numbers&gt;</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 &lt;chat_id|all&gt;</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 &lt;message&gt;</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 &lt;message&gt;</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 &lt;chat_id&gt;</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 &lt;chat_id&gt;</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()