0% found this document useful (0 votes)
3 views65 pages

Updated Commands

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views65 pages

Updated Commands

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

*

=
# ✅ Utility: readable timer
def format_time(time_left):
sec = time_left % (24 * 3600)
hour = sec // 3600
sec %= 3600
mins = sec // 60
sec %= 60
return "%d h %02d m %02d s" % (hour, mins, sec)

if [Link] not in ["group", "supergroup"]:


raise ReturnCommand()

user_id = message.from_user.id
group_id = [Link]

# ✅ Get member status once at start


try:
mem = [Link](group_id, user_id)
member_status = [Link]
except:
member_status = "unknown"

is_admin = member_status in ["administrator", "creator"]

# ✅ Skip bots immediately


if message.from_user.is_bot:
raise ReturnCommand()

# --------------------------------------------------
# 📝 FILTERS (trigger/response system)
# --------------------------------------------------
filters = [Link](f"filters_{group_id}") or {}
if filters:
text_content = ([Link] or [Link] or "").lower()
if text_content.strip():
for trigger, response in [Link]():
if trigger in text_content.split(): # exact word match
[Link](group_id, response,
reply_to_message_id=message.message_id)
raise ReturnCommand()

# --------------------------------------------------
# 👋 Welcome + Tracking Join
# --------------------------------------------------
already_tracked = [Link](f"invite_used_{user_id}_{group_id}")
info = [Link](f"invite_current_{user_id}")

if not already_tracked and info and not [Link]("used") and [Link]("group") ==


group_id:
inviter = [Link]("inviter")
inviter_name = [Link]("inviter_name") or ""

# ✅ Save referral counts


key = f"invite_counts_{group_id}_{inviter}"
count = int([Link](key) or "0")
[Link](key, str(count + 1))
# ✅ Leaderboard list
inviter_list_key = f"inviter_list_{group_id}"
inviter_list = [Link](inviter_list_key) or []
if str(inviter) not in inviter_list:
inviter_list.append(str(inviter))
[Link](inviter_list_key, inviter_list)

# ✅ Track invitee
invited_key = f"invited_users_{group_id}_{inviter}"
invited_list = [Link](invited_key) or ""
invited_ids = invited_list.split(",") if invited_list else []
if str(user_id) not in invited_ids:
invited_ids.append(str(user_id))
[Link](invited_key, ",".join(invited_ids))

# ✅ Resettable tracker
reset_key = f"resettable_invite_keys_{group_id}"
key_list = [Link](reset_key) or []
if key not in key_list:
key_list.append(key)
[Link](reset_key, key_list)

# ✅ Mark used
info["used"] = True
[Link](f"invite_current_{user_id}", info)
[Link](f"invite_used_{user_id}_{group_id}", "ok")

# ✅ Optional notification
settings = [Link](f"group_invite_config_{group_id}") or {"notify": True}
if [Link]("notify", True):
user_mention = f"<a href='tg://user?
id={user_id}'>{message.from_user.first_name}</a>"
inviter_mention = f"<a href='tg://user?id={inviter}'>{inviter_name or 'an
inviter'}</a>"
[Link](
chat_id=group_id,
text=f"🎉 Welcome {user_mention}! Invited by {inviter_mention}. Glad to
have you!",
parse_mode="html"
)

# --------------------------------------------------
# 🚫 BLOCK RULES (admins immune)
# --------------------------------------------------
if not is_admin:
blocks = [Link](f"group_blocks_{group_id}") or []

def check_and_delete(reason, condition):


if condition:
[Link](group_id, message.message_id)
return True
return False

if "links" in blocks and ([Link] or message.caption_entities):


for ent in ([Link] or []) + (message.caption_entities or []):
if [Link] in ["url", "text_link"]:
if check_and_delete("Link", True):
raise ReturnCommand()
if "stickers" in blocks:
if check_and_delete("Sticker", [Link]):
raise ReturnCommand()

if "gifs" in blocks:
if check_and_delete("GIF", [Link]):
raise ReturnCommand()

if "emojis" in blocks and [Link]:


if check_and_delete("Emoji", any(ord(ch) > 10000 for ch in [Link])):
raise ReturnCommand()

if "forwards" in blocks:
if check_and_delete("Forward", (message.forward_from or
message.forward_from_chat)):
raise ReturnCommand()

if "voice" in blocks:
if check_and_delete("Voice/Audio", ([Link] or [Link])):
raise ReturnCommand()

if "commands" in blocks:
if check_and_delete("Command", ([Link] or "").startswith("/")):
raise ReturnCommand()

if "photos" in blocks:
if check_and_delete("Photo", [Link]):
raise ReturnCommand()

if "videos" in blocks:
if check_and_delete("Video", [Link]):
raise ReturnCommand()

if "documents" in blocks:
if check_and_delete("Document", [Link]):
raise ReturnCommand()

# --------------------------------------------------
# 🚫 AI MODERATION (admins immune)
# --------------------------------------------------
text = [Link] or [Link] or ""
if not [Link]():
raise ReturnCommand()

deleted_flag = False
if not is_admin:
modes = [Link](f"group_modes_{group_id}") or []

prompts = {
"toxicity": "Check if the message below contains bullying, rudeness, or
toxic behavior.\nMessage: \"{text}\"...",
"profanity": "Check if this message contains profanity, swearing, or
offensive language.\nMessage: \"{text}\"...",
"nsfw": "Does this message contain sexually explicit or NSFW content?\
nMessage: \"{text}\"...",
"strict_ai": "Detect if this message is passive-aggressive, sarcastic, or
subtly toxic.\nMessage: \"{text}\"...",
"english_only": "Is this message written in a language other than English?\
nMessage: \"{text}\"...",
"ads": "Does this message promote ads, channels, groups, or links?\
nMessage: \"{text}\"...",
"pm_block": "Does this message ask others to PM, DM, or inbox the sender?\
nMessage: \"{text}\"...",
"tag_block": "Does this message mention admins or users with tags like
@admin or @all?\nMessage: \"{text}\"..."
}

reason_texts = {
"toxicity": "toxic or bullying behavior",
"profanity": "offensive or profane language",
"nsfw": "sexually inappropriate content",
"strict_ai": "passive-aggressive or sarcastic behavior",
"english_only": "non-English content (English only is allowed)",
"ads": "unsolicited promotions or links",
"pm_block": "asking users to DM or inbox",
"tag_block": "tagging admins or groups unnecessarily"
}

api_url = "[Link]

for mode in modes:


if mode not in prompts:
continue
try:
payload = {
"gpt": [],
"user": prompts[mode] + "\n\n⚠️ Respond ONLY with the category word
or 'clean'."
}
res = [Link](api_url, json=payload).json()
detected = [Link]("answer", "").strip().lower()

if detected == mode:
try:
[Link](chat_id=group_id,
message_id=message.message_id)
deleted = int([Link]("deleted_total") or 0)
[Link]("deleted_total", deleted + 1)
except:
pass

mention = f'<a href="tg://user?


