Spaces:
Sleeping
Sleeping
Download bot.py from xkailashhh/postingbot: direct link, hf CLI and curl.
- Browser
- Download file 96.9 kB
-
https://huggingface.co/spaces/xkailashhh/postingbot/resolve/main/bot.py
- Command line
-
hf download hf://spaces/xkailashhh/postingbot/bot.py
-
curl -L -o bot.py https://huggingface.co/spaces/xkailashhh/postingbot/resolve/main/bot.py
96.9 kB
"""
bot.py β Telethon bot (MongoDB via Motor).
Run: python bot.py (separate process from FastAPI)
"""
from __future__ import annotations
import asyncio
import json
import logging
import os
from datetime import datetime, timedelta
from pathlib import Path
from typing import Any, Dict, Optional
from telethon import (
Button,
TelegramClient,
events
)
from telethon.errors import (
ChatAdminRequiredError,
MessageNotModifiedError,
RPCError,
UserNotParticipantError,
FloodWaitError,
UserIsBlockedError,
InputUserDeactivatedError,
PeerIdInvalidError,
UserDeactivatedBanError
)
from telethon.tl.functions.channels import (
GetFullChannelRequest,
GetParticipantRequest,
)
from telethon.tl.functions.messages import (
ExportChatInviteRequest,
ForwardMessagesRequest
)
from telethon.tl.types import (
ChannelParticipantAdmin,
ChannelParticipantBanned,
ChannelParticipantCreator,
Message,
MessageService,
MessageMediaDocument,
MessageMediaPhoto,
MessageActionChatAddUser,
UpdateNewChannelMessage
)
from telethon.utils import get_input_channel
from apscheduler.schedulers.asyncio import AsyncIOScheduler
import config
import db
from utils import generate_hash, ImgBBUploader
logging.basicConfig(
level=logging.INFO,
format="[%(asctime)s] %(levelname)s %(name)s: %(message)s",
datefmt="%H:%M:%S",
)
log = logging.getLogger("bot")
CACHE_DIR = Path("downloads")
CACHE_DIR.mkdir(exist_ok=True)
ibb = ImgBBUploader(api_key=config.IMGBB_API_KEY)
client = TelegramClient("bot_session", config.API_ID, config.API_HASH)
# wizard[user_id] = { step, wizard_msg_id, wizard_chat_id, image_url, caption,
# redirect_link, required_ads, category, source_msg_id,
# source_chat_id, ... }
wizard: Dict[int, dict] = {}
_bot_username: str = ""
scheduler = AsyncIOScheduler(timezone="UTC")
# HELPERS ------------------
async def get_bot_username() -> str:
global _bot_username
if not _bot_username:
me = await client.get_me()
_bot_username = me.username or ""
return _bot_username
def make_link(magical_hash: str, bot_username: str) -> str:
return config.miniapp_link(magical_hash, bot_username)
async def is_owner_async(user_id: int) -> bool:
owners = config.OWNER_IDS.copy()
extra = await db.get_setting("extra_owners", "[]")
try:
owners.extend(json.loads(extra))
except Exception:
pass
return user_id in owners
async def safe_edit(event_or_msg, text: str, **kwargs):
"""edit() wrapper that swallows MessageNotModifiedError."""
try:
if hasattr(event_or_msg, "edit"):
await event_or_msg.edit(text, **kwargs)
else:
await event_or_msg.edit(text, **kwargs)
except MessageNotModifiedError:
pass
except Exception as e:
log.warning("safe_edit failed: %s", e)
async def edit_wizard_msg(user_id: int, text: str, **kwargs):
"""
Edit the single wizard message stored in wizard[user_id]['wizard_msg_id'].
Falls back to client.edit_message if we have the coords.
"""
state = wizard.get(user_id, {})
msg_id = state.get("wizard_msg_id")
chat_id = state.get("wizard_chat_id")
if not msg_id or not chat_id:
return
try:
await client.edit_message(chat_id, msg_id, text, **kwargs)
except MessageNotModifiedError:
pass
except Exception as e:
log.warning("edit_wizard_msg failed: %s", e)
async def flush_all_posts() -> int:
"""
Permanently delete ALL posts from the database (both active and soft-deleted).
Returns the number of deleted documents.
"""
result = await db.posts_col().delete_many({})
return result.deleted_count
async def add_posting_channel(channel_id: str, channel_name: str, invite_link: str = "") -> bool:
"""Add a posting channel to the unified channels collection."""
return await db.add_channel(channel_id, channel_name, 0, "posting", invite_link)
# FORCE SUBSCRIPTION
async def check_force_sub(event) -> bool:
if not config.FORCE_SUB_ENABLED:
return True
user_id = event.sender_id
if await is_owner_async(user_id):
return True
all_channels = await db.get_channels()
if not all_channels:
return True
# Step 1: check membership first
failed = []
for ch in all_channels:
channel_id = ch.get("channel_id")
try:
result = await client(GetParticipantRequest(int(channel_id), user_id))
if isinstance(result.participant, ChannelParticipantBanned):
failed.append(ch)
except UserNotParticipantError:
failed.append(ch)
except ChatAdminRequiredError:
failed.append(ch)
except Exception as e:
log.warning("Membership check error %s: %s", channel_id, e)
failed.append(ch) # block on unknown error
if not failed:
return True
# Step 2: get/generate invite links only for failed channels
buttons = []
lines = ["β οΈ <b>Join required channels to continue:</b>\n"]
for ch in failed:
channel_id = ch.get("channel_id")
channel_type = ch.get("type")
invite_link = ch.get("invite_link", "")
name = ch.get("channel_name", channel_id)
if not invite_link:
try:
peer = await client.get_input_entity(int(channel_id))
new_invite = await client(ExportChatInviteRequest(
peer=peer,
legacy_revoke_permanent=False,
request_needed=True,
usage_limit=0,
))
invite_link = new_invite.link
await db.update_channel_invite_link(channel_id, channel_type, invite_link)
log.info("Generated new link on-demand for %s", channel_id)
except Exception as e:
log.warning("On-demand link generation failed %s: %s", channel_id, e)
if invite_link:
lines.append(f"β’ <a href='{invite_link}'>{name}</a>")
buttons.append([Button.url(f"π’ Join {name}", invite_link)])
else:
lines.append(f"β’ {name} (ask admin for link)")
buttons.append([Button.inline("β
I joined β Check again", b"check_sub")])
await event.reply("\n".join(lines), parse_mode="v2", buttons=buttons)
return False
async def perform():
now = datetime.utcnow()
timeout_str = await db.get_setting("fsub_timeout", str(config.DEFAULT_FSUB_TIMEOUT))
try:
FSUB_TIMEOUT = int(timeout_str)
except ValueError:
FSUB_TIMEOUT = config.DEFAULT_FSUB_TIMEOUT
log.info("β³ Checking ForceSub links...")
channels = await db.get_channels(channel_type="posting", include_inactive=False)
if not channels:
log.info("No ForceSub channels found.")
return
log.info(f"Found {len(channels)} ForceSub channel(s) to check.")
refreshed = 0
failed = 0
for ch in channels:
channel_id = ch.get("channel_id")
channel_name = ch.get("channel_name", "Unknown")
current_link = ch.get("invite_link", "")
last_updated = ch.get("last_updated")
if not channel_id:
log.warning(f"Skipping channel with no ID: {ch}")
continue
is_expired = True # Default to refresh if no last_updated
if last_updated:
if isinstance(last_updated, datetime):
expiry = last_updated + timedelta(seconds=FSUB_TIMEOUT)
is_expired = now >= expiry
else:
try:
from dateutil import parser
parsed = parser.isoparse(last_updated) if isinstance(last_updated, str) else last_updated
expiry = parsed + timedelta(seconds=FSUB_TIMEOUT)
is_expired = now >= expiry
except Exception:
is_expired = True
if not is_expired:
log.info(f" β {channel_name} ({channel_id}): link still valid")
continue
# Link expired or never set β refresh it
try:
log.info(f" π Refreshing {channel_name} ({channel_id})...")
peer = await client.get_input_entity(int(channel_id))
if current_link:
try:
await client(ExportChatInviteRequest(
peer=peer,
legacy_revoke_permanent=True
))
log.info(f" β Revoked old link")
except Exception as e:
log.warning(f" β Could not revoke old link: {e}")
new_exp = int((datetime.utcnow() + timedelta(seconds=FSUB_TIMEOUT)).timestamp())
new_invite = await client(ExportChatInviteRequest(
peer=peer,
expire_date=new_exp,
usage_limit=0 # 0 = unlimited uses
))
new_link = new_invite.link
await db.update_channel_invite_link(channel_id, "request", new_link)
log.info(f" β New link created for {channel_name}")
refreshed += 1
except Exception as e:
log.error(f" β Failed to refresh {channel_name} ({channel_id}): {e}")
failed += 1
log.info(f"β
ForceSub cycle complete: {refreshed} refreshed, {failed} failed, {len(channels) - refreshed - failed} skipped.")
def start_scheduler():
if not config.FSUB_TIMEOUT:
log.warning("FSUB_TIMEOUT not configured, skipping scheduler.")
return
scheduler.add_job(
perform,
"interval",
seconds=config.FSUB_TIMEOUT,
id="force_sub_refresh",
replace_existing=True,
)
scheduler.start()
log.info(f"[ForceSub Scheduler] Started with interval {config.FSUB_TIMEOUT // 3600} hours.")
# -------- listeners
@client.on(events.ChatAction)
async def on_bot_added(event):
if not isinstance(event.action_message, Message):
return
if hasattr(event, 'user_added') and event.user_added:
msg = event.action_message
chat_id = event.chat_id
chat = await event.get_chat()
me = await client.get_me()
added_users = []
if isinstance(msg, MessageService) and isinstance(msg.action, MessageActionChatAddUser):
added_users = msg.action.users
elif hasattr(event, 'users'):
added_users = [event.users] if not isinstance(event.users, list) else event.users
if me.id in added_users:
adder_id = None
if hasattr(event, 'added_by') and event.added_by:
adder_id = event.added_by
elif hasattr(msg, 'from_id') and msg.from_id:
adder_id = msg.from_id
if not adder_id:
return
try:
adder = await client.get_entity(adder_id)
adder_name = getattr(adder, 'first_name', str(adder_id))
except:
adder_name = str(adder_id)
chat_name = getattr(chat, 'title', 'Unknown Chat')
chat_username = getattr(chat, 'username', None)
chat_link = f"https://t.me/{chat_username}" if chat_username else f"Private chat (ID: {chat_id})"
await client.send_message(
adder_id,
f"<b><blockquote>π’ Bot Added to Chat!</blockquote></b>\n\n"
f"β’ <b>Chat Name:</b> {chat_name}\n"
f"β’ <b>Chat ID:</b> <code>{chat_id}</code>\n"
f"β’ <b>Invite Link:</b> {chat_link}\n\n"
f"What would you like to do with this chat?\n"
f"Use the buttons below to configure:",
parse_mode='v2',
buttons=[
[Button.inline("π’ Request Channel", f"set_req:{chat_id}".encode())],
[Button.inline("π‘ Posting Channel", f"set_post:{chat_id}".encode())],
[Button.inline("β Ignore", f"ignore:{chat_id}".encode())]
]
)
log.info(f"Bot added to {chat_name} (ID: {chat_id}) by {adder_name} ({adder_id})")
# USER RECORDING
async def record_user(user_id: int, first_name: str, username: str = ""):
await db.record_user(user_id, first_name, username)
# /start
async def send_start(event):
sender = await event.get_sender()
user_id = sender.id
name = getattr(sender, "first_name", "there")
username = getattr(sender, "username", "")
await record_user(user_id, name, username)
bot_username = await get_bot_username()
total = await db.count_active_posts()
if await is_owner_async(user_id):
text = (
f"<blockquote>π Hello <b>{name}</b>!</blockquote>\n\n"
f"π This bot hosts <b>{total} exclusive posts</b>.\n"
f"Watch short ads to unlock content and access links.\n\n"
f"β Tap a button below to get started"
)
buttons = [
[Button.url("π Open App", f"https://t.me/{bot_username}/app?")],
[Button.inline("π Stats", b"public_stats"), Button.inline("π Browse Posts", b"browse")],
[Button.inline("βοΈ Admin Panel", b"admin_hint")],
]
else:
text = (
f"<blockquote>π₯ Hey <b>{name}</b>!</blockquote>\n\n"
"π Craving something extra?\n"
"π Unlock premium vibes β personally for you\n"
"π New surprises landing daily\n\n"
"ποΈποΈ Look closerβ¦ the best is hidden inside\n"
"β€οΈβπ₯ Don't stray β let's keep the vibe going\n"
)
mini_app_url = f"https://t.me/{bot_username}/app?"
second_mini_app_url = f"https://t.me/{bot_username}/app?start=premium"
link1 = "https://additlater.com"
link2 = "https://additlater.com"
buttons = [
[Button.url("π Hot Videos Collection π₯΅", mini_app_url)],
[Button.url("π New desi maal π", second_mini_app_url)],
#[Button.url("π Hot Surprise π₯", link1)],
#[Button.url("π₯΅π₯΅π₯΅", link2)],
]
await event.reply(
text,
file=config.FORCE_SUB_URL if config.FORCE_SUB_URL else None,
parse_mode="v2",
buttons=buttons,
link_preview=False
)
@client.on(events.NewMessage(pattern="/start"))
async def cmd_start(event):
if not await check_force_sub(event):
return
await send_start(event)
raise events.StopPropagation
# MENU RENDERERS (all edit the same message; accept event or (chat_id, msg_id))
async def render_admin_panel(event):
await safe_edit(event,
"<b><blockquote>βοΈ Admin Control Panel</blockquote></b>\n\nChoose a section:",
parse_mode="v2",
buttons=[
[Button.inline("π Posts", b"admin_posts")],
[Button.inline("π’ Channels", b"admin_channels")],
[Button.inline("π Stats", b"admin_stats")],
[Button.inline("π§ Extra", b"admin_extra")],
[Button.inline("π Close", b"admin_close")],
],
)
async def render_posts_menu(event):
await safe_edit(event,
"<b><blockquote>π Post Management</blockquote></b>\n\nChoose an action:",
parse_mode="v2",
buttons=[
[Button.inline("β Create New Post", b"posts_create")],
[Button.inline("π List Active Posts", b"posts_list_edit")],
[Button.inline("π Remove One Post", b"posts_remove_one")],
[Button.inline("β οΈ Remove All Posts", b"posts_remove_all")],
[Button.inline("πΎ Backup Posts", b"posts_backup")],
[Button.inline("π Back", b"back_to_admin")],
],
)
async def render_channels_menu(event):
await safe_edit(event,
"<b><blockquote>π’ Channel Management</blockquote></b>\n\n"
"<b>Request Channels</b> (forceβsub): users must join before using bot.\n"
"<b>Posting Channels</b>: new posts are broadcasted here.\n\n"
"Select a category:",
parse_mode="v2",
buttons=[
[Button.inline("π Request Channels", b"channel_menu_req")],
[Button.inline("π‘ Posting Channels", b"channel_menu_post")],
[Button.inline("π Back", b"back_to_admin")],
],
)
async def render_req_channels_menu(event):
await safe_edit(event,
"<b><blockquote>π Request Channels (ForceβSub)</blockquote></b>\n\n"
"Manage channels that users must join:",
parse_mode="v2",
buttons=[
[Button.inline("β Add Request Channel", b"channels_req_add")],
[Button.inline("π List Request Channels", b"channels_req_list")],
[Button.inline("π Remove One", b"channels_req_remove_one")],
[Button.inline("β οΈ Remove All", b"channels_req_remove_all")],
[Button.inline("π Back to Channels", b"channels_back_main")],
],
)
async def render_post_channels_menu(event):
await safe_edit(event,
"<b><blockquote>π‘ Posting Channels</blockquote></b>\n\n"
"Manage channels where new posts are broadcasted:",
parse_mode="v2",
buttons=[
[Button.inline("β Add Posting Channel", b"channels_post_add")],
[Button.inline("π List Posting Channels", b"channels_post_list")],
[Button.inline("π Remove One", b"channels_post_remove_one")],
[Button.inline("β οΈ Remove All", b"channels_post_remove_all")],
[Button.inline("π Back to Channels", b"channels_back_main")],
],
)
async def render_extra_menu(event):
await safe_edit(event,
"<b><blockquote>π§ Extra Admin Settings</blockquote></b>\n\nManage additional admins:",
parse_mode="v2",
buttons=[
[Button.inline("β Add Admin", b"extra_add_admin")],
[Button.inline("π Remove Admin", b"extra_remove_admin")],
[Button.inline("β οΈ Remove All Extra Admins", b"extra_remove_all_admins")],
[Button.inline("π Back", b"back_to_admin")],
],
)
async def render_stats(event):
total_posts = await db.count_active_posts()
total_unlocks = await db.total_unlocks()
total_views = await db.total_views()
unique_users = await db.unique_users()
total_users = len(await db.get_all_users())
admin_hash = await db.get_setting("admin_password_hash", "")
masked = (admin_hash[:20] + "β¦" + admin_hash[-10:]) if len(admin_hash) > 30 else "not set"
extra = json.loads(await db.get_setting("extra_owners", "[]"))
await safe_edit(event,
f"<b><blockquote>π Detailed Stats</blockquote></b>\n\n"
f"π Active posts: {total_posts}\n"
f"π Total views: {total_views}\n"
f"π Total unlocks: {total_unlocks}\n"
f"π€ Unique users (unlocked): {unique_users}\n"
f"π₯ Total registered users: {total_users}\n"
f"π Admin hash (masked): <code>{masked}</code>\n"
f"π Extra owners: {extra}\n"
f"π Server time: {datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S UTC')}",
parse_mode="v2",
buttons=[[Button.inline("π Back", b"back_to_admin")]],
)
# ADMIN PANEL ENTRY POINTS
async def send_admin_panel(event, edit: bool = False):
text = "<b><blockquote>βοΈ Admin Control Panel</blockquote></b>\n\nChoose a section:"
buttons = [
[Button.inline("π Posts", b"admin_posts")],
[Button.inline("π’ Channels", b"admin_channels")],
[Button.inline("π Stats", b"admin_stats")],
[Button.inline("π§ Extra", b"admin_extra")],
[Button.inline("π Close", b"admin_close")],
]
if edit:
await safe_edit(event, text, parse_mode="v2", buttons=buttons)
else:
await event.reply(text, parse_mode="v2", buttons=buttons)
@client.on(events.NewMessage(pattern="/admin"))
async def cmd_admin(event):
if not await is_owner_async(event.sender_id):
await event.reply("β Owner only.")
return
await send_admin_panel(event, edit=False)
# POST WIZARD
def _wizard_cancel_buttons():
return [[Button.inline("β Cancel", b"post_cancel")]]
def _wizard_step_buttons(back_data: bytes | None = None, cancel: bool = True):
row = []
if back_data:
row.append(Button.inline("β Back", back_data))
if cancel:
row.append(Button.inline("β Cancel", b"post_cancel"))
return [row] if row else []
async def _start_wizard(event, from_admin_panel: bool = False):
"""
Send the wizard's single message and record its ID.
from_admin_panel=True means the wizard was started from the admin panel
inline button; we store that context so Cancel can return there.
"""
user_id = event.sender_id
# If already in a wizard step, cancel it silently first
if user_id in wizard:
old = wizard.pop(user_id, {})
old_msg = old.get("wizard_msg_id")
old_chat = old.get("wizard_chat_id")
if old_msg and old_chat:
try:
await client.edit_message(old_chat, old_msg, "β οΈ Previous wizard cancelled.", buttons=None)
except Exception:
pass
text = (
"<b><blockquote>π New Post β Step 1/5</blockquote></b>\n\n"
"πΈ Send the <b>image URL</b> (https://β¦) or paste a direct link.\n\n"
"<i>Tip: forwarding media from another chat won't be picked up while you're in this wizard.</i>"
)
buttons = _wizard_cancel_buttons()
if from_admin_panel:
# The event IS the callback query; edit that message to become the wizard
await safe_edit(event, text, parse_mode="v2", buttons=buttons)
msg_id = event.message_id
chat_id = event.chat_id
else:
# /post command: reply with a new message that becomes the wizard
sent = await event.reply(text, parse_mode="v2", buttons=buttons)
msg_id = sent.id
chat_id = sent.chat_id
wizard[user_id] = {
"step": "await_image",
"wizard_msg_id": msg_id,
"wizard_chat_id": chat_id,
"from_admin": from_admin_panel,
}
@client.on(events.NewMessage(pattern="/post"))
async def cmd_post(event):
if not await is_owner_async(event.sender_id):
await event.reply("β Owner only.")
return
await _start_wizard(event, from_admin_panel=False)
raise events.StopPropagation
# ββ Wizard:
async def _wizard_handle_image_url(event, user_id: int):
url = (event.message.text or "").strip()
if not url.startswith("http"):
await edit_wizard_msg(user_id,
"<b><blockquote>π New Post β Step 1/5</blockquote></b>\n\n"
"β Must be a valid URL starting with <code>http://</code> or <code>https://</code>.\n"
"Try again:",
parse_mode="v2", buttons=_wizard_cancel_buttons(),
)
return
wizard[user_id]["image_url"] = url
wizard[user_id]["step"] = "await_caption"
try: await event.delete()
except Exception: pass
await edit_wizard_msg(user_id,
"<b><blockquote>π New Post β Step 2/5</blockquote></b>\n\n"
"βοΈ Send the <b>caption / title</b> for this post:",
parse_mode="v2",
buttons=_wizard_step_buttons(back_data=b"wiz_back_to_image"),
)
async def _wizard_handle_caption(event, user_id: int):
caption = (event.message.text or "").strip()
if not caption:
return
wizard[user_id]["caption"] = caption
wizard[user_id]["step"] = "await_redirect"
try: await event.delete()
except Exception: pass
await edit_wizard_msg(user_id,
"<b><blockquote>π New Post β Step 3/5</blockquote></b>\n\n"
"π Send the <b>redirect URL</b> (destination users reach after unlocking):",
parse_mode="v2",
buttons=_wizard_step_buttons(back_data=b"wiz_back_to_caption"),
)
async def _wizard_handle_redirect(event, user_id: int):
url = (event.message.text or "").strip()
if not url.startswith("http"):
await edit_wizard_msg(user_id,
"<b><blockquote>π New Post β Step 3/5</blockquote></b>\n\n"
"β Must be a valid URL starting with http/https. Try again:",
parse_mode="v2",
buttons=_wizard_step_buttons(back_data=b"wiz_back_to_caption"),
)
return
wizard[user_id]["redirect_link"] = url
wizard[user_id]["step"] = "await_category"
try: await event.delete()
except Exception: pass
await edit_wizard_msg(user_id,
"<b><blockquote>π New Post β Step 4/5</blockquote></b>\n\n"
"π· Send a <b>category</b> tag (e.g. <code>movies</code>, <code>series</code>) "
"or tap Skip:",
parse_mode="v2",
buttons=[
[Button.inline("β© Skip (no category)", b"wiz_skip_category")],
*_wizard_step_buttons(back_data=b"wiz_back_to_redirect"),
],
)
async def _wizard_handle_category(event, user_id: int):
category = (event.message.text or "").strip().lower()
wizard[user_id]["category"] = category
wizard[user_id]["step"] = "await_ads"
try: await event.delete()
except Exception: pass
await _show_ads_step(user_id)
async def _show_ads_step(user_id: int):
await edit_wizard_msg(user_id,
f"<b><blockquote>π New Post β Step 5/5</blockquote></b>\n\n"
f"πΊ How many ads must users watch to unlock?\n"
f"(Default: {config.DEFAULT_ADS})",
parse_mode="v2",
buttons=[
[Button.inline("1", b"wiz_ads_1"), Button.inline("2", b"wiz_ads_2"), Button.inline("3", b"wiz_ads_3")],
[Button.inline(f"Default ({config.DEFAULT_ADS})", b"wiz_ads_default"), Button.inline("0 (free)", b"wiz_ads_0")],
*_wizard_step_buttons(back_data=b"wiz_back_to_category"),
],
)
async def _show_confirm_step(user_id: int):
s = wizard.get(user_id, {})
await edit_wizard_msg(user_id,
f"<b><blockquote>π New Post β Confirm</blockquote></b>\n\n"
f"πΌ <b>Image:</b> <code>{s.get('image_url','')[:60]}β¦</code>\n"
f"βοΈ <b>Caption:</b> {s.get('caption','')[:100]}\n"
f"π <b>Redirect:</b> <code>{s.get('redirect_link','')[:60]}</code>\n"
f"π· <b>Category:</b> {s.get('category','β')}\n"
f"πΊ <b>Ads required:</b> {s.get('required_ads', config.DEFAULT_ADS)}\n\n"
f"Confirm or choose distribution:",
parse_mode="v2",
buttons=[
[Button.inline("π’ Send to All Users", b"target_users")],
[Button.inline("π‘ Send to Channels", b"target_channels")],
[Button.inline("π Both", b"target_both")],
[Button.inline("β© Just create, no send", b"target_none")],
*_wizard_step_buttons(back_data=b"wiz_back_to_ads"),
],
)
# MAIN MESSAGE HANDLER
@client.on(events.NewMessage)
async def handle_message(event):
sender_id = event.sender_id
if event.out:
return
# Record all private users
if event.is_private:
user = await event.get_sender()
if hasattr(user, "first_name"):
await record_user(user.id, user.first_name or "", user.username or "")
# Non-owners: only force-sub check
# if not await is_owner_async(sender_id):
# if event.is_private:
# await check_force_sub(event)
# return
state = wizard.get(sender_id)
# ββ Media auto-detect
# ONLY fires when owner is NOT already in any wizard step.
# Also ignores forwarded messages unless there's no active wizard.
if (event.photo or event.video or event.document):
if state is not None:
# Owner is mid-wizard. Is this the image step?
if state.get("step") == "await_image":
# They sent media instead of a URL β upload it
media = event.photo or event.video or event.document
fp = CACHE_DIR / f"{sender_id}_{event.id}.jpg"
await event.client.download_media(media, str(fp))
with open(fp, "rb") as f:
uploaded = await ibb.upload_from_bytes(image_bytes=f.read(), name=str(fp))
url = ibb.get_image_url(uploaded)
os.remove(fp)
wizard[sender_id]["image_url"] = url
wizard[sender_id]["step"] = "await_caption"
try: await event.delete()
except Exception: pass
await edit_wizard_msg(sender_id,
"<b><blockquote>π New Post β Step 2/5</blockquote></b>\n\n"
"β
Image uploaded.\n\n"
"βοΈ Now send the <b>caption / title</b>:",
parse_mode="v2",
buttons=_wizard_step_buttons(back_data=b"wiz_back_to_image"),
)
# In all other steps: silently ignore the media (don't trigger auto-detect)
return
# No active wizard β ask owner if they want to create a post from this media
media = event.photo or event.video or event.document
fp = CACHE_DIR / f"{sender_id}_{event.id}.jpg"
await event.client.download_media(media, str(fp))
with open(fp, "rb") as f:
uploaded = await ibb.upload_from_bytes(image_bytes=f.read(), name=str(fp))
url = ibb.get_image_url(uploaded)
os.remove(fp)
caption_prefill = (event.message.text or event.message.message or "")[:80]
sent = await event.reply(
f"<b><blockquote>πΈ Media detected</blockquote></b>\n"
f"Image uploaded β
\n"
f"Caption prefill: <code>{caption_prefill}</code>\n\n"
f"Create a post from this?",
parse_mode="v2",
buttons=[
[Button.inline("β
", b"media_yes"),
Button.inline("β", b"media_no")],
],
)
# Store state β wizard step is "auto_confirm"
wizard[sender_id] = {
"step": "auto_confirm",
"wizard_msg_id": sent.id,
"wizard_chat_id": sent.chat_id,
"image_url": url,
"caption": caption_prefill,
"from_admin": False,
}
return
# ββ No media β route text to active wizard step
if not state:
return
step = state.get("step")
if step == "await_image":
await _wizard_handle_image_url(event, sender_id)
elif step == "await_caption":
await _wizard_handle_caption(event, sender_id)
elif step == "await_redirect":
await _wizard_handle_redirect(event, sender_id)
elif step == "await_category":
await _wizard_handle_category(event, sender_id)
elif step in ("await_ads", "auto_confirm", "await_target"):
# These are button-driven steps; ignore stray text
pass
# ββ Channel ID input steps
elif step == "await_channel_id_admin":
await _handle_channel_id_input(event, sender_id, state)
elif step == "await_channel_id_remove":
await _handle_channel_remove_input(event, sender_id, state)
elif step == "await_channel_id_direct":
await _handle_channel_id_direct(event, sender_id, state)
# ββ Extra admin input steps
elif step == "await_extra_admin_id":
await _handle_extra_add_admin(event, sender_id, state)
elif step == "await_extra_remove_id":
await _handle_extra_remove_admin(event, sender_id, state)
# ββ Post-delete by hash
elif step == "await_post_hash_for_delete":
await _handle_delete_by_hash(event, sender_id, state)
# For adding request channel (step)
if state and state.get("step") == "await_channel_id_req":
channel_type = state.get("channel_type", "request")
await _handle_channel_input_general(event, sender_id, state, channel_type)
# For adding posting channel (step)
if state and state.get("step") == "await_channel_id_post":
channel_type = state.get("channel_type", "posting")
await _handle_channel_input_general(event, sender_id, state, channel_type)
# For removing request channel
if state and state.get("step") == "await_channel_id_remove_req":
channel_type = "request"
await _handle_channel_remove_general(event, sender_id, state, channel_type)
# For removing posting channel
if state and state.get("step") == "await_channel_id_remove_post":
channel_type = "posting"
await _handle_channel_remove_general(event, sender_id, state, channel_type)
# CHANNEL INPUT HANDLERS
async def _resolve_channel_id(event) -> str | None:
raw = (event.message.text or "").strip()
if event.message.fwd_from:
try:
from_id = event.message.fwd_from.from_id
entity = await client.get_entity(from_id)
if entity:
return f"-100{abs(entity.id)}"
else:
return f"-100{abs(from_id.peer_id)}"
except Exception:
pass
import re
match = re.search(r't\.me/c/(\d+)(?:/\d+)?', raw)
if match:
return f"-100{match.group(1)}"
if re.search(r'https?://t\.me/[^/]+$', raw) or raw.startswith("t.me/"):
link = raw.replace("https://", "").replace("http://", "")
parts = link.split("/")
if len(parts) > 2:
link = parts[0]
try:
entity = await client.get_entity(link)
return f"-100{abs(entity.id)}"
except Exception:
pass
cleaned = raw.lstrip("-")
if cleaned.isdigit():
numeric = raw.lstrip("-")
if numeric.startswith("100"):
numeric = numeric[3:]
return f"-100{numeric}"
return None
async def _handle_channel_id_input(event, sender_id: int, state: dict):
channel_id = await _resolve_channel_id(event)
src_msg_id = state.get("source_msg_id")
src_chat_id = state.get("source_chat_id")
if not channel_id:
await event.reply("β Invalid input. Send a numeric ID, t.me link, or forward from the channel.")
return
added = await db.add_force_sub_channel(channel_id, None)
try: await event.delete()
except Exception: pass
notice = f"β
Channel <code>{channel_id}</code> added." if added else f"β οΈ Channel <code>{channel_id}</code> already exists."
wizard.pop(sender_id, None)
if src_msg_id and src_chat_id:
try:
await client.edit_message(src_chat_id, src_msg_id,
f"<b><blockquote>π’ ForceβSub Channels</blockquote></b>\n\n{notice}\n\nManage channels:",
parse_mode="v2",
buttons=[
[Button.inline("β Add Channel", b"channels_add")],
[Button.inline("π List Channels", b"channels_list")],
[Button.inline("π Remove One Channel", b"channels_remove_one")],
[Button.inline("β οΈ Remove All Channels", b"channels_remove_all")],
[Button.inline("π Back", b"back_to_admin")],
],
)
except MessageNotModifiedError:
pass
except Exception:
await event.reply(notice)
async def _handle_channel_remove_input(event, sender_id: int, state: dict):
channel_id = (event.message.text or "").strip()
removed = await db.remove_force_sub_channel(channel_id)
src_msg_id = state.get("source_msg_id")
src_chat_id = state.get("source_chat_id")
notice = f"β
<code>{channel_id}</code> removed." if removed else f"β <code>{channel_id}</code> not found."
try: await event.delete()
except Exception: pass
wizard.pop(sender_id, None)
if src_msg_id and src_chat_id:
try:
await client.edit_message(src_chat_id, src_msg_id,
f"<b><blockquote>π’ ForceβSub Channels</blockquote></b>\n\n{notice}\n\nManage channels:",
parse_mode="v2",
buttons=[
[Button.inline("β Add Channel", b"channels_add")],
[Button.inline("π List Channels", b"channels_list")],
[Button.inline("π Remove One Channel", b"channels_remove_one")],
[Button.inline("β οΈ Remove All Channels", b"channels_remove_all")],
[Button.inline("π Back", b"back_to_admin")],
],
)
except MessageNotModifiedError:
pass
except Exception:
await event.reply(notice)
async def _handle_channel_id_direct(event, sender_id: int, state: dict):
channel_id = await _resolve_channel_id(event)
if not channel_id:
await event.reply("β Invalid channel ID.")
return
try:
await client.get_entity(int(channel_id))
except Exception as e:
await event.reply(f"β Cannot access channel: {e}")
return
added = await db.add_force_sub_channel(channel_id, "")
notice = f"β
<code>{channel_id}</code> added." if added else f"β οΈ Already exists."
try: await event.delete()
except Exception: pass
wizard.pop(sender_id, None)
src_msg_id = state.get("source_msg_id")
src_chat_id = state.get("source_chat_id")
if src_msg_id and src_chat_id:
try:
await client.edit_message(src_chat_id, src_msg_id,
f"<b><blockquote>π’ ForceβSub Channels</blockquote></b>\n\n{notice}\n\nManage channels:",
parse_mode="v2",
buttons=[
[Button.inline("β Add Channel", b"channels_add")],
[Button.inline("π List Channels", b"channels_list")],
[Button.inline("π Remove One Channel", b"channels_remove_one")],
[Button.inline("β οΈ Remove All Channels", b"channels_remove_all")],
[Button.inline("π Back", b"back_to_admin")],
],
)
except MessageNotModifiedError:
pass
async def _handle_channel_input_general(event, sender_id: int, state: dict, channel_type: str):
"""Generic handler for adding any channel type (request/posting)."""
channel_id = await _resolve_channel_id(event)
src_msg_id = state.get("source_msg_id")
src_chat_id = state.get("source_chat_id")
added_by = sender_id
if not channel_id:
await event.reply("β Invalid input. Send a numeric ID, t.me link, or forward from the channel.")
return
try:
entity = await client.get_entity(int(channel_id))
channel_name = entity.title
except Exception:
channel_name = channel_id
added = await db.add_channel(channel_id, channel_name, added_by, channel_type, "")
try:
await event.delete()
except Exception:
pass
notice = f"β
Channel <code>{channel_id}</code> added as {channel_type}." if added else f"β οΈ Channel already exists."
wizard.pop(sender_id, None)
if src_msg_id and src_chat_id:
try:
if channel_type == "request":
await client.edit_message(src_chat_id, src_msg_id,
f"<b><blockquote>π Request Channels</blockquote></b>\n\n{notice}\n\nManage channels:",
buttons=[
[Button.inline("β Add Request Channel", b"channels_req_add")],
[Button.inline("π List Request Channels", b"channels_req_list")],
[Button.inline("π Remove One", b"channels_req_remove_one")],
[Button.inline("β οΈ Remove All", b"channels_req_remove_all")],
[Button.inline("π Back to Channels", b"channels_back_main")],
], parse_mode="v2")
else:
await client.edit_message(src_chat_id, src_msg_id,
f"<b><blockquote>π‘ Posting Channels</blockquote></b>\n\n{notice}\n\nManage channels:",
buttons=[
[Button.inline("β Add Posting Channel", b"channels_post_add")],
[Button.inline("π List Posting Channels", b"channels_post_list")],
[Button.inline("π Remove One", b"channels_post_remove_one")],
[Button.inline("β οΈ Remove All", b"channels_post_remove_all")],
[Button.inline("π Back to Channels", b"channels_back_main")],
], parse_mode="v2")
except MessageNotModifiedError:
pass
except Exception as e:
await event.reply(notice)
async def _handle_channel_remove_general(event, sender_id: int, state: dict, channel_type: str):
"""Generic handler for removing any channel type."""
channel_id = (event.message.text or "").strip()
removed = await db.remove_channel(channel_id, channel_type)
src_msg_id = state.get("source_msg_id")
src_chat_id = state.get("source_chat_id")
notice = f"β
<code>{channel_id}</code> removed." if removed else f"β <code>{channel_id}</code> not found."
try:
await event.delete()
except Exception:
pass
wizard.pop(sender_id, None)
if src_msg_id and src_chat_id:
try:
if channel_type == "request":
await client.edit_message(src_chat_id, src_msg_id,
f"<b><blockquote>π Request Channels</blockquote></b>\n\n{notice}\n\nManage channels:",
buttons=[
[Button.inline("β Add Request Channel", b"channels_req_add")],
[Button.inline("π List Request Channels", b"channels_req_list")],
[Button.inline("π Remove One", b"channels_req_remove_one")],
[Button.inline("β οΈ Remove All", b"channels_req_remove_all")],
[Button.inline("π Back to Channels", b"channels_back_main")],
], parse_mode="v2")
else:
await client.edit_message(src_chat_id, src_msg_id,
f"<b><blockquote>π‘ Posting Channels</blockquote></b>\n\n{notice}\n\nManage channels:",
buttons=[
[Button.inline("β Add Posting Channel", b"channels_post_add")],
[Button.inline("π List Posting Channels", b"channels_post_list")],
[Button.inline("π Remove One", b"channels_post_remove_one")],
[Button.inline("β οΈ Remove All", b"channels_post_remove_all")],
[Button.inline("π Back to Channels", b"channels_back_main")],
], parse_mode="v2")
except MessageNotModifiedError:
pass
except Exception as e:
await event.reply(notice)
# EXTRA ADMIN INPUT HANDLERS
async def _handle_extra_add_admin(event, sender_id: int, state: dict):
raw = (event.message.text or "").strip()
if not raw.isdigit():
await event.reply("β Invalid user ID. Must be a number.")
return
new_id = int(raw)
extra_s = await db.get_setting("extra_owners", "[]")
try: extra = json.loads(extra_s)
except Exception: extra = []
notice = f"β οΈ <code>{new_id}</code> is already an admin." if new_id in extra else f"β
<code>{new_id}</code> added as admin."
if new_id not in extra:
extra.append(new_id)
await db.set_setting("extra_owners", json.dumps(extra))
try: await event.delete()
except Exception: pass
wizard.pop(sender_id, None)
src_msg_id = state.get("source_msg_id")
src_chat_id = state.get("source_chat_id")
if src_msg_id and src_chat_id:
try:
await client.edit_message(src_chat_id, src_msg_id,
f"<b><blockquote>π§ Extra Admin Settings</blockquote></b>\n\n{notice}\n\nManage additional admins:",
parse_mode="v2",
buttons=[
[Button.inline("β Add Admin", b"extra_add_admin")],
[Button.inline("π Remove Admin", b"extra_remove_admin")],
[Button.inline("β οΈ Remove All Extra Admins", b"extra_remove_all_admins")],
[Button.inline("π Back", b"back_to_admin")],
],
)
except MessageNotModifiedError:
pass
async def _handle_extra_remove_admin(event, sender_id: int, state: dict):
raw = (event.message.text or "").strip()
if not raw.isdigit():
await event.reply("β Invalid user ID.")
return
rem_id = int(raw)
extra_s = await db.get_setting("extra_owners", "[]")
try: extra = json.loads(extra_s)
except Exception: extra = []
if rem_id not in extra:
notice = f"β οΈ <code>{rem_id}</code> is not an extra admin."
else:
extra.remove(rem_id)
await db.set_setting("extra_owners", json.dumps(extra))
notice = f"β
<code>{rem_id}</code> removed."
try: await event.delete()
except Exception: pass
wizard.pop(sender_id, None)
src_msg_id = state.get("source_msg_id")
src_chat_id = state.get("source_chat_id")
if src_msg_id and src_chat_id:
try:
await client.edit_message(src_chat_id, src_msg_id,
f"<b><blockquote>π§ Extra Admin Settings</blockquote></b>\n\n{notice}\n\nManage additional admins:",
parse_mode="v2",
buttons=[
[Button.inline("β Add Admin", b"extra_add_admin")],
[Button.inline("π Remove Admin", b"extra_remove_admin")],
[Button.inline("β οΈ Remove All Extra Admins", b"extra_remove_all_admins")],
[Button.inline("π Back", b"back_to_admin")],
],
)
except MessageNotModifiedError:
pass
async def _handle_delete_by_hash(event, sender_id: int, state: dict):
magical_hash = (event.message.text or "").strip()
# Use _any variant so we can delete even soft-deleted posts
post = await db.get_post_by_hash_any(magical_hash)
src_msg_id = state.get("source_msg_id")
src_chat_id = state.get("source_chat_id")
if not post:
notice = f"β Post <code>{magical_hash}</code> not found."
else:
await db.soft_delete_post(post["_id"])
notice = f"β
Post <code>{magical_hash}</code> deleted."
try: await event.delete()
except Exception: pass
wizard.pop(sender_id, None)
if src_msg_id and src_chat_id:
try:
await client.edit_message(src_chat_id, src_msg_id,
f"<b><blockquote>π Post Management</blockquote></b>\n\n{notice}",
parse_mode="v2",
buttons=[
[Button.inline("β Create New Post", b"posts_create")],
[Button.inline("π List Active Posts", b"posts_list_edit")],
[Button.inline("π Remove One Post", b"posts_remove_one")],
[Button.inline("β οΈ Remove All Posts", b"posts_remove_all")],
[Button.inline("πΎ Backup Posts", b"posts_backup")],
[Button.inline("π Back", b"back_to_admin")],
],
)
except MessageNotModifiedError:
pass
# FINALIZE POST
async def finalize_post(event, user_id: int, target: str):
s = wizard.pop(user_id, None)
if not s:
await event.answer("State lost. Start again.", alert=True)
return
try:
magical_hash = generate_hash()
post = await db.create_post(
magical_hash = magical_hash,
image_url = s.get("image_url", ""),
caption = s.get("caption", ""),
redirect_link = s.get("redirect_link", ""),
required_ads = s.get("required_ads", config.DEFAULT_ADS),
category = s.get("category", ""),
)
username = await get_bot_username()
link = make_link(magical_hash, username)
if target in ("users", "both"):
asyncio.ensure_future(send_post_to_all_users(post, link))
if target in ("channels", "both"):
asyncio.ensure_future(send_post_to_all_channels(post, link))
await safe_edit(event,
f"<b><blockquote>β
Post created!</blockquote></b>\n\n"
f"π Hash: <code>{magical_hash}</code>\n"
f"π <a href='{link}'>Open in Mini App</a>\n"
f"π Target: <b>{target}</b>",
parse_mode="v2",
buttons=[
[Button.url("π Open", link)],
[Button.inline("π Posts Menu", b"admin_posts"),
Button.inline("β New Post", b"posts_create")],
],
)
except Exception as e:
await safe_edit(event, f"β Error creating post: {e}")
# POST LIST β only active posts
async def _fetch_active_posts() -> list:
"""Only active posts for listing in admin panel."""
return await db.list_all_posts_admin(limit=500)
async def send_post_page(event, posts: list, page: int = 0):
per_page = 8
total = len(posts)
start = page * per_page
end = start + per_page
page_posts = posts[start:end]
if not page_posts and page > 0:
page -= 1
start = page * per_page
end = start + per_page
page_posts = posts[start:end]
total_pages = max(1, (total + per_page - 1) // per_page)
lines = [f"<b><blockquote>π Active Posts β Page {page+1}/{total_pages}</blockquote></b>\n"]
for p in page_posts:
active_marker = "π’" if p.get("is_active") else "π΄"
lines.append(f"{active_marker} <code>{p['magical_hash']}</code> β {p.get('caption','')[:40]}β¦")
lines.append("\n\n<i>PS: Presseing button below will delete the selected post!</i>")
buttons = []
for p in page_posts:
buttons.append([Button.inline(
f"π {p['magical_hash'][:10]}",
f"delpost:{p['magical_hash']}".encode()
)])
nav = []
if page > 0:
nav.append(Button.inline("β Prev", f"listposts_page:{page-1}".encode()))
if end < total:
nav.append(Button.inline("Next βΆ", f"listposts_page:{page+1}".encode()))
if nav:
buttons.append(nav)
buttons.append([Button.inline("π Back to Posts", b"admin_posts")])
await safe_edit(event, "\n".join(lines), parse_mode="v2", buttons=buttons)
# Store pagination state
wizard[event.sender_id] = {
**wizard.get(event.sender_id, {}),
"list_posts": posts,
"list_msg_id": event.message_id,
"list_chat_id": event.chat_id,
}
# BROADCAST / SEND TO USERS / CHANNELS
async def broadcast_to_channels(message: Message) -> dict:
result = {"total": 0, "success": 0, "failed": 0, "details": []}
channels = await db.get_channels(channel_type="posting")
if not channels:
result["details"].append("No force-sub channels configured.")
return result
result["total"] = len(channels)
for ch in channels:
try:
await client.send_message(
int(ch["channel_id"]),
message.text or "Broadcast",
file=message.media,
link_preview=False
)
result["success"] += 1
result["details"].append(f"β
{ch['channel_id']}")
except Exception as e:
result["failed"] += 1
result["details"].append(f"β {ch['channel_id']}: {str(e)[:50]}")
return result
#added failsafe and remove dead users
async def send_post_to_all_users(post: dict, miniapp_link: str):
users = await db.get_all_users()
queue = asyncio.Queue()
for user in users:
await queue.put(user["telegram_id"])
sent = 0
failed = 0
removed = 0
while not queue.empty():
tg_id = await queue.get()
if tg_id in config.OWNER_IDS:
continue
try:
await client.send_message(
tg_id,
f"<b><blockquote>β¨ New content available!</blockquote></b>\n\n"
f"<b>{post.get('caption','')}</b>\nTap below to open:",
parse_mode="html",
file=post.get("image_url"),
buttons=[
Button.url("π₯΅ CHECK MORE π₯΅", miniapp_link),
Button.url("π₯ WATCH NOW π₯", post.get("redirect_link"))
],
)
sent += 1
await asyncio.sleep(0.5)
except FloodWaitError as e:
wait_time = e.seconds + 1
log.warning("FloodWait %ds, pausing before retrying user %s", wait_time, tg_id)
await asyncio.sleep(wait_time)
await queue.put(tg_id) # retry same user after wait
except (UserIsBlockedError, InputUserDeactivatedError, UserDeactivatedBanError, PeerIdInvalidError):
await db.remove_user(tg_id)
removed += 1
log.info("Removed dead user %s", tg_id)
await asyncio.sleep(2)
except Exception as e:
failed += 1
log.warning("Failed to send to user %s: %s", tg_id, e)
await asyncio.sleep(2)
finally:
queue.task_done()
log.info("Broadcast done. Sent=%d Failed=%d Removed=%d", sent, failed, removed)
async def send_post_to_all_channels(post: dict, miniapp_link: str):
channels = await db.get_channels(channel_type="posting")
for ch in channels:
try:
await client.send_message(int(ch["channel_id"]),
f"<b><blockquote>π New Post</blockquote></b>\n\n"
f"<b>{post.get('caption','')}</b>\n<i>tap below to watch</i>",
file=post.get("image_url"),
parse_mode="v2",
link_preview=False,
buttons=[
Button.url("π₯΅ WATCH NOW π₯", miniapp_link),
Button.url("πΆοΈ OPEN NOW π", post.get("redirect_link"))
],
)
except Exception as e:
log.warning("Failed to send to channel %s: %s", ch["channel_id"], e)
# MAIN CALLBACK HANDLER
@client.on(events.CallbackQuery)
async def callback_handler(event):
data = event.data
user_id = event.sender_id
# startup things
if data == b"check_sub":
passed = await check_force_sub(event)
if passed:
await event.answer("β
All good!", alert=False)
# Delete the force-sub message
try:
await client.delete_messages(event.chat_id, event.message_id)
except Exception as e:
log.warning("Could not delete force-sub message: %s", e)
await send_start(event)
else:
await event.answer("β Still not joined all channels.", alert=True)
return
if not await is_owner_async(user_id):
await event.answer("Owner only.", alert=True)
return
await event.answer()
if data == b"admin_hint":
if not await is_owner_async(event.sender_id):
await event.answer("Owner only.", alert=True)
return
await send_admin_panel(event, edit=True)
# ββ Universal back buttons
if data == b"back_to_admin":
wizard.pop(user_id, None)
await render_admin_panel(event)
return
if data == b"back_to_posts":
await render_posts_menu(event)
return
if data == b"back_to_channels":
await render_channels_menu(event)
return
if data == b"back_to_extra":
await render_extra_menu(event)
return
# ββ Admin panel
if data == b"admin_hint":
await render_admin_panel(event)
return
if data == b"admin_posts":
await render_posts_menu(event)
return
if data == b"admin_channels":
await render_channels_menu(event)
return
if data == b"admin_stats":
await render_stats(event)
return
if data == b"admin_extra":
await render_extra_menu(event)
return
if data == b"admin_close":
await safe_edit(event, "π Panel closed.", buttons=None)
return
# ββ Public stat / browse
if data == b"public_stats":
total = await db.count_active_posts()
unlocks = await db.total_unlocks()
views = await db.total_views()
await event.reply(
f"<b><blockquote>π Public Stats</blockquote></b>\n\n"
f"π Active posts: <b>{total}</b>\n"
f"π Total views: <b>{views}</b>\n"
f"π Total unlocks: <b>{unlocks}</b>",
parse_mode="v2",
)
return
if data == b"browse":
bot_username = await get_bot_username()
await event.reply(
"π Browse all posts:",
buttons=[[Button.url("π Open App", f"https://t.me/{bot_username}/app")]],
)
return
# ββ Posts sub-menu
if data == b"posts_create":
await _start_wizard(event, from_admin_panel=True)
return
if data == b"posts_list_edit":
posts = await _fetch_active_posts()
if not posts:
await safe_edit(event, "No active posts.",
parse_mode="v2",
buttons=[[Button.inline("π Back", b"admin_posts")]],
)
return
await send_post_page(event, posts, page=0)
return
if data.startswith(b"listposts_page:"):
page = int(data.decode().split(":")[1])
state = wizard.get(user_id, {})
posts = state.get("list_posts") or await _fetch_active_posts()
await send_post_page(event, posts, page=page)
return
if data == b"posts_remove_one":
wizard[user_id] = {
"step": "await_post_hash_for_delete",
"source_msg_id": event.message_id,
"source_chat_id": event.chat_id,
}
await safe_edit(event,
"<b><blockquote>π Remove Post</blockquote></b>\n\nSend the magical hash of the post to delete:",
parse_mode="v2",
buttons=[[Button.inline("π Back", b"admin_posts")]],
)
return
if data == b"posts_remove_all":
await safe_edit(event,
"β οΈ Delete ALL posts? This cannot be undone.",
buttons=[
[Button.inline("β
Yes, delete all", b"posts_delete_all_confirm")],
[Button.inline("β No", b"admin_posts")],
],
)
return
if data == b"posts_delete_all_confirm":
await db.posts_col().update_many({}, {"$set": {"is_active": False}})
await safe_edit(event,
"β
All posts deactivated.",
buttons=[[Button.inline("π Back to Posts", b"admin_posts")]],
)
return
if data == b"posts_backup":
await _do_backup(event)
return
# delpost: magical_hash
if data.startswith(b"delpost:"):
magical_hash = data.decode().split(":", 1)[1]
# Use _any so it works even if already soft-deleted (shows proper message)
post = await db.get_post_by_hash_any(magical_hash)
if post and post.get("is_active"):
await db.soft_delete_post(post["_id"])
await event.answer(f"Deleted: {magical_hash[:10]}", alert=False)
elif post and not post.get("is_active"):
await event.answer("Already deleted.", alert=False)
else:
await event.answer("Not found.", alert=True)
# Refresh the post list
posts = await _fetch_active_posts()
if posts:
await send_post_page(event, posts, page=0)
else:
await safe_edit(event,
"β
No active posts remaining.",
buttons=[[Button.inline("π Back to Posts", b"admin_posts")]],
)
return
# ββ Channels sub-menu
if data == b"channels_add":
wizard[user_id] = {
"step": "await_channel_id_admin",
"source_msg_id": event.message_id,
"source_chat_id": event.chat_id,
}
await safe_edit(event,
"Send the channel ID (e.g., <code>-1001234567890</code>), a t.me link, or forward a message from the channel:",
parse_mode="v2",
buttons=[[Button.inline("π Back", b"back_to_channels")]],
)
return
if data == b"back_to_channels":
wizard.pop(user_id, None)
await render_channels_menu(event)
return
if data == b"channels_list":
channels = await db.get_channels(channel_type="posting")
if not channels:
await safe_edit(event, "No forceβsub channels configured.",
buttons=[[Button.inline("π Back", b"admin_channels")]],
)
return
lines = ["<b>π Force-sub channels:</b>\n"]
for ch in channels:
lines.append(
f"β’ <code>{ch.get('channel_name')}</code> β {ch.get('channel_id')}"
)
await safe_edit(event, "\n".join(lines),
parse_mode="v2",
buttons=[[Button.inline("π Back", b"admin_channels")]],
)
return
if data == b"channels_remove_one":
wizard[user_id] = {
"step": "await_channel_id_remove",
"source_msg_id": event.message_id,
"source_chat_id": event.chat_id,
}
await safe_edit(event,
"Send the channel ID to remove:",
buttons=[[Button.inline("π Back", b"admin_channels")]],
)
return
if data == b"channels_remove_all":
await safe_edit(event,
"β οΈ Remove ALL forceβsub channels?",
buttons=[
[Button.inline("β
Yes", b"channels_delete_all_confirm")],
[Button.inline("β No", b"admin_channels")],
],
)
return
if data == b"channels_delete_all_confirm":
await db.channels_col().delete_many({})
await safe_edit(event, "β
All channels removed.",
buttons=[[Button.inline("π Back", b"admin_channels")]],
)
return
# ββ Extra sub-menu
if data == b"extra_add_admin":
wizard[user_id] = {
"step": "await_extra_admin_id",
"source_msg_id": event.message_id,
"source_chat_id": event.chat_id,
}
await safe_edit(event,
"Send the Telegram user ID to add as admin:",
buttons=[[Button.inline("π Back", b"admin_extra")]],
)
return
if data == b"extra_remove_admin":
wizard[user_id] = {
"step": "await_extra_remove_id",
"source_msg_id": event.message_id,
"source_chat_id": event.chat_id,
}
await safe_edit(event,
"Send the Telegram user ID to remove from admins:",
buttons=[[Button.inline("π Back", b"admin_extra")]],
)
return
if data == b"extra_remove_all_admins":
await safe_edit(event,
"β οΈ Remove ALL extra admins?",
buttons=[
[Button.inline("β
Yes", b"extra_delete_all_confirm")],
[Button.inline("β No", b"admin_extra")],
],
)
return
if data == b"extra_delete_all_confirm":
await db.set_setting("extra_owners", "[]")
await safe_edit(event,
"β
All extra admins removed.",
buttons=[[Button.inline("π Back", b"admin_extra")]],
)
return
# ββ Wizard callbacks
if data == b"media_yes":
state = wizard.get(user_id, {})
if state.get("step") != "auto_confirm":
return
wizard[user_id]["step"] = "await_caption"
# If caption was pre-filled from the media message, skip to next step
if state.get("caption"):
wizard[user_id]["step"] = "await_redirect"
await safe_edit(event,
f"<b><blockquote>π New Post β Step 3/5</blockquote></b>\n\n"
f"Caption pre-filled: <code>{state['caption'][:80]}</code>\n\n"
f"π Now send the <b>redirect URL</b>:",
parse_mode="v2",
buttons=_wizard_step_buttons(back_data=b"wiz_back_to_caption"),
)
else:
await safe_edit(event,
"<b><blockquote>π New Post β Step 2/5</blockquote></b>\n\nβοΈ Send the <b>caption</b>:",
parse_mode="v2",
buttons=_wizard_step_buttons(back_data=b"wiz_back_to_image"),
)
return
if data == b"media_no":
wizard.pop(user_id, None)
await safe_edit(event, "β Cancelled.")
return
if data == b"post_cancel":
wizard.pop(user_id, None)
await safe_edit(event,
"β Post creation cancelled.",
buttons=[[Button.inline("π Posts Menu", b"admin_posts")]],
)
return
# ββ Wizard back navigation
if data == b"wiz_back_to_image":
state = wizard.get(user_id, {})
wizard[user_id] = {**state, "step": "await_image", "image_url": None}
await safe_edit(event,
"<b><blockquote>π New Post β Step 1/5</blockquote></b>\n\n"
"πΈ Send the <b>image URL</b>:",
parse_mode="v2", buttons=_wizard_cancel_buttons(),
)
return
if data == b"wiz_back_to_caption":
state = wizard.get(user_id, {})
wizard[user_id] = {**state, "step": "await_caption"}
await safe_edit(event,
"<b><blockquote>π New Post β Step 2/5</blockquote></b>\n\nβοΈ Send the <b>caption</b>:",
parse_mode="v2",
buttons=_wizard_step_buttons(back_data=b"wiz_back_to_image"),
)
return
if data == b"wiz_back_to_redirect":
state = wizard.get(user_id, {})
wizard[user_id] = {**state, "step": "await_redirect"}
await safe_edit(event,
"<b><blockquote>π New Post β Step 3/5</blockquote></b>\n\nπ Send the <b>redirect URL</b>:",
parse_mode="v2",
buttons=_wizard_step_buttons(back_data=b"wiz_back_to_caption"),
)
return
if data == b"wiz_back_to_category":
state = wizard.get(user_id, {})
wizard[user_id] = {**state, "step": "await_category"}
await safe_edit(event,
"<b><blockquote>π New Post β Step 4/5</blockquote></b>\n\nπ· Send the <b>category</b> or skip:",
parse_mode="v2",
buttons=[
[Button.inline("β© Skip", b"wiz_skip_category")],
*_wizard_step_buttons(back_data=b"wiz_back_to_redirect"),
],
)
return
if data == b"wiz_back_to_ads":
state = wizard.get(user_id, {})
wizard[user_id] = {**state, "step": "await_ads"}
await _show_ads_step(user_id)
return
if data == b"wiz_skip_category":
wizard[user_id]["category"] = ""
wizard[user_id]["step"] = "await_ads"
await _show_ads_step(user_id)
return
# ββ Wizard: ads count
_ads_map = {
b"wiz_ads_1": 1,
b"wiz_ads_2": 2,
b"wiz_ads_3": 3,
b"wiz_ads_default": config.DEFAULT_ADS,
b"wiz_ads_0": 0,
}
if data in _ads_map:
wizard[user_id]["required_ads"] = _ads_map[data]
wizard[user_id]["step"] = "await_target"
await _show_confirm_step(user_id)
return
# ββ Wizard: target / finalize
_target_map = {
b"target_users": "users",
b"target_channels": "channels",
b"target_both": "both",
b"target_none": "none",
}
if data in _target_map:
await finalize_post(event, user_id, target=_target_map[data])
return
# ββ Broadcast
if data == b"broadcast_confirm":
state = wizard.get(user_id, {})
if "broadcast_msg_id" not in state:
await event.answer("No broadcast pending.", alert=True)
return
try:
orig_msg = await client.get_messages(state["chat_id"], ids=state["broadcast_msg_id"])
if not orig_msg:
await safe_edit(event, "Original message not found.")
return
await safe_edit(event, "<b>π’ Broadcastingβ¦</b>", parse_mode="v2")
result = await broadcast_to_channels(orig_msg)
await safe_edit(event,
f"<b><blockquote>β
Broadcast done</blockquote></b>\n\n"
f"β’ Total: {result['total']}\n"
f"β’ Success: {result['success']}\n"
f"β’ Failed: {result['failed']}",
parse_mode="v2",
)
except Exception as e:
await safe_edit(event, f"β Error: {e}")
finally:
wizard.pop(user_id, None)
return
if data == b"broadcast_cancel":
wizard.pop(user_id, None)
await safe_edit(event, "β Broadcast cancelled.")
return
if data == b"flush_confirm":
user_id = event.sender_id
state = wizard.get(user_id, {})
deleted = await flush_all_posts()
wizard.pop(user_id, None)
await event.edit(
f"<b><blockquote>β
Flush Complete</blockquote></b>\n\n"
f"Deleted <b>{deleted}</b> posts permanently.",
parse_mode="v2",
buttons=None,
)
if data == b"flush_cancel":
user_id = event.sender_id
wizard.pop(user_id, None)
await event.edit("β Flush cancelled.", buttons=None)
if data.startswith(b"set_req:"):
channel_id = data.decode().split(":", 1)[1]
added = await db.add_force_sub_channel(channel_id, "")
if added:
await event.answer("β
Added as request (force-sub) channel!", alert=True)
await event.edit("Channel added as request channel. Users will need to join before using the bot.")
else:
await event.answer("β Channel already exists!", alert=True)
if data.startswith(b"set_post:"):
channel_id = data.decode().split(":", 1)[1]
channel_name = (await event.client.get_entity(channel_id)).title
added = await db.add_posting_channel(channel_id, channel_name, "")
if added:
await event.answer("β
Added as posting channel!", alert=True)
await event.edit("Channel added as posting channel. New posts will be sent here automatically.")
else:
await event.answer("β Channel already exists!", alert=True)
if data.startswith(b"ignore:"):
channel_id = data.decode().split(":", 1)[1]
await event.answer("Ignored.", alert=True)
await event.edit("Channel ignored. No further action will be taken.")
# ββ Channels menu navigation ββ
if data == b"channel_menu_req":
await render_req_channels_menu(event)
if data == b"channel_menu_post":
await render_post_channels_menu(event)
if data == b"channels_back_main":
await render_channels_menu(event)
# ββ Request channel actions ββ
if data == b"channels_req_add":
wizard[user_id] = {
"step": "await_channel_id_req",
"source_msg_id": event.message_id,
"source_chat_id": event.chat_id,
"channel_type": "request",
}
await safe_edit(event,
"Send the channel ID (e.g., -1001234567890), t.me link, or forward a message:",
buttons=[[Button.inline("π Back", b"channels_back_main")]],
)
if data == b"channels_req_list":
channels = await db.get_channels(channel_type="request")
if not channels:
await safe_edit(event, "No request channels configured.",
buttons=[[Button.inline("π Back", b"channel_menu_req")]])
return
lines = ["<b>π Request Channels:</b>\n"]
for ch in channels:
lines.append(
f"β’ <code>{ch.get('channel_name')}</code> β {ch.get('channel_id')}"
)
await safe_edit(event, "\n".join(lines),
parse_mode="v2",
buttons=[[Button.inline("π Back", b"channel_menu_req")]],
)
if data == b"channels_post_list":
channels = await db.get_channels(channel_type="posting")
if not channels:
await safe_edit(event, "No posting channels configured.",
buttons=[[Button.inline("π Back", b"channel_menu_post")]])
return
lines = ["<b>π‘ Posting Channels:</b>\n"]
for ch in channels:
lines.append(
f"β’ <code>{ch.get('channel_name')}</code> β {ch.get('channel_id')}"
)
await safe_edit(event, "\n".join(lines),
parse_mode="v2",
buttons=[[Button.inline("π Back", b"channel_menu_post")]],
)
return
if data == b"channels_req_remove_one":
wizard[user_id] = {
"step": "await_channel_id_remove",
"source_msg_id": event.message_id,
"source_chat_id": event.chat_id,
"channel_type": "request",
}
await safe_edit(event,
"Send the channel ID to remove:",
buttons=[[Button.inline("π Back", b"channel_menu_req")]],
)
if data == b"channels_req_remove_all":
await safe_edit(event,
"β οΈ Remove ALL request channels?",
buttons=[
[Button.inline("β
Yes", b"channels_req_delete_all_confirm")],
[Button.inline("β No", b"channel_menu_req")],
],
)
if data == b"channels_req_delete_all_confirm":
await db.remove_all_channels("request")
await safe_edit(event, "β
All request channels removed.",
buttons=[[Button.inline("π Back", b"channel_menu_req")]],
)
# ββ posting channel actions ββ
if data == b"channels_post_add":
wizard[user_id] = {
"step": "await_channel_id_post",
"source_msg_id": event.message_id,
"source_chat_id": event.chat_id,
"channel_type": "posting",
}
await safe_edit(event,
"Send the channel ID (e.g., -1001234567890), t.me link, or forward a message:",
buttons=[[Button.inline("π Back", b"channels_back_main")]],
)
if data == b"channels_post_remove_one":
wizard[user_id] = {
"step": "await_channel_id_remove",
"source_msg_id": event.message_id,
"source_chat_id": event.chat_id,
"channel_type": "posting",
}
await safe_edit(event,
"Send the channel ID to remove:",
buttons=[[Button.inline("π Back", b"channel_menu_req")]],
)
if data == b"channels_post_remove_all":
await safe_edit(event,
"β οΈ Remove ALL posting channels?",
buttons=[
[Button.inline("β
Yes", b"channels_post_delete_all_confirm")],
[Button.inline("β No", b"channel_menu_req")],
],
)
if data == b"channels_post_delete_all_confirm":
await db.remove_all_channels("posting")
await safe_edit(event, "β
All posting channels removed.",
buttons=[[Button.inline("π Back", b"channel_menu_req")]],
)
# COMMANDS
@client.on(events.NewMessage(pattern="/stats"))
async def cmd_stats(event):
if not await is_owner_async(event.sender_id):
return
total = await db.count_active_posts()
unlocks = await db.total_unlocks()
views = await db.total_views()
users = await db.unique_users()
await event.reply(
f"<b><blockquote>π Bot Stats</blockquote></b>\n\n"
f"π Active posts: <code>{total}</code>\n"
f"π Total views: <code>{views}</code>\n"
f"π Total unlocks: <code>{unlocks}</code>\n"
f"π€ Unique users: <code>{users}</code>",
parse_mode="v2",
)
raise events.StopPropagation
@client.on(events.NewMessage(pattern="/listposts"))
async def cmd_listposts(event):
if not await is_owner_async(event.sender_id):
return
posts = await _fetch_active_posts()
if not posts:
await event.reply("No active posts.")
return
sent = await event.reply("Loadingβ¦")
# Fake a callback event so send_post_page can edit that message
class _FakeEvent:
sender_id = event.sender_id
message_id = sent.id
chat_id = sent.chat_id
async def edit(self, *a, **kw): await sent.edit(*a, **kw)
await send_post_page(_FakeEvent(), posts, page=0)
raise events.StopPropagation
@client.on(events.NewMessage(pattern="/deletepost(?:\\s+(\\w+))?"))
async def cmd_deletepost(event):
if not await is_owner_async(event.sender_id):
return
parts = event.message.text.split(maxsplit=1)
if len(parts) < 2:
await event.reply("Usage: /deletepost <magical_hash>")
return
mh = parts[1].strip()
post = await db.get_post_by_hash_any(mh)
if not post:
await event.reply(f"β Post <code>{mh}</code> not found.", parse_mode="v2")
return
await db.soft_delete_post(post["_id"])
await event.reply(f"β
Post <code>{mh}</code> deleted.", parse_mode="v2")
@client.on(events.NewMessage(pattern="/add_channel"))
async def cmd_add_channel(event):
if not await is_owner_async(event.sender_id):
return
await event.reply(
"<b><blockquote>β Add ForceβSub Channel</blockquote></b>\n\nChoose:",
parse_mode="v2",
buttons=[
[Button.inline("β
Add Channel", b"add_channel_start")],
[Button.inline("β Cancel", b"add_channel_cancel")],
],
)
raise events.StopPropagation
@client.on(events.CallbackQuery(data=b"add_channel_start"))
async def cb_add_channel_start(event):
if not await is_owner_async(event.sender_id):
return
wizard[event.sender_id] = {
"step": "await_channel_id_direct",
"source_msg_id": event.message_id,
"source_chat_id": event.chat_id,
}
await safe_edit(event,
"Send the channel ID (e.g., <code>-1001234567890</code>) or forward a message:",
parse_mode="v2",
buttons=[[Button.inline("β Cancel", b"add_channel_cancel")]],
)
@client.on(events.CallbackQuery(data=b"add_channel_cancel"))
async def cb_add_channel_cancel(event):
wizard.pop(event.sender_id, None)
await safe_edit(event, "β Cancelled.")
@client.on(events.NewMessage(pattern="/remove_channel"))
async def cmd_remove_channel(event):
if not await is_owner_async(event.sender_id):
return
channels = await db.get_force_sub_channels()
if not channels:
await event.reply("No channels configured.")
return
buttons = [
[Button.inline(f"π {ch['channel_id']}", f"del_ch:{ch['channel_id']}".encode())]
for ch in channels
]
await event.reply("Select channel to remove:", buttons=buttons)
raise events.StopPropagation
@client.on(events.CallbackQuery(pattern=rb"del_ch:(.+)"))
async def handle_del_channel(event):
if not await is_owner_async(event.sender_id):
return
channel_id = event.pattern_match.group(1).decode()
removed = await db.remove_force_sub_channel(channel_id)
await event.answer(f"β
Removed {channel_id}" if removed else "Not found.", alert=not removed)
if removed:
await safe_edit(event, f"β
Removed <code>{channel_id}</code>.", parse_mode="v2")
@client.on(events.NewMessage(pattern="/list_channels"))
async def cmd_list_channels(event):
if not await is_owner_async(event.sender_id):
return
channels = await db.get_force_sub_channels()
if not channels:
await event.reply("No force-sub channels configured.")
return
lines = ["π <b>Force-sub channels:</b>\n"]
for ch in channels:
lines.append(
f"β’ <code>{ch.get('channel_name')}</code> β {ch.get('channel_id')}"
)
await event.reply("\n".join(lines), parse_mode="v2")
raise events.StopPropagation
@client.on(events.NewMessage(pattern="/broadcast"))
async def cmd_broadcast(event):
if not await is_owner_async(event.sender_id):
return
if not event.message.reply_to_msg_id:
await event.reply("Reply to a message with /broadcast to send it to all channels.")
return
reply_msg = await event.get_reply_message()
if not reply_msg:
await event.reply("Reply message not found.")
return
wizard[event.sender_id] = {
"step": "broadcast_confirm",
"broadcast_msg_id": reply_msg.id,
"chat_id": event.chat_id,
}
await event.reply(
f"<b><blockquote>π’ Confirm Broadcast</blockquote></b>\n\n"
f"<blockquote>{reply_msg.text[:200]}</blockquote>\n\n"
f"Send to ALL channels where bot is admin?",
parse_mode="v2",
buttons=[
[Button.inline("β
Yes, Broadcast", b"broadcast_confirm")],
[Button.inline("β Cancel", b"broadcast_cancel")],
],
)
raise events.StopPropagation
@client.on(events.NewMessage(pattern="/backup"))
async def cmd_backup(event):
if not await is_owner_async(event.sender_id):
return
await _do_backup(event)
raise events.StopPropagation
async def _do_backup(event):
await event.reply("<b>β³ Exportingβ¦</b>", parse_mode="v2")
collections = ["posts", "unlocks", "views", "force_sub_channels", "settings", "users"]
backup_data = {}
for col in collections:
docs = await db.get_collection(col).find().to_list(length=None)
for doc in docs:
doc["_id"] = str(doc["_id"])
backup_data[col] = docs
fname = f"backup_{datetime.utcnow().strftime('%Y%m%d_%H%M%S')}.json"
with open(fname, "w") as f:
json.dump(backup_data, f, indent=2, default=str)
await event.reply(
f"<b><blockquote>β
Backup complete</blockquote></b>\nFile: <code>{fname}</code>",
parse_mode="v2",
file=fname,
)
os.remove(fname)
@client.on(events.NewMessage(pattern="/addowner"))
async def cmd_add_owner(event):
if not await is_owner_async(event.sender_id):
return
parts = event.message.text.split()
if len(parts) != 2 or not parts[1].isdigit():
await event.reply("Usage: /addowner <telegram_user_id>")
return
new_id = int(parts[1])
extra_s = await db.get_setting("extra_owners", "[]")
try: extra = json.loads(extra_s)
except Exception: extra = []
if new_id in extra:
await event.reply(f"β οΈ <code>{new_id}</code> is already an owner.", parse_mode="v2")
return
extra.append(new_id)
await db.set_setting("extra_owners", json.dumps(extra))
await event.reply(f"β
<code>{new_id}</code> added as owner.", parse_mode="v2")
raise events.StopPropagation
@client.on(events.NewMessage(pattern="/update_links"))
async def cmd_update_links(event):
if not await is_owner_async(event.sender_id):
return
msg = await event.reply("π Updating invite linksβ¦")
channels = await db.get_channels() # all types
updated = 0
bot_me = await client.get_me()
for ch in channels:
cid = ch["channel_id"] # keep as string β matches DB
channel_type = ch.get("type", "request")
try:
p = await client(GetParticipantRequest(int(cid), bot_me.id))
if not isinstance(p.participant, (ChannelParticipantAdmin, ChannelParticipantCreator)):
continue
# Revoke old link if exists
old_link = ch.get("invite_link", "")
if old_link:
try:
from telethon.tl.functions.messages import EditExportedChatInviteRequest
await client(EditExportedChatInviteRequest(
peer=int(cid),
link=old_link,
revoked=True,
))
except Exception as e:
log.warning("Could not revoke old link %s: %s", old_link, e)
# Generate fresh link
inv = await client(ExportChatInviteRequest(
peer=int(cid),
legacy_revoke_permanent=False,
request_needed=True,
usage_limit=0,
))
new_link = inv.link
if new_link and new_link != old_link:
await db.update_channel_invite_link(cid, channel_type, new_link)
updated += 1
except Exception as e:
log.error("update_links error for %s: %s", cid, e)
await msg.edit(f"β
Updated {updated} invite link(s)." if updated else "β οΈ No links updated.")
@client.on(events.NewMessage(pattern="/help"))
async def cmd_help(event):
if not await is_owner_async(event.sender_id):
return
await event.reply(
"<b><blockquote>π€ Bot Owner Commands</blockquote></b>\n\n"
"<b>π Post Management</b>\n"
" β’ <b>/post</b> β create a new post (wizard)\n"
" β’ <b>/listposts</b> β list active posts with delete buttons\n"
" β’ <b>/deletepost <hash></b> β delete a post\n"
" β’ <b>/flush</b> β β οΈ permanently delete ALL posts\n\n"
"<b>π’ Channel Management (Request)</b>\n"
" β’ <b>/add_channel</b> β add forceβsub (request) channel\n"
" β’ <b>/remove_channel</b> β remove a request channel\n"
" β’ <b>/list_channels</b> β list all request channels\n"
" β’ <b>/update_links</b> β refresh invite links for request channels\n\n"
"<b>π‘ Posting Channels</b>\n"
" β’ <b>/add_posting <id></b> β add a posting channel\n"
" β’ <b>/remove_posting <id></b> β remove a posting channel\n"
" β’ <b>/list_posting</b> β list all posting channels\n\n"
"<b>π§ Administration</b>\n"
" β’ <b>/admin</b> β open interactive admin panel\n"
" β’ <b>/stats</b> β quick stats\n"
" β’ <b>/broadcast</b> β reply to a message to broadcast to all posting channels\n"
" β’ <b>/backup</b> β export database to JSON\n"
" β’ <b>/addowner <id></b> β add a new owner\n\n"
"<b>π οΈ Utilities</b>\n"
" β’ <b>/upload</b> β reply to an image to upload to ImgBB\n\n"
"<b>βΉοΈ Info</b>\n"
" β’ <b>/help</b> β this message",
parse_mode="html"
)
raise events.StopPropagation
@client.on(events.NewMessage(pattern="/fuck_you"))
async def cmd_reset(event):
if not await is_owner_async(event.sender_id):
await event.reply("Sure!")
return
try: await event.delete()
except Exception: pass
sender_id = event.sender_id
wizard.pop(sender_id, None)
x = await event.respond("Wizard state cleared.")
await asyncio.sleep(3)
try: await x.delete()
except Exception: pass
@client.on(events.NewMessage(pattern="/flush"))
async def cmd_flush(event):
if not await is_owner_async(event.sender_id):
await event.reply("β Owner only.")
return
# Ask for confirmation
msg = await event.reply(
"<b><blockquote>β οΈ DANGER ZONE</blockquote></b>\n\n"
"This will <b>permanently delete EVERY post</b> from the database.\n"
"This action <b>cannot be undone</b>.\n\n"
"Are you absolutely sure?",
parse_mode="v2",
buttons=[
[Button.inline("β
YES, DELETE ALL", b"flush_confirm")],
[Button.inline("β Cancel", b"flush_cancel")],
],
)
wizard[event.sender_id] = {"flush_msg_id": msg.id, "flush_chat_id": event.chat_id}
raise events.StopPropagation
# ββ Request channel commands ββββββββββββββββββββββββββββββ
@client.on(events.NewMessage(pattern="/add_request(?:\\s+(.+))?"))
async def cmd_add_request(event):
if not await is_owner_async(event.sender_id):
return
parts = event.message.text.split(maxsplit=1)
if len(parts) < 2:
await event.reply("Usage: /add_request <channel_id> or forward a message.\nYou can also reply with a channel ID or link.")
return
channel_id = parts[1].strip()
resolved = await _resolve_channel_id(event)
if not resolved:
await event.reply("β Invalid channel ID. Send a numeric ID, t.me link, or forward a message.")
return
added = await db.add_channel(resolved, event.sender_id, "request", "")
if added:
await event.reply(f"β
Channel <code>{resolved}</code> added as **request** (forceβsub) channel.", parse_mode="v2")
else:
await event.reply(f"β οΈ Channel <code>{resolved}</code> already exists.", parse_mode="v2")
raise events.StopPropagation
@client.on(events.NewMessage(pattern="/remove_request(?:\\s+(.+))?"))
async def cmd_remove_request(event):
if not await is_owner_async(event.sender_id):
return
parts = event.message.text.split(maxsplit=1)
if len(parts) < 2:
await event.reply("Usage: /remove_request <channel_id>")
return
channel_id = parts[1].strip()
removed = await db.remove_channel(channel_id, "request")
if removed:
await event.reply(f"β
Request channel <code>{channel_id}</code> removed.", parse_mode="v2")
else:
await event.reply(f"β Request channel <code>{channel_id}</code> not found.", parse_mode="v2")
raise events.StopPropagation
# ββ Posting channel commands ββββββββββββββββββββββββββββββ
@client.on(events.NewMessage(pattern="/add_posting(?:\\s+(.+))?"))
async def cmd_add_posting(event):
if not await is_owner_async(event.sender_id):
return
parts = event.message.text.split(maxsplit=1)
if len(parts) < 2:
await event.reply("Usage: /add_posting <channel_id> or forward a message.")
return
channel_id = parts[1].strip()
resolved = await _resolve_channel_id(event)
if not resolved:
await event.reply("β Invalid channel ID. Send a numeric ID, t.me link, or forward a message.")
return
added = await db.add_channel(resolved, event.sender_id, "posting", "")
if added:
await event.reply(f"β
Channel <code>{resolved}</code> added as **posting** channel.", parse_mode="v2")
else:
await event.reply(f"β οΈ Channel <code>{resolved}</code> already exists.", parse_mode="v2")
raise events.StopPropagation
@client.on(events.NewMessage(pattern="/remove_posting(?:\\s+(.+))?"))
async def cmd_remove_posting(event):
if not await is_owner_async(event.sender_id):
return
parts = event.message.text.split(maxsplit=1)
if len(parts) < 2:
await event.reply("Usage: /remove_posting <channel_id>")
return
channel_id = parts[1].strip()
removed = await db.remove_channel(channel_id, "posting")
if removed:
await event.reply(f"β
Posting channel <code>{channel_id}</code> removed.", parse_mode="v2")
else:
await event.reply(f"β Posting channel <code>{channel_id}</code> not found.", parse_mode="v2")
raise events.StopPropagation
# ββ List channels commands ββββββββββββββββββββββββββββββ
@client.on(events.NewMessage(pattern="/list_request"))
async def cmd_list_request(event):
if not await is_owner_async(event.sender_id):
return
channels = await db.get_channels(channel_type="request")
if not channels:
await event.reply("No request channels configured.")
return
lines = ["<b>π Request channels (forceβsub):</b>\n"]
for ch in channels:
lines.append(
f"β’ <code>{ch.get('channel_name')}</code> β {ch.get('channel_id')}"
)
await event.reply("\n".join(lines), parse_mode="v2")
raise events.StopPropagation
@client.on(events.NewMessage(pattern="/list_posting"))
async def cmd_list_posting(event):
if not await is_owner_async(event.sender_id):
return
channels = await db.get_channels(channel_type="posting")
if not channels:
await event.reply("No posting channels configured.")
return
lines = ["<b>π‘ Posting channels:</b>\n"]
for ch in channels:
lines.append(
f"β’ <code>{ch.get('channel_name')}</code> β {ch.get('channel_id')}"
)
await event.reply("\n".join(lines), parse_mode="v2")
raise events.StopPropagation
@client.on(events.NewMessage(pattern="/upload"))
async def cmd_upload(event):
if not await is_owner_async(event.sender_id):
await event.reply("β Owner only.")
return
# Check if replying to a message
reply_msg = await event.get_reply_message()
if not reply_msg:
await event.reply(
"<b>β Usage:</b> Reply to an image/video with <code>/upload</code>",
parse_mode="v2"
)
return
# Check if replied message contains media
if not reply_msg.media:
await event.reply("β The replied message has no media (image/video).")
return
# Send "uploading" status
status_msg = await event.reply("<b>β³ Uploading to ImgBB...</b>", parse_mode="v2")
try:
# Download media
file_path = CACHE_DIR / f"upload_{event.sender_id}_{reply_msg.id}.jpg"
await client.download_media(reply_msg.media, str(file_path))
# Upload to ImgBB
with open(file_path, "rb") as f:
uploaded = await ibb.upload_from_bytes(image_bytes=f.read(), name=str(file_path))
image_url = ibb.get_image_url(uploaded)
delete_url = uploaded.get("delete_url", "No delete URL")
# Clean up temp file
os.remove(file_path)
# Prepare response
result_text = (
f"<b><blockquote>β
Upload successful!</blockquote></b>\n\n"
f"π <b>Image URL:</b>\n<code>{image_url}</code>\n\n"
f"π <b>Delete URL:</b>\n<code>{delete_url}</code>"
)
buttons = [
[Button.url("π Copy URL", f"https://t.me/share/url?url={image_url}")],
[Button.url("π Open Image", image_url)],
]
await status_msg.edit(result_text, parse_mode="v2", buttons=buttons)
except Exception as e:
await status_msg.edit(f"β Upload failed: {e}")
# STARTUP
async def main():
config.validate()
await db.ensure_indexes()
if not await db.get_setting("extra_owners", ""):
await db.set_setting("extra_owners", "[]")
try:
await db.get_collection("users").create_index("telegram_id", unique=True)
except Exception:
pass
log.info("Starting botβ¦")
await client.start(bot_token=config.BOT_TOKEN)
me = await client.get_me()
log.info("Running as @%s (ID: %s)", me.username, me.id)
log.info("Owners: %s", config.OWNER_IDS)
log.info("Extra owners: %s", json.loads(await db.get_setting("extra_owners", "[]")))
log.info("Force-sub: %s", config.FORCE_SUB_ENABLED)
log.info("WebApp URL: %s", config.WEBAPP_URL)
log.info("Ad network: %s", config.AD_NETWORK)
global _bot_username
_bot_username = me.username or ""
# schedular
start_scheduler()
await client.run_until_disconnected()
if __name__ == "__main__":
asyncio.run(main())
"""
bot.py β Telethon bot (MongoDB via Motor).
Run: python bot.py (separate process from FastAPI)
"""
from __future__ import annotations
import asyncio
import json
import logging
import os
from datetime import datetime, timedelta
from pathlib import Path
from typing import Any, Dict, Optional
from telethon import (
Button,
TelegramClient,
events
)
from telethon.errors import (
ChatAdminRequiredError,
MessageNotModifiedError,
RPCError,
UserNotParticipantError,
FloodWaitError,
UserIsBlockedError,
InputUserDeactivatedError,
PeerIdInvalidError,
UserDeactivatedBanError
)
from telethon.tl.functions.channels import (
GetFullChannelRequest,
GetParticipantRequest,
)
from telethon.tl.functions.messages import (
ExportChatInviteRequest,
ForwardMessagesRequest
)
from telethon.tl.types import (
ChannelParticipantAdmin,
ChannelParticipantBanned,
ChannelParticipantCreator,
Message,
MessageService,
MessageMediaDocument,
MessageMediaPhoto,
MessageActionChatAddUser,
UpdateNewChannelMessage
)
from telethon.utils import get_input_channel
from apscheduler.schedulers.asyncio import AsyncIOScheduler
import config
import db
from utils import generate_hash, ImgBBUploader
logging.basicConfig(
level=logging.INFO,
format="[%(asctime)s] %(levelname)s %(name)s: %(message)s",
datefmt="%H:%M:%S",
)
log = logging.getLogger("bot")
CACHE_DIR = Path("downloads")
CACHE_DIR.mkdir(exist_ok=True)
ibb = ImgBBUploader(api_key=config.IMGBB_API_KEY)
client = TelegramClient("bot_session", config.API_ID, config.API_HASH)
# wizard[user_id] = { step, wizard_msg_id, wizard_chat_id, image_url, caption,
# redirect_link, required_ads, category, source_msg_id,
# source_chat_id, ... }
wizard: Dict[int, dict] = {}
_bot_username: str = ""
scheduler = AsyncIOScheduler(timezone="UTC")
# HELPERS ------------------
async def get_bot_username() -> str:
global _bot_username
if not _bot_username:
me = await client.get_me()
_bot_username = me.username or ""
return _bot_username
def make_link(magical_hash: str, bot_username: str) -> str:
return config.miniapp_link(magical_hash, bot_username)
async def is_owner_async(user_id: int) -> bool:
owners = config.OWNER_IDS.copy()
extra = await db.get_setting("extra_owners", "[]")
try:
owners.extend(json.loads(extra))
except Exception:
pass