id={user_id}">{message.from_user.first_name}</a>'
reason = reason_texts.get(mode, [Link]("_", " ").title())
warn = [Link](
chat_id=group_id,
text=f"🚫 {mention}, your message was removed for
<b>{reason}</b>.",
parse_mode="html",
reply_markup={
"inline_keyboard": [[
{"text": "🤖 Create Your Own Bot", "url":
"[Link]
]]
}
)
[Link](f"delmsg_warn_{warn.message_id}", group_id)
[Link](60, "/delmsg", f"warn_{warn.message_id}")
deleted_flag = True
break
except:
pass

# --------------------------------------------------
# 🚫 BLOCKED WORDS (admins immune)
# --------------------------------------------------
if not is_admin:
blocked_words = [Link](f"blocked_words_{group_id}") or []
for bw in blocked_words:
word = [Link]("word", "").strip()
mode = [Link]("mode", "included")

if not word:
continue

text = ([Link] or [Link] or "").strip()


text_lower = [Link]()
word_lower = [Link]()

match_found = False
if mode == "precise" and text_lower == word_lower:
match_found = True
elif mode == "included":
words_in_text = text_lower.split()
if word_lower in words_in_text and len(words_in_text) > 1:
match_found = True

if match_found:
try:
[Link](group_id, message.message_id)
except:
pass
raise ReturnCommand()

# --------------------------------------------------
# ✅ ACTIVITY LOGGER
# --------------------------------------------------
if not deleted_flag:
settings = [Link](f"activity_settings_{group_id}") or {}
count_admins = [Link]("count_admins", False)
msg_cldwn = int([Link]("msg_cldwn", 0))

# Skip admins only if setting says so


if is_admin and not count_admins:
raise ReturnCommand()

# ✅ Cooldown check
cooldown_key = f"activity_cooldown_{group_id}_{user_id}"
last_time = float([Link](cooldown_key) or 0)
now = [Link]()
time_left = int(last_time + msg_cldwn - now)

if time_left <= 0:
points_key = f"user_points_{group_id}_{user_id}"
current_points = int([Link](points_key) or 0)
[Link](points_key, current_points + 1)
user_list_key = f"activity_user_list_{group_id}"
user_list = [Link](user_list_key) or []
if str(user_id) not in user_list:
user_list.append(str(user_id))
[Link](user_list_key, user_list)

[Link](cooldown_key, now)

/activity_cooldown
==================
# /activity_cooldown <group_id> [seconds]
if [Link] != "private":
raise ReturnCommand()

split = [Link]().split()
group_id = split[0]
selected = int(split[1]) if len(split) > 1 else None
u = [Link]
ctx = [Link]("settings_context")

# ✅ Verify session & admin


if not ctx or str([Link]("group_id")) != group_id:
[Link](u, "❌ Invalid or expired session.")
raise ReturnCommand()

try:
member = [Link](group_id, u)
if [Link] not in ["administrator", "creator"]:
[Link](u, "🚫 You must be an admin in the group to manage this
setting.")
raise ReturnCommand()
except:
[Link](u, "❌ Could not verify your admin status.")
raise ReturnCommand()

# ✅ Load activity settings


settings = [Link](f"activity_settings_{group_id}") or {}
[Link]("msg_cldwn", 0)

# ✅ If a number is provided, save it


if selected is not None:
if 0 <= selected <= 60:
settings["msg_cldwn"] = selected
[Link](f"activity_settings_{group_id}", settings)
else:
[Link](u, "❌ Invalid value. Must be 0–60 seconds.")
raise ReturnCommand()

# ✅ Build buttons in order (0,5,10,...,60)


buttons_flat = []
for i in range(0, 65, 5):
label = f"{i} s {'✅' if settings['msg_cldwn'] == i else ''}".strip()
buttons_flat.append(InlineKeyboardButton(label,
callback_data=f"/activity_cooldown {group_id} {i}"))

# ✅ Arrange buttons in rows of 3


buttons = [buttons_flat[i:i+3] for i in range(0, len(buttons_flat), 3)]

# ✅ Add back button


[Link]([InlineKeyboardButton("🔙 Back", callback_data=f"/activity_settings
{group_id}")])

# ✅ Message text
text = (
f"<b> Message Cooldown Settings</b>\n\n"
f"This sets the period in seconds in which a user can only gain 1 activity
point per message.\n\n"
f"Current cooldown: <b>{settings['msg_cldwn']} seconds</b>\n\n"
f"Select a new cooldown from the options below:"
)

# ✅ Edit message
try:
[Link](
chat_id=u,
message_id=message.message_id,
text=text,
parse_mode="html",
reply_markup=InlineKeyboardMarkup(buttons)
)
except:
[Link](
u,
text,
parse_mode="html",
reply_markup=InlineKeyboardMarkup(buttons)
)

/activity_lb
============
# /activity_lb
# ✅ Configurable cooldown in minutes
COOLDOWN_MINUTES = 10 # Change this value to set cooldown duration
COOLDOWN_SECONDS = COOLDOWN_MINUTES * 60

# ✅ Utility: readable timer


def format_time(time_left):
sec = time_left % (24 * 3600)
hour = sec // 3600
sec %= 3600
mins = sec // 60
sec %= 60
return "%d h %02d m %02d s" % (hour, mins, sec)

# ✅ Group validation
if [Link] not in ["group", "supergroup"]:
raise ReturnCommand()

group_id = [Link]
user_id = message.from_user.id
group_title = [Link] or "this group"

# ✅ Load activity settings


settings = [Link](f"activity_settings_{group_id}") or {}
trigger_mode = [Link]("trigger", "admins") # "admins" or "everyone"

# ✅ Admin check
is_admin = False
try:
member = [Link](group_id, user_id)
is_admin = [Link] in ["administrator", "creator"]
except:
pass

# ✅ Trigger permission
if trigger_mode == "admins" and not is_admin:
[Link](
group_id,
"🚫 Only admins can trigger the activity leaderboard. Change this in
/settings"
)
raise ReturnCommand()

# ✅ Rate limiting (non-admins only)


cooldown_key = f"activity_lb_cooldown_{group_id}"
cooldown_expiry = [Link](cooldown_key)
now = [Link]()
time_left = 0

if not is_admin and cooldown_expiry:


try:
expiry_time = float(cooldown_expiry)
time_left = int(expiry_time - now)
except:
time_left = 0

if time_left > 0:
last_msg_data = [Link](f"last_activity_lb_msg_{group_id}")
if last_msg_data:
last_msg_id = last_msg_data.get("message_id")
if last_msg_id:
msg_link = f"[Link]
[Link](
group_id,
f"⏳ Please wait {format_time(time_left)} before checking the
activity leaderboard again.\n\n"
f"🔁 You can still view the <a href=\"{msg_link}\">last leaderboard
here</a>.",
parse_mode="HTML"
)
raise ReturnCommand()
[Link](
group_id,
f"⏳ Please wait {format_time(time_left)} before checking the activity
leaderboard again."
)
raise ReturnCommand()

# ✅ Set cooldown
if not is_admin:
[Link](cooldown_key, str(now + COOLDOWN_SECONDS))

# ✅ Build leaderboard using stored list


user_list_key = f"activity_user_list_{group_id}"
user_ids = [Link](user_list_key) or []

entries = []
for uid_str in user_ids:
uid = int(uid_str)
points_key = f"user_points_{group_id}_{uid}"
points = int([Link](points_key) or 0)
[Link]((uid, points))

# ✅ Sort descending
[Link](key=lambda x: x[1], reverse=True)
limit = int([Link](f"group_lb_limit_{group_id}") or 10)
top_users = entries[:limit]

if not top_users:
[Link](group_id, "📭 No activity points recorded yet in this group.")
raise ReturnCommand()

# ✅ Delete old leaderboard if exists


old_msg_data = [Link](f"last_activity_lb_msg_{group_id}")
if old_msg_data:
try:
old_msg_id = old_msg_data.get("message_id")
if old_msg_id:
[Link](group_id, old_msg_id)
except:
pass

# ✅ Build leaderboard text


text = f"<b>🏆 Activity Leaderboard for {group_title}</b>\n"
text += f"<i>Showing top {limit} users by activity points:</i>\n\n"

for i, (uid, pts) in enumerate(top_users, 1):


try:
user = [Link](group_id, uid).user
name = user.first_name or "User"
name = [Link]("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
profile_link = f'<a href="tg://user?id={uid}">{name}</a>'
except:
profile_link = f'<a href="tg://user?id={uid}">User</a>'
point_word = "point" if pts == 1 else "points"
text += f"{i}. {profile_link} – {pts} {point_word}\n"

# ✅ Add info button


btns = InlineKeyboardMarkup([
[InlineKeyboardButton("ℹ️ How Points Are Calculated",
url="[Link]
])

# ✅ Send new leaderboard


msg = [Link](group_id, text, parse_mode="HTML", reply_markup=btns)

# ✅ Save new leaderboard message ID


if msg:
[Link](f"last_activity_lb_msg_{group_id}", {
"message_id": msg.message_id,
"timestamp": int(now)
})

/activity_settings
==================
if [Link] != "private":
raise ReturnCommand()

group_id = [Link]()
u = [Link]
ctx = [Link]("settings_context")

# ✅ Verify session
if not ctx or str(ctx["group_id"]) != group_id:
[Link](u, "❌ Invalid or expired session.")
raise ReturnCommand()

group_title = [Link]("group_title", "Group")

# ✅ Verify user is still admin


try:
member = [Link](group_id, u)
if [Link] not in ["administrator", "creator"]:
[Link](u, "🚫 You must be an admin in the group to manage these
settings.")
raise ReturnCommand()
except:
[Link](u, "❌ Could not verify your admin status.")
raise ReturnCommand()

# ✅ Load activity settings and defaults


settings = [Link](f"activity_settings_{group_id}") or {}
[Link]("trigger", "admins")
[Link]("count_media", True)
[Link]("count_admins", False)
[Link]("msg_cldwn", 0) # message cooldown

# ✅ Build button labels


trigger_label = f"Leaderboard Trigger ({'Admins Only' if
settings['trigger']=='admins' else 'Everyone'})"
count_label = f"Count Media ({'ON ✅' if settings['count_media'] else 'OFF'})"
count_admin_label = f"Count Admins ({'ON ✅' if settings['count_admins'] else
'OFF'})"
cooldown_label = f"Message Cooldown ({settings['msg_cldwn']} s)"

buttons = [
[InlineKeyboardButton(trigger_label, callback_data=f"/toggle_activity
{group_id} trigger")],
[InlineKeyboardButton(count_label, callback_data=f"/toggle_activity {group_id}
count_media")],
[InlineKeyboardButton(cooldown_label, callback_data=f"/activity_cooldown
{group_id}")],
[InlineKeyboardButton(count_admin_label, callback_data=f"/toggle_activity
{group_id} count_admins")],
[InlineKeyboardButton("♻️ Reset Activity", callback_data=f"/reset_activity
{group_id}")],
[InlineKeyboardButton("🔙 Back", callback_data="/settings_dm")]
]

text = (
f"<b>📊 Activity Settings for:</b> {group_title}\n\n"
f"• <b>Leaderboard Trigger</b>: Choose if only admins or everyone can use the
leaderboard.\n"
f"• <b>Count Media</b>: Decide if sending photos, GIFs, or stickers also give
activity points.\n"
f"• <b>Message Cooldown</b>: Limit how often activity points are given.\n"
f"• <b>Count Admins</b>: Decide if admin messages also count.\n"
f"• <b>Reset Activity</b>: Clears all saved activity points for this group."
)

# ✅ Edit message seamlessly


try:
[Link](
chat_id=u,
message_id=message.message_id,
text=text,
parse_mode="html",
reply_markup=InlineKeyboardMarkup(buttons)
)
except:
# fallback if edit fails
[Link](
u,
text,
parse_mode="html",
reply_markup=InlineKeyboardMarkup(buttons)
)

/add_blocked_word
=================
# Command: /add_blocked_word
if [Link] != "private":
raise ReturnCommand()

u = message.from_user.id
ctx = [Link]("settings_context")

if not ctx or [Link]("admin_id") != u:


[Link](u, "❌ No active session. Please use /settings in your group
first.")
raise ReturnCommand()

group_id = ctx["group_id"]
group_title = ctx["group_title"]

# ✅ Verify admin
try:
member = [Link](group_id, u)
if [Link] not in ["administrator", "creator"]:
[Link](u, "🚫 You must be an admin to manage blocked words.")
raise ReturnCommand()
except:
[Link](u, "❌ Could not verify your admin status.")
raise ReturnCommand()

# ✅ Check if mode is already provided


parts = [Link]() if params else []
mode = parts[1] if len(parts) > 1 else None

if not mode:
# Ask the admin how they want to block the word
text = (
f"🛡 *Add Blocked Word in {group_title}*\n\n"
"Choose how you want to block the word:\n"
"• *Included Block* → Blocks if word/phrase appears anywhere in a message\
n"
"• *Precise Block* → Blocks only if the word/phrase is sent alone"
)

btns = {
"inline_keyboard": [
[{"text": "🔎 Included Block", "callback_data": f"/add_blocked_word
{group_id} included"}],
[{"text": "🎯 Precise Block", "callback_data": f"/add_blocked_word
{group_id} precise"}],
[{"text": "🔙 Back", "callback_data": f"/list_blocked_words
{group_id}"}]
]
}

try:
[Link](
chat_id=u,
message_id=message.message_id,
text=text,
parse_mode="markdown",
reply_markup=btns
)
except:
[Link](
u,
text,
parse_mode="markdown",
reply_markup=btns
)
raise ReturnCommand()

# ✅ If mode is selected, ask for the word/phrase


if mode not in ["included", "precise"]:
[Link](u, "❌ Invalid mode. Please try again.")
raise ReturnCommand()

# 🔹 Save both group_id and mode in temporary data


[Link]("blocked_word_context", {
"group_id": group_id,
"mode": mode
})

text = (
f"✍️ *Add Blocked Word ({[Link]()} Block)*\n\n"
"Please send the word or phrase you want to block.\n\n"
"👉 Send `X` to cancel."
)

[Link](
chat_id=u,
message_id=message.message_id,
text=text,
parse_mode="markdown"
)

# ✅ Wait for user input


[Link]("/save_blocked_word")
/block_settings
===============
if [Link] != "private":
raise ReturnCommand()

group_id = [Link]()
u = [Link]
ctx = [Link]("settings_context")

# ✅ Verify session
if not ctx or str(ctx["group_id"]) != group_id:
[Link](u, "❌ Invalid or expired session.")
raise ReturnCommand()

group_title = [Link]("group_title", "Group")

# ✅ Verify user is still admin in group


try:
member = [Link](group_id, u)
if [Link] not in ["administrator", "creator"]:
[Link](u, "🚫 You must be an admin in the group to manage these
settings.")
raise ReturnCommand()
except:
[Link](u, "❌ Could not verify your admin status.")
raise ReturnCommand()

# ✅ Load saved block settings


stored_blocks = [Link](f"group_blocks_{group_id}")
blocks = stored_blocks if stored_blocks is not None else []

# ✅ Available block options


all_blocks = {
"links": "Links",
"stickers": "Stickers",
"gifs": "GIFs",
"emojis": "Emojis",
"forwards": "Forwards",
"voice": "Voice Messages",
"commands": "Commands",
"photos": "Photos",
"videos": "Videos",
"documents": "Documents"
}

# ✅ Build toggle buttons


buttons = [[InlineKeyboardButton(
f"{'✅' if key in blocks else '❌'} {label}",
callback_data=f"/toggle_block {group_id} {key}"
)] for key, label in all_blocks.items()]

# ✅ Back button
[Link]([InlineKeyboardButton("🔙 Back", callback_data="/settings_dm")])

# ✅ Message text
text = (
f"<b>🚫 Block Settings for:</b> {group_title}\n\n"
f"Toggle options below.\n\n"
f"Anything marked ✅ will be deleted by the bot automatically."
)

# ✅ Update or send message


try:
[Link](
chat_id=u,
message_id=message.message_id,
text=text,
parse_mode="html",
reply_markup=InlineKeyboardMarkup(buttons)
)
except:
[Link](
u,
text,
parse_mode="html",
reply_markup=InlineKeyboardMarkup(buttons)
)

/check_swr
==========
group_id = [Link]
user_id = message.from_user.id
text = ([Link] or "").strip().lower()

if [Link] not in ["group", "supergroup"]:


raise ReturnCommand()

session = [Link](f"swr_session_{group_id}")
if not session or not [Link]("current_word"):
[Link](group_id, "⚠️ No active round found.")
raise ReturnCommand()

correct_word = session["current_word"].lower()
if text == correct_word:
players = [Link]("players", {})
if str(user_id) not in players:
players[str(user_id)] = {"score": 0, "name": message.from_user.first_name}
players[str(user_id)]["score"] += 1
session["players"] = players
[Link](f"swr_session_{group_id}", session)

[Link](group_id, f"✅ {message.from_user.first_name} got it correct! (+1


pt)")

[Link](10, "/start_swr")
else:
[Link](group_id, f"❌ {message.from_user.first_name} guessed incorrectly.
Try again!")
[Link]("/check_swr")

/edit_goodbye
=============
# /edit_goodbye
if [Link] != "private":
raise ReturnCommand()

u = [Link]
group_id = [Link]()

ctx = [Link]("settings_context")

# ✅ Verify session
if not ctx or str([Link]("group_id")) != group_id:
[Link](u, "❌ Invalid or expired session.")
raise ReturnCommand()

group_title = [Link]("group_title", "Group")

# ✅ Verify admin
try:
member = [Link](group_id, u)
if [Link] not in ["administrator", "creator"]:
[Link](u, "🚫 You must be an admin to manage these settings.")
raise ReturnCommand()
except:
[Link](u, "❌ Could not verify your admin status.")
raise ReturnCommand()

# ✅ Edit message to ask for new goodbye message


text = (
f"<b>✏️ Customize Goodbye Message for:</b> {group_title}\n\n"
f"Please send the new goodbye message you want the bot to use.\n\n"
f"• You can use basic HTML formatting (e.g., <b>bold</b>, <i>italic</i>).\n"
f"• You can include placeholders:\n"
f" - <code>{{name}}</code> → user's first name\n"
f" - <code>{{username}}</code> → user's username\n"
f" - <code>{{group}}</code> → group title\n"
f"• You may also attach an image or video to include with the goodbye message.\
n\n"
f"Send <b>X</b> to cancel."
)

try:
[Link](
chat_id=u,
message_id=message.message_id,
text=text,
parse_mode="html"
)
except:
[Link](u, text, parse_mode="html")

# ✅ Save the group ID temporarily for next message handling


[Link]("goodbye_edit_group", group_id)

# ✅ Set next command handler


# This will catch the admin's next message and handle saving or canceling
[Link]("/save_goodbye")

/edit_welcome
=============
if [Link] != "private":
raise ReturnCommand()

group_id = [Link]()
u = [Link]
ctx = [Link]("settings_context")

# ✅ Verify session
if not ctx or str([Link]("group_id")) != group_id:
[Link](u, "❌ Invalid or expired session.")
raise ReturnCommand()

group_title = [Link]("group_title", "Group")

# ✅ Verify admin
try:
member = [Link](group_id, u)
if [Link] not in ["administrator", "creator"]:
[Link](u, "🚫 You must be an admin to manage these settings.")
raise ReturnCommand()
except:
[Link](u, "❌ Could not verify your admin status.")
raise ReturnCommand()

# ✅ Save group_id temporarily for next steps


[Link]("welcome_edit_group", group_id)

# ✅ Edit message to ask for new welcome message


text = (
f"<b>✏️ Customize Welcome Message for:</b> {group_title}\n\n"
f"Please send the new welcome message you want the bot to use.\n\n"
f"• You can use basic HTML formatting (e.g., <b>bold</b>, <i>italic</i>).\n"
f"• You can include placeholders:\n"
f" - <code>{{name}}</code> → user's first name\n"
f" - <code>{{username}}</code> → user's username\n"
f" - <code>{{group}}</code> → group title\n"
f"• You may also attach an image or video.\n\n"
f"Send <b>X</b> to cancel."
)

try:
[Link](chat_id=u, message_id=message.message_id, text=text,
parse_mode="html")
except:
[Link](u, text, parse_mode="html")

# ✅ Set next command handler


[Link]("/save_welcome")

/filter
=======
# Command: /filter
if [Link] not in ["group", "supergroup"]:
raise ReturnCommand()

group_id = [Link]
u = message.from_user.id

# ✅ Admin check
try:
member = [Link](group_id, u)
if [Link] not in ["administrator", "creator"]:
[Link](group_id, f"❌ {[Link](u)}, only group admins can set
filters.")
raise ReturnCommand()
except:
[Link](u, "⚠️ Failed to verify admin permissions.")
raise ReturnCommand()

parts = [Link](maxsplit=2)
if len(parts) < 2:
[Link](group_id, "❌ Usage:\n`/filter trigger response`",
parse_mode="markdown")
raise ReturnCommand()

trigger = parts[1].lower()
response = None

# Case 1: Replied message


if message.reply_to_message and len(parts) == 2:
response = message.reply_to_message.text or message.reply_to_message.caption
else:
if len(parts) < 3:
[Link](group_id, "❌ You must provide a response or reply to a
message.", parse_mode="markdown")
raise ReturnCommand()
response = parts[2]

filters = [Link](f"filters_{group_id}") or {}
filters[trigger] = response
[Link](f"filters_{group_id}", filters)

[Link](
group_id,
f"✅ Filter added!\nWhenever someone says *{trigger}*, I'll reply with your
response.",
parse_mode="markdown"
)

/filter_list
============
# Command: /filter_list
if [Link] not in ["group", "supergroup"]:
raise ReturnCommand()

group_id = [Link]
u = message.from_user.id

# ✅ Admin check
try:
member = [Link](group_id, u)
if [Link] not in ["administrator", "creator"]:
[Link](group_id, f"❌ {[Link](u)}, only group admins can
view filters.")
raise ReturnCommand()
except:
[Link](u, "⚠️ Failed to verify admin permissions.")
raise ReturnCommand()

filters = [Link](f"filters_{group_id}") or {}

if not filters:
[Link](group_id, "_No filters set for this group._",
parse_mode="markdown")
else:
triggers = "\n".join([f"• {t}" for t in [Link]()])
[Link](group_id, f"📃 *Active Filters:*\n{triggers}",
parse_mode="markdown")

/filter_settings
================
# Command: /filter_settings <group_id>
if [Link] != "private":
raise ReturnCommand()

u = message.from_user.id
params = [Link]().split() if params else []
if not params:
raise ReturnCommand()

group_id = int(params[0])
ctx = [Link]("settings_context")

if not ctx or [Link]("group_id") != group_id or [Link]("admin_id") != u:


[Link](u, "❌ No active session. Please use /settings in your group
first.")
raise ReturnCommand()

text = (
"🧹 *Filter Settings*\n\n"
"Filtered words let the bot automatically respond whenever someone uses them in
the group.\n\n"
"👉 *How to set up:*\n"
"• `/filter trigger response` → Add a filter (trigger = one word, response =
any text)\n"
"• Reply to a message with `/filter trigger` → Makes the replied message the
response\n\n"
"👉 *Managing filters:*\n"
"• `/stop_filter trigger` → Remove a filter\n"
"• `/filter_list` → Show all active triggers\n\n"
"⚠️ Note: Only one word can be the trigger, but the response can be as long as
you want."
)

btns = {
"inline_keyboard": [
[{"text": "⬅️ Back", "callback_data": f"/settings_dm"}],
[{"text": "❌ Close", "callback_data": "/close_dm"}]
]
}

try:
[Link](
chat_id=u,
message_id=message.message_id,
text=text,
parse_mode="markdown",
reply_markup=btns
)
except:
[Link](
u,
text,
parse_mode="markdown",
reply_markup=btns
)

/game
=====
# Command: /game <game_code>
if [Link] not in ["group", "supergroup"]:
raise ReturnCommand()

group_id = [Link]
game_code = [Link]().lower() if params else ""

# ✅ Determine game instructions


if game_code == "swr":
text = (
"🏆 *Secret Word Race*\n\n"
"The bot will generate an image with a hidden word (spoiler).\n"
"The first person to correctly type the word in chat wins a point!\n\n"
"To start a game, send:\n"
"`/swr <number_of_rounds>`\n\n"
"Example: `/swr 3`"
)
elif game_code == "ctt":
text = (
" *Catch the Thief*\n\n"
"A thief will randomly appear in chat. Players must react or type a command
to catch them.\n"
"The first person to catch the thief gets points.\n\n"
"To start a game, send:\n"
"`/ctt <number_of_rounds>`\n\n"
"Example: `/ctt 5`"
)
else:
text = "❌ Unknown game. Returning to the main game menu."

# ✅ Back button to main menu


buttons = {
"inline_keyboard": [
[{"text": "🔙 Back to Games", "callback_data": "/games"}]
]
}

# ✅ Try to edit, fallback to reply


try:
[Link](
chat_id=group_id,
message_id=message.message_id,
text=text,
parse_mode="Markdown",
reply_markup=buttons
)
except:
[Link](group_id, text, parse_mode="Markdown", reply_markup=buttons)

/games
======
# Command: /games
if [Link] not in ["group", "supergroup"]:
raise ReturnCommand()

group_id = [Link]

text = "🎮 *Available Group Games*\n\nSelect a game to see instructions or start


playing:"

buttons = {
"inline_keyboard": [
[{"text": "🏆 Secret Word Race", "callback_data": "/game swr"}],
[{"text": " Catch the Thief", "callback_data": "/game ctt"}]
]
}

# ✅ Try to edit message, fallback to reply


try:
[Link](
chat_id=group_id,
message_id=message.message_id,
text=text,
parse_mode="Markdown",
reply_markup=buttons
)
except:
[Link](group_id, text, parse_mode="Markdown", reply_markup=buttons)

/goodbye_message
================
# /goodbye_message
if [Link] != "private":
raise ReturnCommand()

u = [Link]

# ✅ Use params if provided, otherwise fallback to temporary saved group ID


if params and [Link]():
group_id = [Link]()
else:
group_id = [Link]("goodbye_edit_group")
if not group_id:
[Link](u, "❌ No active session. Please start again.")
raise ReturnCommand()
# ✅ Delete temporary data after using it
[Link]("goodbye_edit_group")

ctx = [Link]("settings_context")

# ✅ Verify session
if not ctx or str([Link]("group_id")) != group_id:
[Link](u, "❌ Invalid or expired session.")
raise ReturnCommand()

group_title = [Link]("group_title", "Group")

# ✅ Verify admin
try:
member = [Link](group_id, u)
if [Link] not in ["administrator", "creator"]:
[Link](u, "🚫 You must be an admin to manage these settings.")
raise ReturnCommand()
except:
[Link](u, "❌ Could not verify your admin status.")
raise ReturnCommand()

# ✅ Load goodbye settings


goodbye_settings = [Link](f"goodbye_settings_{group_id}") or {
"enabled": False,
"message": "Goodbye {name}, we will miss you!"
}

# ✅ Build button labels


toggle_label = "✅ On" if goodbye_settings["enabled"] else "❌ Off"

buttons = [
[InlineKeyboardButton(f"Goodbye Messages: {toggle_label}",
callback_data=f"/toggle_goodbye {group_id}")],
[InlineKeyboardButton("✏️ Customize Goodbye Message",
callback_data=f"/edit_goodbye {group_id}")],
[InlineKeyboardButton("📄 View Current Goodbye Message",
callback_data=f"/view_goodbye {group_id}")],
[InlineKeyboardButton("🔙 Back", callback_data=f"/welcome_goodbye {group_id}")]
]

text = (
f"<b>💔 Goodbye Message Settings for:</b> {group_title}\n\n"
f"• Toggle goodbye messages on or off.\n"
f"• Customize the goodbye message text.\n"
f"• View the current goodbye message."
)

try:
[Link](
chat_id=u,
message_id=message.message_id,
text=text,
parse_mode="html",
reply_markup=InlineKeyboardMarkup(buttons)
)
except:
[Link](
u,
text,
parse_mode="html",
reply_markup=InlineKeyboardMarkup(buttons)
)

/handler_chat_member
====================
# /handler_chat_member
try:
if [Link] in ["group", "supergroup"]:
group_id = [Link]
group_title = [Link] or "Unnamed"

# ========== User Joined ==========


if (
update_type == "chat_member"
and message.new_chat_member.status == "member"
and message.old_chat_member.status in ["left", "kicked"]
):
new_user = message.new_chat_member.user
first_name = new_user.first_name or "User"
username = f"@{new_user.username}" if new_user.username else first_name

welcome_settings = [Link](f"welcome_settings_{group_id}") or {
"enabled": False,
"message": "Welcome {name} to {group}!"
}

if welcome_settings.get("enabled"):
saved = [Link](f"welcome_message_{group_id}") or {}
welcome_text = [Link]("text", welcome_settings["message"])
welcome_text = welcome_text.replace("{name}", first_name)
welcome_text = welcome_text.replace("{username}", username)
welcome_text = welcome_text.replace("{group}", group_title)

welcome_photo = [Link]("photo")
welcome_video = [Link]("video")

buttons = []
btns = [Link](f"welcome_buttons_{group_id}") or []
for row in btns:
row_buttons = []
for btn in row:
row_buttons.append(InlineKeyboardButton(btn["text"],
url=btn["url"]))
if row_buttons:
[Link](row_buttons)

if welcome_photo:
[Link](
chat_id=group_id,
photo=welcome_photo,
caption=welcome_text,
parse_mode="html",
reply_markup=InlineKeyboardMarkup(buttons) if buttons else
None
)
elif welcome_video:
[Link](
chat_id=group_id,
video=welcome_video,
caption=welcome_text,
parse_mode="html",
reply_markup=InlineKeyboardMarkup(buttons) if buttons else
None
)
else:
[Link](
chat_id=group_id,
text=welcome_text,
parse_mode="html",
reply_markup=InlineKeyboardMarkup(buttons) if buttons else
None
)
raise ReturnCommand()

# ========== User Left ==========


if (
update_type == "chat_member"
and message.new_chat_member.status == "left"
and message.old_chat_member.status == "member"
):
left_user = message.new_chat_member.user
first_name = left_user.first_name or "User"
username = f"@{left_user.username}" if left_user.username else
first_name

goodbye_settings = [Link](f"goodbye_settings_{group_id}") or {
"enabled": False,
"message": "Goodbye {name}, we will miss you!"
}

if goodbye_settings.get("enabled"):
saved = [Link](f"goodbye_message_{group_id}") or {}
goodbye_text = [Link]("text", goodbye_settings["message"])
goodbye_text = goodbye_text.replace("{name}", first_name)
goodbye_text = goodbye_text.replace("{username}", username)
goodbye_text = goodbye_text.replace("{group}", group_title)

# Goodbye is plain text (no HTML parsing issues)


[Link](chat_id=group_id, text=goodbye_text)

raise ReturnCommand()
except Exception as e:
raise ReturnCommand()

/invite_settings
================
if [Link] != "private":
raise ReturnCommand()

u = message.from_user.id
group_id = [Link]()
ctx = [Link]("settings_context")

if not ctx or str(ctx["group_id"]) != group_id or ctx["admin_id"] != u:


[Link](u, "❌ No valid session found.")
raise ReturnCommand()
try:
member = [Link](group_id, u)
if [Link] not in ["administrator", "creator"]:
[Link](u, "🚫 You must be an admin in the group to manage these
settings.")
raise ReturnCommand()
except:
[Link](u, "❌ Could not verify your admin status.")
raise ReturnCommand()

group_title = [Link]("group_title", "Group")


text = (
f"<b>🔧 Invite Settings Panel</b>\n\n"
f"This controls who can generate invites, what is shown when someone joins, and
more.\n\n"
f"Group: <b>{group_title}</b>"
)

buttons = InlineKeyboardMarkup([
[InlineKeyboardButton("⚙️ Invite System Controls",
callback_data=f"/invite_config_menu {group_id}")],
[InlineKeyboardButton("🔢 Max Invite Limit", callback_data=f"/invite_max_config
{group_id}")],
[InlineKeyboardButton("🧩 Captcha Settings",
callback_data=f"/captcha_config_menu {group_id}")],
[InlineKeyboardButton("🔙 Back", callback_data="/settings_dm")]
])

try:
[Link](
chat_id=u,
message_id=message.message_id,
text=text,
parse_mode="html",
reply_markup=buttons
)
except:
[Link](u, text, parse_mode="html", reply_markup=buttons)

/lbformat
=========
if [Link] != "private":
raise ReturnCommand()

u = [Link]
group_id = [Link]()
ctx = [Link]("settings_context")

if not ctx or str(ctx["group_id"]) != group_id or [Link]("admin_id") != u:


[Link](u, "❌ No valid session found.")
raise ReturnCommand()
try:
member = [Link](group_id, u)
if [Link] not in ["administrator", "creator"]:
[Link](u, "🚫 You must be an admin in the group to manage these
settings.")
raise ReturnCommand()
except:
[Link](u, "❌ Could not verify your admin status.")
raise ReturnCommand()

group_title = [Link]("group_title", "Group")


selected = [Link](f"group_lb_limit_{group_id}") or 15

text = f"<b>📊 Leaderboard Settings for {group_title}</b>\n\nChoose how many top


inviters to show on the leaderboard."

options = [5, 10, 15, 20, 25, 30, 35, 40, 45, 50]
rows, temp = [], []

for num in options:


label = f"{num} ✅" if num == selected else str(num)
[Link](InlineKeyboardButton(label, callback_data=f"/lbformat_set
{group_id} {num}"))
if len(temp) == 4:
[Link](temp)
temp = []

if temp:
[Link](temp)

[Link]([InlineKeyboardButton("🔙 Back", callback_data="/leaderboard_settings "


+ group_id)])

try:
[Link](chat_id=u, message_id=message.message_id, text=text,
parse_mode="html", reply_markup=InlineKeyboardMarkup(rows))
except:
[Link](u, text, parse_mode="html",
reply_markup=InlineKeyboardMarkup(rows))

/lbformat_set
=============
if [Link] != "private":
raise ReturnCommand()

u = [Link]
split = [Link]().split(" ")

if len(split) != 2:
[Link](u, "⚠️ Invalid usage.")
raise ReturnCommand()

group_id, num_str = split


ctx = [Link]("settings_context")

if not ctx or str(ctx["group_id"]) != group_id or [Link]("admin_id") != u:


[Link](u, "❌ No valid session found.")
raise ReturnCommand()
try:
member = [Link](group_id, u)
if [Link] not in ["administrator", "creator"]:
[Link](u, "🚫 You must be an admin in the group to manage these
settings.")
raise ReturnCommand()
except:
[Link](u, "❌ Could not verify your admin status.")
raise ReturnCommand()
try:
new_limit = int(num_str)
if new_limit < 5 or new_limit > 50:
raise ValueError()
[Link](f"group_lb_limit_{group_id}", new_limit)
except:
[Link](u, "⚠️ Invalid number. Please choose between 5 and 50.")
raise ReturnCommand()

options = [5, 10, 15, 20, 25, 30, 35, 40, 45, 50]
rows, temp = [], []

for num in options:


label = f"{num} ✅" if num == new_limit else str(num)
[Link](InlineKeyboardButton(label, callback_data=f"/lbformat_set
{group_id} {num}"))
if len(temp) == 4:
[Link](temp)
temp = []

if temp:
[Link](temp)

[Link]([InlineKeyboardButton("🔙 Back", callback_data=f"/leaderboard_settings


{group_id}")])

try:
[Link](chat_id=u, message_id=message.message_id,
reply_markup=InlineKeyboardMarkup(rows))
except:
pass

/lbreset
========
# Command: /lbreset <group_id> <yes/no>
if [Link] not in ["group", "supergroup", "private"]:
raise ReturnCommand()

u = message.from_user.id
params = [Link]().split() if params else []

if len(params) < 1:
[Link](u, "❌ Group ID missing.")
raise ReturnCommand()

group_id = int(params[0])
choice = params[1].lower() if len(params) > 1 else ""

# ✅ Admin check
try:
member = [Link](group_id, u)
if [Link] not in ["administrator", "creator"]:
[Link](u, "🚫 Only admins can reset the leaderboard.")
raise ReturnCommand()
except:
[Link](u, "⚠️ Failed to verify permissions.")
raise ReturnCommand()

# ✅ Prepare text for editing later


ctx = [Link]("settings_context") or {}
group_title = [Link]("group_title", "Group")
base_text = f"🏆 *Leaderboard Settings for:* {group_title}\n\nManage how the
leaderboard works in your group."
buttons = {
"inline_keyboard": [
[{"text": " Leaderboard Trigger", "callback_data": f"/lbtrigger
{group_id}"}],
[{"text": "🎨 Edit Format", "callback_data": f"/lbformat {group_id}"}],
[{"text": "🧹 Reset Leaderboard", "callback_data": f"/lbreset {group_id}"}],
[{"text": "🔙 Back", "callback_data": "/settings_dm"}]
]
}

# ✅ Reset leaderboard if confirmed


if choice == "yes":
# Delete invite leaderboard
inviter_list = [Link](f"inviter_list_{group_id}") or []
for inviter in inviter_list:
[Link](f"invite_counts_{group_id}_{inviter}")
[Link](f"invited_users_{group_id}_{inviter}")
[Link](f"inviter_list_{group_id}")
[Link](f"resettable_invite_keys_{group_id}")

# Delete activity leaderboard


user_list = [Link](f"activity_user_list_{group_id}") or []
for uid in user_list:
[Link](f"user_points_{group_id}_{uid}")
[Link](f"activity_cooldown_{group_id}_{uid}")
[Link](f"activity_user_list_{group_id}")

try:
[Link](chat_id=group_id, message_id=message.message_id)
except:
pass # silently ignore if message doesn't exist

text = "🧹 Leaderboard has been successfully reset.\n\n" + base_text

elif choice == "no":


try:
[Link](chat_id=group_id, message_id=message.message_id)
except:
pass # silently ignore

text = "❌ Operation aborted. Leaderboard remains intact.\n\n" + base_text

else:
# Ask for confirmation
btns = InlineKeyboardMarkup([
[
InlineKeyboardButton("✅ Yes", callback_data=f"/lbreset {group_id}
yes"),
InlineKeyboardButton("❌ No", callback_data=f"/lbreset {group_id} no")
]
])
try:
[Link](
chat_id=u,
message_id=message.message_id,
text=f"⚠️ This will clear the *invite & activity leaderboard* for the
group ({group_id}).\n\n"
"Are you sure you want to proceed?",
parse_mode="Markdown",
reply_markup=btns
)
except:
[Link](
u,
f"⚠️ This will clear the *invite & activity leaderboard* for the group
({group_id}).\n\n"
"Are you sure you want to proceed?",
parse_mode="Markdown",
reply_markup=btns
)
raise ReturnCommand()

# ✅ Always edit back to leaderboard settings menu


try:
[Link](
chat_id=u,
message_id=message.message_id,
text=text,
parse_mode="Markdown",
reply_markup=buttons
)
except:
[Link](u, text, parse_mode="Markdown", reply_markup=buttons)

/lbtrigger
==========
if [Link] != "private":
raise ReturnCommand()

group_id = [Link]()
u = [Link]
ctx = [Link]("settings_context")

if not ctx or str(ctx["group_id"]) != group_id:


[Link](u, "❌ Invalid or expired session.")
raise ReturnCommand()
try:
member = [Link](group_id, u)
if [Link] not in ["administrator", "creator"]:
[Link](u, "🚫 You must be an admin in the group to manage these
settings.")
raise ReturnCommand()
except:
[Link](u, "❌ Could not verify your admin status.")
raise ReturnCommand()

group_title = [Link]("group_title", "Group")


current = [Link](f"group_lb_trigger_{group_id}") or "everyone"

options = [("admins", "Admins Only"), ("everyone", "Everyone")]


buttons = [[InlineKeyboardButton(
f"{'✅' if val == current else '❌'} {label}",
callback_data=f"/set_lbtrigger {group_id} {val}"
)] for val, label in options]

[Link]([InlineKeyboardButton("🔙 Back", callback_data="/leaderboard_settings


" + group_id)])

text = f"⚙️ <b>Leaderboard Trigger for:</b> <code>{group_title}</code>\n\nChoose


who can trigger the leaderboard."

try:
[Link](chat_id=u, message_id=message.message_id, text=text,
parse_mode="html", reply_markup=InlineKeyboardMarkup(buttons))
except:
[Link](u, text, parse_mode="html",
reply_markup=InlineKeyboardMarkup(buttons))

/leaderboard_settings
=====================
# /leaderboard_settings_dm <group_id>
if [Link] != "private":
raise ReturnCommand()

group_id = [Link]()
ctx = [Link]("settings_context")

if not ctx or str(ctx["group_id"]) != group_id:


[Link](u, "❌ Invalid or expired session.")
raise ReturnCommand()
try:
member = [Link](group_id, u)
if [Link] not in ["administrator", "creator"]:
[Link](u, "🚫 You must be an admin in the group to manage these
settings.")
raise ReturnCommand()
except:
[Link](u, "❌ Could not verify your admin status.")
raise ReturnCommand()

group_title = [Link]("group_title", "Group")

text = f"🏆 *Leaderboard Settings for:* {group_title}\n\nManage how the leaderboard


works in your group."

buttons = {
"inline_keyboard": [
[{"text": " Leaderboard Trigger", "callback_data": f"/lbtrigger
{group_id}"}],
[{"text": "🎨 Edit Format", "callback_data": f"/lbformat {group_id}"}],
[{"text": "♻️ Reset Leaderboard", "callback_data": f"/lbreset
{group_id}"}],
[{"text": "🔙 Back", "callback_data": "/settings_dm"}]
]
}

try:
[Link](
chat_id=[Link],
message_id=message.message_id,
text=text,
parse_mode="markdown",
reply_markup=buttons
)
except:
[Link](u, text, parse_mode="markdown", reply_markup=buttons)

/list_blocked_words
===================
# Command: /list_blocked_words
if [Link] != "private":
raise ReturnCommand()

u = message.from_user.id
ctx = [Link]("settings_context")

if not ctx or [Link]("admin_id") != u:


[Link](u, "❌ No active session. Please use /settings in your group
first.")
raise ReturnCommand()

group_id = ctx["group_id"]
group_title = ctx["group_title"]

# ✅ Verify admin
try:
member = [Link](group_id, u)
if [Link] not in ["administrator", "creator"]:
[Link](u, "🚫 You must be an admin to view these settings.")
raise ReturnCommand()
except:
[Link](u, "❌ Could not verify your admin status.")
raise ReturnCommand()

# ✅ Load blocked words


blocked_words = [Link](f"blocked_words_{group_id}") or []

if not blocked_words:
text = f"📜 *Blocked Words for {group_title}:*\n\n_No blocked words set yet._"
else:
formatted = []
for w in blocked_words:
mode_icon = ""✂️
if w["mode"] == "precise" else " "
mode_name = "Precise" if w["mode"] == "precise" else "Included"
[Link](f"• `{w['word']}` — {mode_icon} *{mode_name}*")
word_list = "\n".join(formatted)
text = f"📜 *Blocked Words for {group_title}:*\n\n{word_list}"

btns = {
"inline_keyboard": [
[{"text": "➕ Add Blocked Word", "callback_data": f"/add_blocked_word
{group_id}"}],
[{"text": "➖ Remove Blocked Word", "callback_data": f"/remove_blocked_word
{group_id}"}],
[{"text": "🔙 Back", "callback_data": f"/word_blocks {group_id}"}]
]
}

try:
[Link](
chat_id=u,
message_id=message.message_id,
text=text,
parse_mode="markdown",
reply_markup=btns
)
except:
[Link](
u,
text,
parse_mode="markdown",
reply_markup=btns
)

/mute
=====
if [Link] not in ["group", "supergroup"]:
[Link]([Link], "⚠️ This command can only be used in groups.")
raise ReturnCommand()

if not params:
[Link]([Link], "❗ Usage: /mute <user_id or @username>")
raise ReturnCommand()

target = params[0]

try:
# Try treating it as an integer user_id
target_user_id = int(target)
except Exception:
# Otherwise, assume it's a username string like @username
target_user_id = target

try:
[Link](
chat_id=[Link],
user_id=target_user_id,
permissions={
"can_send_messages": False,
"can_send_media_messages": False,
"can_send_polls": False,
"can_add_web_page_previews": False,
"can_change_info": False,
"can_invite_users": True,
"can_pin_messages": False
}
)
[Link]([Link], f"✅ User <code>{target_user_id}</code> has been
muted.", {"parse_mode": "HTML"})

except Exception:
[Link]([Link], "❌ Failed to mute user.")

/remove_blocked_word
====================
# Command: /remove_blocked_word
if [Link] != "private":
raise ReturnCommand()

u = message.from_user.id

# ✅ Extract group_id from params


if not params:
[Link](u, "❌ Group ID missing.")
raise ReturnCommand()

# If params is a string, strip and split by space


group_id = int([Link]().split()[0])

# ✅ Verify admin
try:
member = [Link](group_id, u)
if [Link] not in ["administrator", "creator"]:
[Link](u, "🚫 You must be an admin to manage blocked words.")
raise ReturnCommand()
except:
[Link](u, "❌ Could not verify your admin status.")
raise ReturnCommand()

# ✅ Save context
[Link]("remove_blocked_word_context", {"group_id": group_id})

# ✅ Edit previous message if exists, otherwise send new


text = "✏️ Please send the exact word you want to remove from the block list.\n\
nSend `X` to cancel."
btns = None # no buttons needed at this step

try:
[Link](
chat_id=u,
message_id=message.message_id,
text=text,
parse_mode="markdown",
reply_markup=btns
)
except:
[Link](u, text, parse_mode="markdown", reply_markup=btns)

# ✅ Handle next input


[Link]("/save_removed_word")

/reset_activity
===============
# /reset_activity <group_id> [yes|no]
if [Link] != "private":
raise ReturnCommand()

u = [Link]
split = [Link]().split(" ")
group_id = split[0]
confirm = split[1] if len(split) > 1 else None

ctx = [Link]("settings_context")

# ✅ Verify session & admin


if not ctx or str([Link]("group_id")) != group_id:
[Link](u, "❌ Invalid or expired session.")
raise ReturnCommand()

try:
member = [Link](group_id, u)
if [Link] not in ["administrator", "creator"]:
[Link](u, "🚫 You must be an admin in the group to reset activity.")
raise ReturnCommand()
except:
[Link](u, "❌ Could not verify your admin status.")
raise ReturnCommand()

# ✅ If no confirmation yet, ask


if confirm not in ["yes", "no"]:
buttons = [
[InlineKeyboardButton("✅ Yes, reset all activity",
callback_data=f"/reset_activity {group_id} yes")],
[InlineKeyboardButton("❌ No, cancel", callback_data=f"/reset_activity
{group_id} no")],
[InlineKeyboardButton("🔙 Back", callback_data=f"/activity_settings
{group_id}")]
]

text = (
f"<b>⚠️ Reset Activity Points</b>\n\n"
f"Are you sure you want to reset all user activity points for this group? "
f"This action cannot be undone."
)

try:
[Link](
chat_id=u,
message_id=message.message_id,
text=text,
parse_mode="html",
reply_markup=InlineKeyboardMarkup(buttons)
)
except:
[Link](u, text, parse_mode="html",
reply_markup=InlineKeyboardMarkup(buttons))
raise ReturnCommand()

# ✅ If "no", go back to Activity Settings


if confirm == "no":
settings = [Link](f"activity_settings_{group_id}") or {
"trigger": "admins",
"count_media": True,
"count_admins": False,
"msg_cldwn": 0
}

# Button labels
trigger_label = f"Leaderboard Trigger ({'Admins Only' if
settings['trigger']=='admins' else 'Everyone'})"
count_label = f"Count Media ({'ON ✅' if settings['count_media'] else 'OFF'})"
count_admin_label = f"Count Admins ({'ON ✅' if settings['count_admins'] else
'OFF'})"
cooldown_label = f"Message Cooldown ({settings['msg_cldwn']} s)"

buttons = [
[InlineKeyboardButton(trigger_label, callback_data=f"/toggle_activity
{group_id} trigger")],
[InlineKeyboardButton(count_label, callback_data=f"/toggle_activity
{group_id} count_media")],
[InlineKeyboardButton(cooldown_label, callback_data=f"/activity_cooldown
{group_id}")],
[InlineKeyboardButton(count_admin_label, callback_data=f"/toggle_activity
{group_id} count_admins")],
[InlineKeyboardButton("♻️ Reset Activity", callback_data=f"/reset_activity
{group_id}")],
[InlineKeyboardButton("🔙 Back", callback_data="/settings_dm")]
]

text = (
f"<b>📊 Activity Settings for:</b> {[Link]('group_title', 'Group')}\n\n"
f"• <b>Leaderboard Trigger</b>: Choose if only admins or everyone can use
the leaderboard.\n"
f"• <b>Count Media</b>: Decide if sending photos, GIFs, or stickers also
give activity points.\n"
f"• <b>Count Admins</b>: Decide if admin messages also count.\n"
f"• <b>Message Cooldown</b>: Limit how often activity points are given.\n"
f"• <b>Reset Activity</b>: Clears all saved activity points for this
group."
)

try:
[Link](chat_id=u, message_id=message.message_id,
text=text, parse_mode="html",
reply_markup=InlineKeyboardMarkup(buttons))
except:
pass
raise ReturnCommand()

# ✅ If "yes", delete all user points for this group


user_list_key = f"activity_user_list_{group_id}"
user_ids = [Link](user_list_key) or []

deleted_count = 0
for uid_str in user_ids:
points_key = f"user_points_{group_id}_{uid_str}"
[Link](points_key)
deleted_count += 1

# ✅ Delete the stored user list itself


[Link](user_list_key)

# ✅ Confirm deletion with edit


buttons = [[InlineKeyboardButton("🔙 Back", callback_data=f"/activity_settings
{group_id}")]]
[Link](
chat_id=u,
message_id=message.message_id,
text=f"✅ All activity points have been cleared for {deleted_count} users in
this group.",
parse_mode="html",
reply_markup=InlineKeyboardMarkup(buttons)
)

/save_blocked_word
==================
# Command: /save_blocked_word
if [Link] != "private":
raise ReturnCommand()

u = message.from_user.id
ctx = [Link]("blocked_word_context")

if not ctx:
[Link](u, "❌ No blocked word session found. Please start again with
/add_blocked_word.")
raise ReturnCommand()

group_id = ctx["group_id"]
mode = ctx["mode"]

# ✅ Verify admin
try:
member = [Link](group_id, u)
if [Link] not in ["administrator", "creator"]:
[Link](u, "🚫 You must be an admin to manage blocked words.")
raise ReturnCommand()
except:
[Link](u, "❌ Could not verify your admin status.")
raise ReturnCommand()

# ✅ Cancel check
word = [Link]()
if [Link]() == "x":
[Link](u, "❌ Blocked word creation cancelled.")
[Link]("blocked_word_context")
[Link]("/list_blocked_words")
raise ReturnCommand()

# ✅ Load existing blocked words


blocked_words = [Link](f"blocked_words_{group_id}") or []

# ✅ Save new blocked word


blocked_words.append({"word": word, "mode": mode})
[Link](f"blocked_words_{group_id}", blocked_words)

# ✅ Clear session context


[Link]("blocked_word_context")

[Link](
u,
f"✅ Blocked word added:\n• Word: `{word}`\n• Mode: *{[Link]()}*",
parse_mode="markdown"
)

# ✅ Refresh list
[Link]("/list_blocked_words")

/save_buttons
=============
if [Link] != "private":
raise ReturnCommand()

u = [Link]
group_id = [Link]("welcome_edit_group")
ctx = [Link]("settings_context")

if not group_id:
[Link](u, "❌ No active session. Please start again.")
raise ReturnCommand()

# ✅ Verify admin
try:
member = [Link](group_id, u)
if [Link] not in ["administrator", "creator"]:
[Link](u, "🚫 You must be an admin to manage these settings.")
raise ReturnCommand()
except:
[Link](u, "❌ Could not verify your admin status.")
raise ReturnCommand()

# ✅ Handle skip
if [Link] and [Link]().upper() == "X":
[Link](f"welcome_buttons_{group_id}") # remove old buttons if any
[Link](u, "✅ Skipped adding buttons.")
[Link]("/welcome_goodbye")
raise ReturnCommand()

# ✅ Parse button input


button_input = [Link]()
rows = button_input.split("\n") # newline = new row
buttons = []

for row_text in rows:


row_text = row_text.strip()
if not row_text:
continue

row_buttons = []
# split row by "-" → multiple buttons in same row
parts = row_text.split(" - ")
for part in parts:
try:
text, link = [Link]().split(" ", 1)
if not [Link]("http"):
raise ValueError
row_buttons.append({"text": text, "url": link})
except:
[Link](
u,
f"❌ Invalid button format in row: `{row_text}`\n\n"
"📌 Format:\n"
"[Text] [Link] - [Text] [Link]\n"
"➡️ `-` = same row\n"
"➡️ New line = new row\n\n"
"Send `X` to skip.",
parse_mode="Markdown"
)
[Link]("/save_buttons")
raise ReturnCommand()
if row_buttons:
[Link](row_buttons)

# ✅ Save buttons
[Link](f"welcome_buttons_{group_id}", buttons)

[Link](u, "✅ Inline buttons saved successfully!")


[Link]("/welcome_goodbye")

/save_goodbye
=============
if [Link] == "private":
u = [Link]
# Retrieve group ID from temporary storage
group_id = [Link]("goodbye_edit_group")
if not group_id:
[Link]("❌ No active session.")
raise ReturnCommand()

# Retrieve settings context to verify session


ctx = [Link]("settings_context")
if not ctx or str([Link]("group_id")) != group_id:
[Link](u, "❌ Invalid or expired session.")
raise ReturnCommand()

group_title = [Link]("group_title", "Group")

# Attempt to verify admin status (error handling improved)


try:
member = [Link](group_id, u)
if [Link] not in ["administrator", "creator"]:
[Link](u, "🚫 You must be an admin in the group to use this
function.")
raise ReturnCommand()
except:
[Link](u, "❌ Could not verify your admin status in the group.")
raise ReturnCommand()

# Check for cancellation


if [Link] and [Link]().upper() == "X":
[Link]("❌ Goodbye message setup cancelled.")
[Link]("/goodbye_message") # Back to main menu
raise ReturnCommand()

# Extract message parts, handling for both image and text messages
goodbye_text = [Link] if [Link] else [Link] if
[Link] else ""
goodbye_photo = [Link][-1].file_id if [Link] else None
goodbye_video = [Link].file_id if [Link] else None

# Check HTML formatting and give a user-friendly warning if invalid


try:
[Link](text=goodbye_text, chat_id=u, parse_mode="HTML",
disable_notification=True)
except:
[Link](
chat_id=u,
text="❌ Invalid HTML formatting found. Please check and try again.
Basic tags like <b>, <i>, <a> are allowed.",
parse_mode="HTML"
)
[Link]("/save_goodbye")
raise ReturnCommand()

# Save settings (improved feedback and handling)


try:
[Link](f"goodbye_message_{group_id}", {
"text": goodbye_text,
"photo": goodbye_photo,
"video": goodbye_video
})

saved = [Link](f"goodbye_message_{group_id}")

if [Link]("photo"):
[Link](
photo=saved["photo"],
caption=[Link]("text", "✅ Goodbye message saved successfully!"),
parse_mode="HTML"
)
elif [Link]("video"):
[Link](
video=saved["video"],
caption=[Link]("text", "✅ Goodbye message saved successfully!"),
parse_mode="HTML"
)
else:
[Link](
chat_id=u,
text=f"✅ Goodbye message saved successfully!\n\n{[Link]('text',
'')}",
parse_mode="HTML"
)
except:
[Link](u, "❌ Could not save goodbye settings. Please try again.")

# Return to the main settings menu


[Link]("/goodbye_message")
else:
[Link]([Link], "❌ This command must be used in private.")

/save_removed_word
==================
# Command: /save_removed_word
if [Link] != "private":
raise ReturnCommand()

u = message.from_user.id
ctx = [Link]("remove_blocked_word_context")

if not ctx:
[Link](u, "❌ No removal session found. Please start again with
/remove_blocked_word.")
raise ReturnCommand()

group_id = ctx["group_id"]

# ✅ Verify admin
try:
member = [Link](group_id, u)
if [Link] not in ["administrator", "creator"]:
[Link](u, "🚫 You must be an admin to manage blocked words.")
raise ReturnCommand()
except:
[Link](u, "❌ Could not verify your admin status.")
raise ReturnCommand()

# ✅ Cancel check
word = [Link]()
if [Link]() == "x":
[Link](u, "❌ Blocked word removal cancelled.")
[Link]("remove_blocked_word_context")
[Link]("/list_blocked_words")
raise ReturnCommand()

# ✅ Load blocked words


blocked_words = [Link](f"blocked_words_{group_id}") or []

# ✅ Find & remove


new_list = [w for w in blocked_words if w["word"].lower() != [Link]()]

if len(new_list) == len(blocked_words):
[Link](u, f"⚠️ No blocked word found matching `{word}`.",
parse_mode="markdown")
else:
[Link](f"blocked_words_{group_id}", new_list)
[Link](u, f"✅ Blocked word `{word}` has been removed.",
parse_mode="markdown")

# ✅ Clear context
[Link]("remove_blocked_word_context")

# ✅ Refresh list
[Link]("/list_blocked_words")

/save_welcome
=============
# /save_welcome
if [Link] == "private":
u = [Link]
# Retrieve group ID from temporary storage
group_id = [Link]("welcome_edit_group")
if not group_id:
[Link](u, "❌ No active session.")
raise ReturnCommand()

# Retrieve settings context to verify session


ctx = [Link]("settings_context")
if not ctx or str([Link]("group_id")) != group_id:
[Link](u, "❌ Invalid or expired session.")
raise ReturnCommand()

group_title = [Link]("group_title", "Group")

# Attempt to verify admin status


try:
member = [Link](group_id, u)
if [Link] not in ["administrator", "creator"]:
[Link](u, "🚫 You must be an admin in the group to use this
function.")
raise ReturnCommand()
except:
[Link](u, "❌ Could not verify your admin status in the group.")
raise ReturnCommand()

# Check for cancellation


if [Link] and [Link]().upper() == "X":
[Link]("❌ Welcome message setup cancelled.")
[Link]("/welcome_message") # Back to main menu
raise ReturnCommand()

# Extract text/media
welcome_text = [Link] if [Link] else [Link] if
[Link] else ""
welcome_photo = [Link][-1].file_id if [Link] else None
welcome_video = [Link].file_id if [Link] else None

# Check HTML formatting


try:
[Link](text=welcome_text, chat_id=u, parse_mode="HTML",
disable_notification=True)
except:
[Link](
chat_id=u,
text="❌ Invalid HTML formatting found. Please check and try again.
Basic tags like <b>, <i>, <a> are allowed.",
parse_mode="HTML"
)
[Link]("/save_welcome")
raise ReturnCommand()

# Save welcome message


try:
[Link](f"welcome_message_{group_id}", {
"text": welcome_text,
"photo": welcome_photo,
"video": welcome_video
})

saved = [Link](f"welcome_message_{group_id}")

if [Link]("photo"):
[Link](
photo=saved["photo"],
caption=[Link]("text", "✅ Welcome message saved successfully!"),
parse_mode="HTML"
)
elif [Link]("video"):
[Link](
video=saved["video"],
caption=[Link]("text", "✅ Welcome message saved successfully!"),
parse_mode="HTML"
)
else:
[Link](
chat_id=u,
text=f"✅ Welcome message saved successfully!\n\n{[Link]('text',
'')}",
parse_mode="HTML"
)
except:
[Link]("❌ Could not save welcome settings. Please try again.")

# ✅ Ask for inline buttons (after successful save)


[Link](
"✅ Welcome message saved!\n\n"
"Do you want to add inline buttons?\n\n"
"📌 Format:\n"
"[Text] [Link] - [Text] [Link]\n"
"➡️ `-` = buttons in the same row\n"
"➡️ New line = new row\n\n"
"Example:\n"
"Google [Link] - Bing [Link]
"Yahoo [Link]
"Send `X` to skip."
)
[Link]("/save_buttons")
else:
[Link]([Link], "❌ This command must be used in private.")

/scan_mode
==========
if [Link] != "private":
raise ReturnCommand()

group_id = [Link]()
u = [Link]
ctx = [Link]("settings_context")

# ✅ Verify session
if not ctx or str(ctx["group_id"]) != group_id:
[Link](u, "❌ Invalid or expired session.")
raise ReturnCommand()

group_title = [Link]("group_title", "Group")

# ✅ Verify user is still admin in group


try:
member = [Link](group_id, u)
if [Link] not in ["administrator", "creator"]:
[Link](u, "🚫 You must be an admin in the group to manage these
settings.")
raise ReturnCommand()
except:
[Link](u, "❌ Could not verify your admin status.")
raise ReturnCommand()

stored_modes = [Link](f"group_modes_{group_id}")
modes = stored_modes if stored_modes is not None else []

# ✅ Available modes (no Ads/Links)


all_modes = {
"toxicity": "Toxicity",
"profanity": "Profanity",
"nsfw": "NSFW",
"strict_ai": "Passive Aggression",
"english_only": "English Only",
"pm_block": "DM/PM Ask",
"tag_block": "Admin Pings"
}

buttons = [[InlineKeyboardButton(
f"{'✅' if key in modes else '❌'} {label}",
callback_data=f"/toggle_mode {group_id} {key}"
)] for key, label in all_modes.items()]

[Link]([InlineKeyboardButton("🔙 Back", callback_data="/settings_dm")])

text = f"<b> Scan Mode for:</b> {group_title}\n\nTap to toggle scan types."

try:
[Link](chat_id=u, message_id=message.message_id, text=text,
parse_mode="html", reply_markup=InlineKeyboardMarkup(buttons))
except:
[Link](u, text, parse_mode="html",
reply_markup=InlineKeyboardMarkup(buttons))

/set_captcha
============
if [Link] != "private":
raise ReturnCommand()

u = message.from_user.id
parts = [Link]().split(" ")
if len(parts) != 2:
raise ReturnCommand()

group_id, captcha_type = parts


ctx = [Link]("settings_context")

if not ctx or str(ctx["group_id"]) != group_id or [Link]("admin_id") != u:


[Link](u, "❌ No valid session found.")
raise ReturnCommand()

try:
member = [Link](group_id, u)
if [Link] not in ["administrator", "creator"]:
[Link](u, "🚫 You must be an admin in the group to manage these
settings.")
raise ReturnCommand()
except:
[Link](u, "❌ Could not verify your admin status.")
raise ReturnCommand()
if captcha_type not in ["emoji", "math"]:
[Link](u, "❌ Invalid captcha type.")
raise ReturnCommand()

# ✅ Save new selection


config = [Link](f"group_invite_config_{group_id}") or {}
config["captcha_type"] = captcha_type
[Link](f"group_invite_config_{group_id}", config)

# ✅ Build and edit the updated menu directly


group_title = [Link]("group_title", "Group")
selected = config["captcha_type"]

text = (
f"<b>🤖 Captcha Settings</b>\n\n"
f"Choose the verification method new users must complete to join:\n\n"
f"Group: <b>{group_title}</b>"
)

options = {
"emoji": "Emoji Captcha",
"math": "Math Captcha"
}

buttons = []
for key, label in [Link]():
emoji_mark = "✅" if selected == key else "❌"
[Link]([InlineKeyboardButton(f"{emoji_mark} {label}",
callback_data=f"/set_captcha {group_id} {key}")])
[Link]([InlineKeyboardButton("🔙 Back to Invite Settings",
callback_data=f"/invite_settings {group_id}")])
try:
[Link](
chat_id=u,
message_id=message.message_id,
text=text,
parse_mode="html",
reply_markup=InlineKeyboardMarkup(buttons)
)
except:
pass

/set_invite
===========
# /set_invite <group_id> <setting_key>
if [Link] != "private":
raise ReturnCommand()

u = [Link]
parts = [Link]().split(" ")
if len(parts) != 2:
raise ReturnCommand()

group_id, setting_key = parts


ctx = [Link]("settings_context")

if not ctx or str(ctx["group_id"]) != group_id or ctx["admin_id"] != u:


[Link](u, "❌ No valid session found.")
raise ReturnCommand()
try:
member = [Link](group_id, u)
if [Link] not in ["administrator", "creator"]:
[Link](u, "🚫 You must be an admin in the group to manage these
settings.")
raise ReturnCommand()
except:
[Link](u, "❌ Could not verify your admin status.")
raise ReturnCommand()
group_title = [Link]("group_title", "Group")

# ✅ Toggle and save setting


config = [Link](f"group_invite_config_{group_id}") or {}
config[setting_key] = not [Link](setting_key, False)
[Link](f"group_invite_config_{group_id}", config)

# ✅ Labels and descriptions


options = {
"linkgen": "Invite Link Generation",
"notify": "Group Invite Notification",
"verify_ai": "Invite Verification AI"
}
descriptions = {
"linkgen": "Enable or disable invite link creation in the group.",
"notify": "Toggle whether a welcome message is shown when a user joins via
invite.",
"verify_ai": "Use AI to analyze who is joining (recommended)."
}

# ✅ Buttons
buttons = []
for key, label in [Link]():
emoji = "✅" if [Link](key, False) else "❌"
[Link]([InlineKeyboardButton(f"{emoji} {label}",
callback_data=f"/set_invite {group_id} {key}")])
[Link]([InlineKeyboardButton("🔙 Back", callback_data=f"/invite_settings
{group_id}")])

# ✅ Info text
text = f"<b>🔗 Invite Settings for:</b> {group_title}\n\n"
for key, label in [Link]():
state = "[ON]" if [Link](key, False) else "[OFF]"
text += f"• <b>{label}</b> {state}\n — {descriptions[key]}\n\n"

# ✅ Try to edit, fallback silent


try:
[Link](
chat_id=u,
message_id=message.message_id,
text=text,
parse_mode="html",
reply_markup=InlineKeyboardMarkup(buttons)
)
except:
pass

/set_invite_limit
=================
# /set_invite_limit <group_id> <value>
if [Link] != "private":
raise ReturnCommand()

u = [Link]
parts = [Link]().split(" ", 1)
if len(parts) != 2:
raise ReturnCommand()

group_id, val = parts


ctx = [Link]("settings_context")

if not ctx or str(ctx["group_id"]) != group_id or ctx["admin_id"] != u:


[Link](u, "❌ No valid session found.")
raise ReturnCommand()
try:
member = [Link](group_id, u)
if [Link] not in ["administrator", "creator"]:
[Link](u, "🚫 You must be an admin in the group to manage these
settings.")
raise ReturnCommand()
except:
[Link](u, "❌ Could not verify your admin status.")
raise ReturnCommand()
if val == "custom":
try:
[Link](chat_id=u, message_id=message.message_id)
except:
pass
[Link]("🧮 Send the custom invite limit...\n\nSend <b>X</b> to
cancel.", parse_mode="html")
[Link]("custom_limit_group", group_id)
[Link]("/set_max_custom")
raise ReturnCommand()

# ✅ Update the config


config = [Link](f"group_invite_config_{group_id}") or {}
if val == "off":
[Link]("max_invites", None)
else:
try:
num = int(val)
if num <= 0:
raise ValueError()
config["max_invites"] = num
except:
[Link](u, "❗ Invalid number. Please choose a positive integer.")
raise ReturnCommand()

[Link](f"group_invite_config_{group_id}", config)

# ✅ Rebuild updated UI (exact same as /invite_max_config)


group_title = [Link]("group_title", "Group")
limit = [Link]("max_invites")
current = f"{limit} invites" if limit else "No limit (OFF)"

text = (
f"<b>🎯 Invite Limit Settings</b>\n\n"
f"Define how many invite links each user can generate.\n\n"
f"Group: <b>{group_title}</b>\n"
f"Current limit: <b>{current}</b>"
)

btns = []
presets = [("No limit (OFF)", None), ("10 invites", 10), ("50 invites", 50), ("100
invites", 100)]
for label, val in presets:
emoji = "✅" if val == limit else "❌"
callback = f"/set_invite_limit {group_id} {val}" if val is not None else
f"/set_invite_limit {group_id} off"
[Link]([InlineKeyboardButton(f"{emoji} {label}", callback_data=callback)])

custom_label = f"Custom ✅ ({limit})" if limit and limit not in [10, 50, 100] else
"Custom…"
[Link]([InlineKeyboardButton(custom_label, callback_data=f"/set_invite_limit
{group_id} custom")])
[Link]([InlineKeyboardButton("🔙 Back to Invite Settings",
callback_data=f"/invite_settings {group_id}")])

try:
[Link](
chat_id=u,
message_id=message.message_id,
text=text,
parse_mode="html",
reply_markup=InlineKeyboardMarkup(btns)
)
except:
[Link](u, text, parse_mode="html",
reply_markup=InlineKeyboardMarkup(btns))
/settings_dm
============
# Command: /settings_dm
if [Link] != "private":
raise ReturnCommand()

u = message.from_user.id
ctx = [Link]("settings_context")

if not ctx or [Link]("admin_id") != u:


[Link](u, "❌ No active session. Please use /settings in your group
first.")
raise ReturnCommand()

group_title = ctx["group_title"]
group_id = ctx["group_id"]

text = f"⚙️ *Settings for:* {group_title}\n\nChoose what you want to manage:"

btns = {
"inline_keyboard": [
[{"text": "👋 Welcome & Goodbye Settings", "callback_data":
f"/welcome_goodbye {group_id}"}],
[{"text": "🚫 Block Settings", "callback_data": f"/block_settings
{group_id}"}],
[{"text": "🧹 Filter Settings", "callback_data": f"/filter_settings
{group_id}"}],
[{"text": "🧠 Scan Settings", "callback_data": f"/scan_mode {group_id}"}],
[{"text": "🏆 Leaderboard Settings", "callback_data":
f"/leaderboard_settings {group_id}"}],
[{"text": "🔗 Invite Settings", "callback_data": f"/invite_settings
{group_id}"}],
[{"text": "📊 Activity Settings", "callback_data": f"/activity_settings
{group_id}"}],
[{"text": "📝 Word Blocks", "callback_data": f"/word_blocks {group_id}"}],
[{"text": "❌ Close", "callback_data": "/close_dm"}]
]
}

try:
[Link](
chat_id=u,
message_id=message.message_id,
text=text,
parse_mode="markdown",
reply_markup=btns
)
except:
[Link](
u,
text,
parse_mode="markdown",
reply_markup=btns
)

/start_swr
==========
if [Link] not in ["group", "supergroup"]:
raise ReturnCommand()

group_id = [Link]

# Load session
session = [Link](f"swr_session_{group_id}")
if not session:
[Link](group_id, "❌ No SWR session found. Start a new game with `/swr
<rounds>`")
raise ReturnCommand()

# Increment round
session["rounds_done"] += 1
[Link](f"swr_session_{group_id}", session)

if session["rounds_done"] > session["rounds_total"]:


[Link](group_id, "🏁 The Secret Word Race has finished!")

players = [Link]("players", {})


if players:
leaderboard = "\n".join([
f"• {pdata['name']}: {pdata['score']} pts"
for uid, pdata in sorted([Link](), key=lambda x: x[1]["score"],
reverse=True)
])
[Link](
group_id,
f"📊 Final Leaderboard:\n{leaderboard}\n\nStart a new game with `/swr
<rounds>`",
parse_mode="Markdown"
)
else:
[Link](group_id, "_No points were scored this session._",
parse_mode="Markdown")

[Link](f"swr_session_{group_id}")
raise ReturnCommand()

try:
response = [Link]("[Link]
10000-english/master/[Link]")
word_list = str([Link]).splitlines()
filtered_words = [w for w in word_list if 3 <= len(w) <= 8]

word = [Link](filtered_words)
session["current_word"] = word
[Link](f"swr_session_{group_id}", session)

image_url = f"[Link]
[Link](
chat_id=group_id,
photo=image_url,
caption="📝 First person to type the secret word in the chat wins this
round!",
parse_mode="Markdown"
)
[Link]("/check_swr")
except Exception as e:
[Link](group_id, f"❌ Error fetching word list: {str(e)}")
/stop_filter
============
# Command: /stop_filter
if [Link] not in ["group", "supergroup"]:
raise ReturnCommand()

group_id = [Link]
u = message.from_user.id

# ✅ Admin check
try:
member = [Link](group_id, u)
if [Link] not in ["administrator", "creator"]:
[Link](group_id, f"❌ {[Link](u)}, only group admins can
remove filters.")
raise ReturnCommand()
except:
[Link](u, "⚠️ Failed to verify admin permissions.")
raise ReturnCommand()

parts = [Link](maxsplit=1)
if len(parts) < 2:
[Link](group_id, "❌ Usage: `/stop_filter trigger`",
parse_mode="markdown")
raise ReturnCommand()

trigger = parts[1].lower()
filters = [Link](f"filters_{group_id}") or {}

if trigger in filters:
del filters[trigger]
[Link](f"filters_{group_id}", filters)
[Link](group_id, f" Filter for *{trigger}* removed.",
parse_mode="markdown")
else:
[Link](group_id, f"⚠️ No filter found for *{trigger}*.",
parse_mode="markdown")

/stop_swr
=========
# Command: /stop_swr
if [Link] not in ["group", "supergroup"]:
raise ReturnCommand()

u = message.from_user.id
group_id = [Link]

# ✅ Admin check
try:
member = [Link](group_id, u)
if [Link] not in ["administrator", "creator"]:
[Link](group_id, "🚫 Only admins can stop a SWR session.")
raise ReturnCommand()
except:
[Link](group_id, "⚠️ Failed to verify admin status.")
raise ReturnCommand()

# ✅ Load session
session = [Link](f"swr_session_{group_id}")
if not session:
[Link](group_id, "⚠️ No active SWR session found.")
raise ReturnCommand()

# ✅ Delete session
[Link](f"swr_session_{group_id}")
[Link](group_id, "🛑 The current Secret Word Race session has been stopped.")

/swr
====
# Command: /swr <rounds>
if [Link] not in ["group", "supergroup"]:
raise ReturnCommand()

u = message.from_user.id
group_id = [Link]

# ✅ Admin check
try:
member = [Link](group_id, u)
if [Link] not in ["administrator", "creator"]:
[Link](group_id, "🚫 Only admins can start the SWR game.")
raise ReturnCommand()
except:
[Link](group_id, "⚠️ Failed to verify admin permissions.")
raise ReturnCommand()

# ✅ Prevent multiple sessions


if [Link](f"swr_session_{group_id}"):
[Link](group_id, "❌ A Secret Word Race session is already ongoing in
this group.")
raise ReturnCommand()

# ✅ Validate rounds param


params = [Link]().split() if params else []
if not params or not params[0].isdigit():
[Link](u, "❌ Usage: /swr <number_of_rounds>")
raise ReturnCommand()

rounds_total = int(params[0])
session = {
"group_id": group_id,
"rounds_total": rounds_total,
"rounds_done": 0,
"players": {},
"current_word": None
}
[Link](f"swr_session_{group_id}", session)

[Link](group_id, f"🎮 Secret Word Race will begin in 10 seconds! Get


ready...")
[Link](10, "/start_swr")

/toggle_activity
================
if [Link] != "private":
raise ReturnCommand()
split = [Link]()
if len(split) != 2:
[Link]([Link], "❌ Invalid parameters.")
raise ReturnCommand()

group_id_str, setting = split


group_id = int(group_id_str) # ✅ Ensure group_id is an int
u = [Link]
ctx = [Link]("settings_context")

# ✅ Verify session
if not ctx or int(ctx["group_id"]) != group_id:
[Link](u, "❌ Invalid or expired session.")
raise ReturnCommand()

group_title = [Link]("group_title", "Group")

# ✅ Verify admin
try:
member = [Link](group_id, u)
if [Link] not in ["administrator", "creator"]:
[Link](u, "🚫 You must be an admin in the group to manage these
settings.")
raise ReturnCommand()
except:
[Link](u, "❌ Could not verify your admin status.")
raise ReturnCommand()

# ✅ Load activity settings and ensure keys


settings = [Link](f"activity_settings_{group_id}") or {}
[Link]("trigger", "admins")
[Link]("count_media", True)
[Link]("count_admins", False)
[Link]("msg_cldwn", 0)

# ✅ Toggle logic
if setting == "trigger":
settings["trigger"] = "everyone" if settings["trigger"] == "admins" else
"admins"
elif setting == "count_media":
settings["count_media"] = not settings["count_media"]
elif setting == "count_admins":
settings["count_admins"] = not settings["count_admins"]
else:
[Link](u, "❌ Unknown setting.")
raise ReturnCommand()

# ✅ Save changes
[Link](f"activity_settings_{group_id}", settings)

# ✅ Rebuild buttons
trigger_label = f"Leaderboard Trigger ({'Admins Only' if
settings['trigger']=='admins' else 'Everyone'})"
count_label = f"Count Media ({'ON ✅' if settings['count_media'] else 'OFF'})"
count_admin_label = f"Count Admins ({'ON ✅' if settings['count_admins'] else
'OFF'})"
cooldown_label = f"Message Cooldown ({settings['msg_cldwn']} s)"

buttons = [
[InlineKeyboardButton(trigger_label, callback_data=f"/toggle_activity
{group_id} trigger")],
[InlineKeyboardButton(count_label, callback_data=f"/toggle_activity {group_id}
count_media")],
[InlineKeyboardButton(cooldown_label, callback_data=f"/activity_cooldown
{group_id}")],
[InlineKeyboardButton(count_admin_label, callback_data=f"/toggle_activity
{group_id} count_admins")],
[InlineKeyboardButton("♻️ Reset Activity", callback_data=f"/reset_activity
{group_id}")],
[InlineKeyboardButton("🔙 Back", callback_data="/settings_dm")]
]

text = (
f"<b>📊 Activity Settings for:</b> {group_title}\n\n"
f"• <b>Leaderboard Trigger</b>: Choose if only admins or everyone can use the
leaderboard.\n"
f"• <b>Count Media</b>: Decide if sending photos, GIFs, or stickers also give
activity points.\n"
f"• <b>Message Cooldown</b>: Limit how often activity points are given.\n"
f"• <b>Count Admins</b>: Decide if admin messages also count.\n"
f"• <b>Reset Activity</b>: Clears all saved activity points for this group."
)

# ✅ Try editing the message; fallback to sending a new one


try:
[Link](
chat_id=u,
message_id=message.message_id,
text=text,
parse_mode="html",
reply_markup=InlineKeyboardMarkup(buttons)
)
except:
[Link](
u,
text,
parse_mode="html",
reply_markup=InlineKeyboardMarkup(buttons)
)

/toggle_block
=============
if [Link] != "private":
raise ReturnCommand()

u = [Link]
split = [Link](" ")

if len(split) != 2:
[Link](u, "❌ Invalid usage.")
raise ReturnCommand()

group_id, block_key = split


ctx = [Link]("settings_context")

if not ctx or str(ctx["group_id"]) != group_id or [Link]("admin_id") != u:


[Link](u, "❌ No valid session found.")
raise ReturnCommand()
# ✅ Check if user is still admin in the group
member = [Link](group_id, u)
if [Link] not in ["administrator", "creator"]:
[Link](u, "🚫 You are no longer an admin in this group.")
raise ReturnCommand()

# ✅ All block options


all_blocks = {
"links": "Links",
"stickers": "Stickers",
"gifs": "GIFs",
"emojis": "Emojis",
"forwards": "Forwards",
"voice": "Voice Messages",
"commands": "Commands",
"photos": "Photos",
"videos": "Videos",
"documents": "Documents"
}

# ✅ Validate block type


if block_key not in all_blocks:
[Link](u, "❌ Invalid block type.")
raise ReturnCommand()

# ✅ Load current blocks


stored_blocks = [Link](f"group_blocks_{group_id}")
blocks = stored_blocks if stored_blocks is not None else []

# ✅ Toggle block
if block_key in blocks:
[Link](block_key)
else:
[Link](block_key)

# ✅ Save back
[Link](f"group_blocks_{group_id}", blocks)

# ✅ Rebuild buttons
buttons = [[InlineKeyboardButton(
f"{'✅' if key in blocks else '❌'} {label}",
callback_data=f"/toggle_block {group_id} {key}"
)] for key, label in all_blocks.items()]

[Link]([InlineKeyboardButton("🔙 Back", callback_data="/settings_dm")])

# ✅ Updated menu
text = f"<b>🚫 Block Settings for:</b> {[Link]('group_title', 'Group')}\n\nTap to
toggle block types."

try:
[Link](
chat_id=u,
message_id=message.message_id,
text=text,
parse_mode="html",
reply_markup=InlineKeyboardMarkup(buttons)
)
except:
pass

/toggle_goodbye
===============
# /toggle_goodbye
if [Link] != "private":
raise ReturnCommand()

u = [Link]

# ✅ Use params if provided, otherwise fallback to temporary saved group ID


if params and [Link]():
group_id = [Link]()
else:
group_id = [Link]("goodbye_edit_group")
if not group_id:
[Link](u, "❌ No active session. Please start again.")
raise ReturnCommand()
# ✅ Delete temporary data after using it
[Link]("goodbye_edit_group")

ctx = [Link]("settings_context")

# ✅ Verify session
if not ctx or str([Link]("group_id")) != group_id:
[Link](u, "❌ Invalid or expired session.")
raise ReturnCommand()

group_title = [Link]("group_title", "Group")

# ✅ Verify admin
try:
member = [Link](group_id, u)
if [Link] not in ["administrator", "creator"]:
[Link](u, "🚫 You must be an admin to manage these settings.")
raise ReturnCommand()
except:
[Link](u, "❌ Could not verify your admin status.")
raise ReturnCommand()

# ✅ Load current goodbye settings


goodbye_settings = [Link](f"goodbye_settings_{group_id}") or {"enabled":
False, "message": "Goodbye {name}, we will miss you!"}

# ✅ Toggle the enabled state


goodbye_settings["enabled"] = not goodbye_settings.get("enabled", False)

# ✅ Save changes
[Link](f"goodbye_settings_{group_id}", goodbye_settings)

# ✅ Rebuild buttons
toggle_label = "✅ On" if goodbye_settings["enabled"] else "❌ Off"
buttons = [
[InlineKeyboardButton(f"Goodbye Messages: {toggle_label}",
callback_data=f"/toggle_goodbye {group_id}")],
[InlineKeyboardButton("✏️ Customize Goodbye Message",
callback_data=f"/edit_goodbye {group_id}")],
[InlineKeyboardButton("📄 View Current Goodbye Message",
callback_data=f"/view_goodbye {group_id}")],
[InlineKeyboardButton("🔙 Back", callback_data=f"/welcome_goodbye {group_id}")]
]

text = (
f"<b>💔 Goodbye Message Settings for:</b> {group_title}\n\n"
f"• Toggle goodbye messages on or off.\n"
f"• Customize the goodbye message text.\n"
f"• View the current goodbye message."
)

try:
[Link](
chat_id=u,
message_id=message.message_id,
text=text,
parse_mode="html",
reply_markup=InlineKeyboardMarkup(buttons)
)
except:
[Link](
u,
text,
parse_mode="html",
reply_markup=InlineKeyboardMarkup(buttons)
)

/toggle_mode
============
if [Link] != "private":
raise ReturnCommand()

u = [Link]
split = [Link](" ")

if len(split) != 2:
[Link](u, "❌ Invalid usage.")
raise ReturnCommand()

group_id, mode_key = split


ctx = [Link]("settings_context")

if not ctx or str(ctx["group_id"]) != group_id or [Link]("admin_id") != u:


[Link](u, "❌ No valid session found.")
raise ReturnCommand()

# ✅ Verify user is still admin in group


try:
member = [Link](group_id, u)
if [Link] not in ["administrator", "creator"]:
[Link](u, "🚫 You are no longer an admin in this group.")
raise ReturnCommand()
except:
[Link](u, "❌ Could not verify your admin status.")
raise ReturnCommand()

# ✅ Available modes (no Ads/Links)


all_modes = {
"toxicity": "Toxicity",
"profanity": "Profanity",
"nsfw": "NSFW",
"strict_ai": "Passive Aggression",
"english_only": "English Only",
"pm_block": "DM/PM Ask",
"tag_block": "Admin Pings"
}

if mode_key not in all_modes:


[Link](u, "❌ Invalid mode.")
raise ReturnCommand()

stored_modes = [Link](f"group_modes_{group_id}")
modes = stored_modes if stored_modes is not None else []

if mode_key in modes:
[Link](mode_key)
else:
[Link](mode_key)

[Link](f"group_modes_{group_id}", modes)

buttons = [[InlineKeyboardButton(
f"{'✅' if key in modes else '❌'} {label}",
callback_data=f"/toggle_mode {group_id} {key}"
)] for key, label in all_modes.items()]

[Link]([InlineKeyboardButton("🔙 Back", callback_data="/settings_dm")])

text = f"<b> Scan Mode for:</b> {[Link]('group_title', 'Group')}\n\nTap to toggle


scan types."

try:
[Link](chat_id=u, message_id=message.message_id, text=text,
parse_mode="html", reply_markup=InlineKeyboardMarkup(buttons))
except:
pass

/toggle_welcome
===============
if [Link] != "private":
raise ReturnCommand()

group_id = [Link]()
u = [Link]
ctx = [Link]("settings_context")

# ✅ Verify session
if not ctx or str([Link]("group_id")) != group_id:
[Link](u, "❌ Invalid or expired session.")
raise ReturnCommand()

group_title = [Link]("group_title", "Group")

# ✅ Verify admin
try:
member = [Link](group_id, u)
if [Link] not in ["administrator", "creator"]:
[Link](u, "🚫 You must be an admin to manage these settings.")
raise ReturnCommand()
except:
[Link](u, "❌ Could not verify your admin status.")
raise ReturnCommand()

# ✅ Load welcome settings


welcome_settings = [Link](f"welcome_settings_{group_id}") or {
"enabled": False,
"message": "Welcome {name} to {group}!"
}

# ✅ Toggle the enabled status


welcome_settings["enabled"] = not welcome_settings["enabled"]

# ✅ Save changes
[Link](f"welcome_settings_{group_id}", welcome_settings)

# ✅ Update button labels


toggle_label = "✅ On" if welcome_settings["enabled"] else "❌ Off"

buttons = [
[InlineKeyboardButton(f"Welcome Messages: {toggle_label}",
callback_data=f"/toggle_welcome {group_id}")],
[InlineKeyboardButton("✏️ Customize Welcome Message",
callback_data=f"/edit_welcome {group_id}")],
[InlineKeyboardButton("📄 View Current Welcome Message",
callback_data=f"/view_welcome {group_id}")],
[InlineKeyboardButton("🔙 Back", callback_data=f"/welcome_goodbye {group_id}")]
]

text = (
f"<b>👋 Welcome Message Settings for:</b> {group_title}\n\n"
f"• Toggle welcome messages on or off.\n"
f"• Customize the welcome message text.\n"
f"• View the current welcome message."
)

# ✅ Edit message to reflect new status


try:
[Link](
chat_id=u,
message_id=message.message_id,
text=text,
parse_mode="html",
reply_markup=InlineKeyboardMarkup(buttons)
)
except:
[Link](
u,
text,
parse_mode="html",
reply_markup=InlineKeyboardMarkup(buttons)
)

/view_goodbye
=============
# /view_goodbye
if [Link] != "private":
raise ReturnCommand()
u = [Link]

# ✅ Get group_id from params


if not params:
[Link](u, "❌ No group specified.")
raise ReturnCommand()
group_id = [Link]()

# ✅ Verify session context


ctx = [Link]("settings_context")
if not ctx or str([Link]("group_id")) != group_id:
[Link](u, "❌ Invalid or expired session.")
raise ReturnCommand()

group_title = [Link]("group_title", "Group")

# ✅ Verify admin
try:
member = [Link](group_id, u)
if [Link] not in ["administrator", "creator"]:
[Link](u, "🚫 You must be an admin to view these settings.")
raise ReturnCommand()
except:
[Link](u, "❌ Could not verify your admin status.")
raise ReturnCommand()

# ✅ Load goodbye message


goodbye_data = [Link](f"goodbye_message_{group_id}") or {}
text = goodbye_data.get("text", "ℹ️ No goodbye message is set for this group yet.")
photo = goodbye_data.get("photo")
video = goodbye_data.get("video")

# ✅ Back button
reply_markup = {
"inline_keyboard": [
[{"text": "🔙 Back", "callback_data": f"/goodbye_message {group_id}"}]
]
}

# ✅ Safe preview (inline, no def)


try:
if photo:
[Link](
chat_id=u,
message_id=message.message_id,
caption=text,
parse_mode="HTML",
reply_markup=reply_markup
)
elif video:
[Link](
chat_id=u,
message_id=message.message_id,
caption=text,
parse_mode="HTML",
reply_markup=reply_markup
)
else:
[Link](
chat_id=u,
message_id=message.message_id,
text=text,
parse_mode="HTML",
reply_markup=reply_markup
)
except:
# fallback if editing fails
try:
if photo:
[Link](u, photo, caption=text, parse_mode="HTML",
reply_markup=reply_markup)
elif video:
[Link](u, video, caption=text, parse_mode="HTML",
reply_markup=reply_markup)
else:
[Link](
chat_id=u,
message_id=message.message_id,
text=f"ℹ️ Unable to load media. Showing text only:\n\n{text}",
parse_mode="HTML",
reply_markup=reply_markup
)
except:
[Link](
f"ℹ️ Unable to load media. Showing text only:\n\n{text}",
parse_mode="HTML"
)

/view_welcome
=============
# Command: /view_welcome
if [Link] != "private":
raise ReturnCommand()

u = [Link]

# ✅ Get group_id from params


if not params:
[Link](u, "❌ No group specified.")
raise ReturnCommand()
group_id = [Link]()

# ✅ Verify session context


ctx = [Link]("settings_context")
if not ctx or str([Link]("group_id")) != group_id:
[Link](u, "❌ Invalid or expired session.")
raise ReturnCommand()

group_title = [Link]("group_title", "Group")

# ✅ Verify admin
try:
member = [Link](group_id, u)
if [Link] not in ["administrator", "creator"]:
[Link](u, "🚫 You must be an admin to view these settings.")
raise ReturnCommand()
except:
[Link](u, "❌ Could not verify your admin status.")
raise ReturnCommand()

# ✅ Load welcome message


welcome_data = [Link](f"welcome_message_{group_id}") or {}
text = welcome_data.get("text", "ℹ️ No welcome message is set for this group yet.")
photo = welcome_data.get("photo")
video = welcome_data.get("video")

# ✅ Load inline buttons if any


buttons_data = [Link](f"welcome_buttons_{group_id}") or []

# Always append back button at the end


buttons_data.append([{"text": "🔙 Back", "callback_data": f"/welcome_goodbye
{group_id}"}])

# Convert buttons to InlineKeyboardButton objects


inline_keyboard = []
for row in buttons_data:
inline_row = []
for button in row:
if [Link]("url"):
inline_row.append({"text": button["text"], "url": button["url"]})
else:
inline_row.append({"text": button["text"], "callback_data":
button["callback_data"]})
inline_keyboard.append(inline_row)

reply_markup = {"inline_keyboard": inline_keyboard}

# ✅ Safe preview (prioritize editing with buttons, no def)


try:
# First try: edit the message with text + buttons.
[Link](
chat_id=u,
message_id=message.message_id,
text=f"ℹ️ Unable to load media. Showing text only:\n\n{text}",
parse_mode="HTML",
reply_markup=reply_markup
)
except:
# If editing fails, try sending a new message
try:
if photo:
[Link](u, photo, caption=text, parse_mode="HTML",
reply_markup=reply_markup)
elif video:
[Link](u, video, caption=text, parse_mode="HTML",
reply_markup=reply_markup)
else:
[Link](
u,
f"ℹ️ Unable to load media. Showing text only:\n\n{text}",
parse_mode="HTML",
reply_markup=reply_markup
)
except:
# If everything fails, just send the plain text
[Link](f"ℹ️ Unable to load media. Showing text only:\n\n{text}")
/welcome_goodbye
================
if [Link] != "private":
raise ReturnCommand()

u = [Link]

# ✅ Use params if provided, otherwise fallback to temporary saved group ID


if params and [Link]():
group_id = [Link]()
else:
group_id = [Link]("welcome_edit_group")
if not group_id:
[Link](u, "❌ No active session. Please start again.")
raise ReturnCommand()
# ✅ Delete temporary data after using it
[Link]("welcome_edit_group")

ctx = [Link]("settings_context")

# ✅ Verify session
if not ctx or str([Link]("group_id")) != group_id:
[Link](u, "❌ Invalid or expired session.")
raise ReturnCommand()

group_title = [Link]("group_title", "Group")

# ✅ Verify user is still admin


try:
member = [Link](group_id, u)
if [Link] not in ["administrator", "creator"]:
[Link](u, "🚫 You must be an admin to manage these settings.")
raise ReturnCommand()
except:
[Link](u, "❌ Could not verify your admin status.")
raise ReturnCommand()

# ✅ Build menu buttons


buttons = [
[InlineKeyboardButton("👋 Welcome Message", callback_data=f"/welcome_message
{group_id}")],
[InlineKeyboardButton("💔 Goodbye Message", callback_data=f"/goodbye_message
{group_id}")],
[InlineKeyboardButton("🔙 Back", callback_data=f"/settings_dm")]
]

text = (
f"<b>👋 Welcome & Goodbye Settings for:</b> {group_title}\n\n"
f"Choose which message you want to configure."
)

try:
[Link](
chat_id=u,
message_id=message.message_id,
text=text,
parse_mode="html",
reply_markup=InlineKeyboardMarkup(buttons)
)
except:
[Link](
u,
text,
parse_mode="html",
reply_markup=InlineKeyboardMarkup(buttons)
)

/welcome_message
================
if [Link] != "private":
raise ReturnCommand()

u = [Link]

# ✅ Use params if provided, otherwise fallback to temporary saved group ID


if params and [Link]():
group_id = [Link]()
else:
group_id = [Link]("welcome_edit_group")
if not group_id:
[Link](u, "❌ No active session. Please start again.")
raise ReturnCommand()
# ✅ Delete temporary data after using it
[Link]("welcome_edit_group")

ctx = [Link]("settings_context")

# ✅ Verify session
if not ctx or str([Link]("group_id")) != group_id:
[Link](u, "❌ Invalid or expired session.")
raise ReturnCommand()

group_title = [Link]("group_title", "Group")

# ✅ Verify admin
try:
member = [Link](group_id, u)
if [Link] not in ["administrator", "creator"]:
[Link](u, "🚫 You must be an admin to manage these settings.")
raise ReturnCommand()
except:
[Link](u, "❌ Could not verify your admin status.")
raise ReturnCommand()

# ✅ Load welcome settings


welcome_settings = [Link](f"welcome_settings_{group_id}") or {
"enabled": False,
"message": "Welcome {name} to {group}!"
}

# ✅ Build button labels


toggle_label = "✅ On" if welcome_settings["enabled"] else "❌ Off"

buttons = [
[InlineKeyboardButton(f"Welcome Messages: {toggle_label}",
callback_data=f"/toggle_welcome {group_id}")],
[InlineKeyboardButton("✏️ Customize Welcome Message",
callback_data=f"/edit_welcome {group_id}")],
[InlineKeyboardButton("📄 View Current Welcome Message",
callback_data=f"/view_welcome {group_id}")],
[InlineKeyboardButton("🔙 Back", callback_data=f"/welcome_goodbye {group_id}")]
]

text = (
f"<b>👋 Welcome Message Settings for:</b> {group_title}\n\n"
f"• Toggle welcome messages on or off.\n"
f"• Customize the welcome message text.\n"
f"• View the current welcome message."
)

try:
[Link](
chat_id=u,
message_id=message.message_id,
text=text,
parse_mode="html",
reply_markup=InlineKeyboardMarkup(buttons)
)
except:
[Link](
u,
text,
parse_mode="html",
reply_markup=InlineKeyboardMarkup(buttons)
)

/word_blocks
============
# /word_blocks
if [Link] != "private":
raise ReturnCommand()

u = message.from_user.id
ctx = [Link]("settings_context")

if not ctx or [Link]("admin_id") != u:


[Link](u, "❌ No active session. Please use /settings in your group
first.")
raise ReturnCommand()

group_title = ctx["group_title"]
group_id = ctx["group_id"]

text = f"📝 *Word Block Settings for:* {group_title}\n\nChoose an option below:"

btns = {
"inline_keyboard": [
[{"text": "📃 List of Blocked Words", "callback_data": f"/list_blocked_words
{group_id}"}],
[{"text": "➕ Add Blocked Word", "callback_data": f"/add_blocked_word
{group_id}"}],
[{"text": "➖ Remove Blocked Word", "callback_data": f"/remove_blocked_word
{group_id}"}],
[{"text": "🔙 Back", "callback_data": f"/settings_dm"}]
]
}
try:
[Link](
chat_id=u,
message_id=message.message_id,
text=text,
parse_mode="markdown",
reply_markup=btns
)
except:
[Link](
u,
text,
parse_mode="markdown",
reply_markup=btns
)

@
=
# /handler_bot_added
try:
my_bot_id = 7995887863 # <-- your bot ID here

if [Link] in ["group", "supergroup"]:


group_id = [Link]
group_title = [Link] or "Unnamed"

# ========== Bot Added ==========


if (
update_type == "my_chat_member"
and message.new_chat_member.[Link] == my_bot_id
and message.new_chat_member.status in ["member", "administrator"]
):
adder_id = message.from_user.id if message.from_user else None

try:
try:
count = [Link](chat_id=group_id)
except:
count = 0

if count >= 100 and adder_id:


rewarded_groups = [Link]("affiliate_rewarded_groups") or
[]
if group_id not in rewarded_groups:
referrer_id = [Link]("affiliate_referrer",
user=adder_id)
if referrer_id:
amount = 0.05
claim_delay = [Link]("affiliate_claim_delay") or
(24 * 3600)
unlock_time = [Link]() + claim_delay
pending = [Link]("affiliate_pending",
user=referrer_id) or []
[Link]({
"amount": amount,
"unlock_at": unlock_time,
"group_id": group_id,
"group_name": group_title
})
[Link]("affiliate_pending", pending,
user=referrer_id)
[Link](
chat_id=referrer_id,
text=(
f"💰 One of your referrals "
f"(@{message.from_user.username or
message.from_user.first_name}) "
f"added me to <b>{group_title}</b> (100+
members)!\n\n"
f"🎁 <b>${amount}</b> added to your pending
balance.\n"
f"⏳ See more with /affiliate"
),
parse_mode="html"
)
rewarded_groups.append(group_id)
[Link]("affiliate_rewarded_groups",
rewarded_groups)
except:
pass

join_text = (
"🤖 <b>Elite Group Bot has arrived!</b>\n\n"
"✨ I help keep your community clean & engaging:\n"
"🛡 Auto-delete spam, toxicity & profanity\n"
"📩 Track invites & run contests with ease\n"
"📊 Analytics & referral rewards system\n\n"
f"⚙️ Type <b>/settings</b> to set me up in <b>{group_title}</b>!\n\
n"
"🚀 Let's make this group safer, smarter, and more fun together!"
)
[Link](chat_id=group_id, text=join_text, parse_mode="html")

raise ReturnCommand()

# ========== Store neutral invite link ==========


groups = [Link]("group_list") or []
found = next((g for g in groups if g["id"] == group_id), None)
if not found:
try:
invite = [Link](chat_id=group_id, name="Neutral")
real_link = invite.invite_link
[Link]({"id": group_id, "title": group_title, "link":
real_link})
[Link]("group_list", groups)
except:
pass
except Exception as e:
[Link](
chat_id=5029593137,
text=f"❌ BotAdded handler error: <code>{str(e)}</code>",
parse_mode="html"
)

serve
=====
# Command: /check_swr
if [Link] not in ["group", "supergroup"]:
raise ReturnCommand()

group_id = [Link]
user_id = message.from_user.id
text = ([Link] or "").strip().lower() # this is correct; no extra definition
needed

# ✅ Load session
session = [Link](f"swr_session_{group_id}")
if not session or not [Link]("current_word"):
[Link](group_id, "⚠️ No active round found.")
raise ReturnCommand()

[Link](group_id, f"⚠️ [DEBUG] Checking guess for word:


{session['current_word']} by user {user_id}")

# ✅ Check answer
correct_word = session["current_word"].lower()
if text == correct_word:
# ✅ Update player score
players = [Link]("players", {})
players[str(user_id)] = [Link](str(user_id), 0) + 1
session["players"] = players
[Link](f"swr_session_{group_id}", session)

[Link](group_id, f"✅ {[Link]('name', user=user_id)} got it


correct! (+1 pt)")
[Link](group_id, f"⚠️ [DEBUG] Updated players: {players}")

# ✅ Schedule next round after 10 seconds


[Link](10, "/start_swr")
[Link](group_id, "⚠️ [DEBUG] Next round scheduled in 10 seconds.")

else:
[Link](group_id, f"❌ {[Link]('name', user=user_id)} guessed
incorrectly. Try again!")
[Link](group_id, "⚠️ [DEBUG] Incorrect guess received, waiting for next
guess.")

# ✅ Re-register for next guess immediately


[Link]("/check_swr") # Must be last, immediately after
processing

You might also like