From 26a9aecfcb3528ef5486ffa630d169d4e12c3a19 Mon Sep 17 00:00:00 2001 From: Shamil Habeeb Date: Wed, 2 Dec 2026 20:51:39 +0530 Subject: [PATCH 01/10] Fix Peer id invalid on fresh start, apply CUSTOM_CAPTION to all media --- 1-bot.py | 91 +++++++++++++++++++++++++++++ 2-helper_func.py | 147 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 238 insertions(+) create mode 100644 1-bot.py create mode 100644 2-helper_func.py diff --git a/1-bot.py b/1-bot.py new file mode 100644 index 000000000..2f38d1ff6 --- /dev/null +++ b/1-bot.py @@ -0,0 +1,91 @@ +#(©)Codexbotz + +from aiohttp import web +from plugins import web_server + +import pyromod.listen +from pyrogram import Client +from pyrogram import raw, utils +from pyrogram.enums import ParseMode +import sys +from datetime import datetime + +from config import API_HASH, APP_ID, LOGGER, TG_BOT_TOKEN, TG_BOT_WORKERS, FORCE_SUB_CHANNEL, CHANNEL_ID, PORT + + +ascii_art = """ +░█████╗░░█████╗░██████╗░███████╗██╗░░██╗██████╗░░█████╗░████████╗███████╗ +██╔══██╗██╔══██╗██╔══██╗██╔════╝╚██╗██╔╝██╔══██╗██╔══██╗╚══██╔══╝╚════██║ +██║░░╚═╝██║░░██║██║░░██║█████╗░░░╚███╔╝░██████╦╝██║░░██║░░░██║░░░░░███╔═╝ +██║░░██╗██║░░██║██║░░██║██╔══╝░░░██╔██╗░██╔══██╗██║░░██║░░░██║░░░██╔══╝░░ +╚█████╔╝╚█████╔╝██████╔╝███████╗██╔╝╚██╗██████╦╝╚█████╔╝░░░██║░░░███████╗ +░╚════╝░░╚════╝░╚═════╝░╚══════╝╚═╝░░╚═╝╚═════╝░░╚════╝░░░░╚═╝░░░╚══════╝ +""" + +class Bot(Client): + def __init__(self): + super().__init__( + name="Bot", + api_hash=API_HASH, + api_id=APP_ID, + plugins={ + "root": "plugins" + }, + workers=TG_BOT_WORKERS, + bot_token=TG_BOT_TOKEN + ) + self.LOGGER = LOGGER + + async def start(self): + await super().start() + usr_bot_me = await self.get_me() + self.uptime = datetime.now() + + if FORCE_SUB_CHANNEL: + try: + link = (await self.get_chat(FORCE_SUB_CHANNEL)).invite_link + if not link: + await self.export_chat_invite_link(FORCE_SUB_CHANNEL) + link = (await self.get_chat(FORCE_SUB_CHANNEL)).invite_link + self.invitelink = link + except Exception as a: + self.LOGGER(__name__).warning(a) + self.LOGGER(__name__).warning("Bot can't Export Invite link from Force Sub Channel!") + self.LOGGER(__name__).warning(f"Please Double check the FORCE_SUB_CHANNEL value and Make sure Bot is Admin in channel with Invite Users via Link Permission, Current Force Sub Channel Value: {FORCE_SUB_CHANNEL}") + self.LOGGER(__name__).info("\nBot Stopped. Join https://t.me/CodeXBotzSupport for support") + sys.exit() + try: + try: + db_channel = await self.get_chat(CHANNEL_ID) + except ValueError: + # Fresh session (no cached peers, e.g. Railway/Heroku/Docker): the bot has + # never seen the channel, so ask Telegram for it by id and retry once. + await self.invoke( + raw.functions.channels.GetChannels( + id=[raw.types.InputChannel(channel_id=utils.get_channel_id(CHANNEL_ID), access_hash=0)] + ) + ) + db_channel = await self.get_chat(CHANNEL_ID) + self.db_channel = db_channel + test = await self.send_message(chat_id = db_channel.id, text = "Test Message") + await test.delete() + except Exception as e: + self.LOGGER(__name__).warning(e) + self.LOGGER(__name__).warning(f"Make Sure bot is Admin in DB Channel, and Double check the CHANNEL_ID Value, Current Value {CHANNEL_ID}") + self.LOGGER(__name__).info("\nBot Stopped. Join https://t.me/CodeXBotzSupport for support") + sys.exit() + + self.set_parse_mode(ParseMode.HTML) + self.LOGGER(__name__).info(f"Bot Running..!\n\nCreated by \nhttps://t.me/CodeXBotz") + print(ascii_art) + print("""Welcome to CodeXBotz File Sharing Bot""") + self.username = usr_bot_me.username + #web-response + app = web.AppRunner(await web_server()) + await app.setup() + bind_address = "0.0.0.0" + await web.TCPSite(app, bind_address, PORT).start() + + async def stop(self, *args): + await super().stop() + self.LOGGER(__name__).info("Bot stopped.") diff --git a/2-helper_func.py b/2-helper_func.py new file mode 100644 index 000000000..173ce4093 --- /dev/null +++ b/2-helper_func.py @@ -0,0 +1,147 @@ +#(©)Codexbotz + +import base64 +import re +import asyncio +import logging +from pyrogram import filters +from pyrogram.enums import ChatMemberStatus +from config import FORCE_SUB_CHANNEL, ADMINS, AUTO_DELETE_TIME, AUTO_DEL_SUCCESS_MSG +from pyrogram.errors.exceptions.bad_request_400 import UserNotParticipant +from pyrogram.errors import FloodWait + +async def is_subscribed(filter, client, update): + if not FORCE_SUB_CHANNEL: + return True + user_id = update.from_user.id + if user_id in ADMINS: + return True + try: + member = await client.get_chat_member(chat_id = FORCE_SUB_CHANNEL, user_id = user_id) + except UserNotParticipant: + return False + + if not member.status in [ChatMemberStatus.OWNER, ChatMemberStatus.ADMINISTRATOR, ChatMemberStatus.MEMBER]: + return False + else: + return True + +async def encode(string): + string_bytes = string.encode("ascii") + base64_bytes = base64.urlsafe_b64encode(string_bytes) + base64_string = (base64_bytes.decode("ascii")).strip("=") + return base64_string + +async def decode(base64_string): + base64_string = base64_string.strip("=") # links generated before this commit will be having = sign, hence striping them to handle padding errors. + base64_bytes = (base64_string + "=" * (-len(base64_string) % 4)).encode("ascii") + string_bytes = base64.urlsafe_b64decode(base64_bytes) + string = string_bytes.decode("ascii") + return string + +async def get_messages(client, message_ids): + messages = [] + total_messages = 0 + while total_messages != len(message_ids): + temb_ids = message_ids[total_messages:total_messages+200] + try: + msgs = await client.get_messages( + chat_id=client.db_channel.id, + message_ids=temb_ids + ) + except FloodWait as e: + await asyncio.sleep(e.x) + msgs = await client.get_messages( + chat_id=client.db_channel.id, + message_ids=temb_ids + ) + except: + pass + total_messages += len(temb_ids) + messages.extend(msgs) + return messages + +async def get_message_id(client, message): + if message.forward_from_chat: + if message.forward_from_chat.id == client.db_channel.id: + return message.forward_from_message_id + else: + return 0 + elif message.forward_sender_name: + return 0 + elif message.text: + pattern = "https://t.me/(?:c/)?(.*)/(\d+)" + matches = re.match(pattern,message.text) + if not matches: + return 0 + channel_id = matches.group(1) + msg_id = int(matches.group(2)) + if channel_id.isdigit(): + if f"-100{channel_id}" == str(client.db_channel.id): + return msg_id + else: + if channel_id == client.db_channel.username: + return msg_id + else: + return 0 + +class _SafeCaptionDict(dict): + # Unknown placeholders (e.g. a stray "{name}") are left as typed instead of raising KeyError. + def __missing__(self, key): + return "{" + key + "}" + +def build_caption(msg, custom_caption): + """Return the caption to send for a stored message. + + CUSTOM_CAPTION is applied to every media type that has a file name + (document, video, audio, animation), not only documents. A bad template + falls back to the original caption instead of dropping the file. + """ + previous = "" if not msg.caption else msg.caption.html + if not custom_caption: + return previous + media = msg.document or msg.video or msg.audio or msg.animation + if not media: + return previous + try: + return custom_caption.format_map(_SafeCaptionDict( + previouscaption=previous, + filename=getattr(media, "file_name", None) or "", + )) + except (ValueError, IndexError, AttributeError): + return previous + +def get_readable_time(seconds: int) -> str: + count = 0 + up_time = "" + time_list = [] + time_suffix_list = ["s", "m", "h", "days"] + while count < 4: + count += 1 + remainder, result = divmod(seconds, 60) if count < 3 else divmod(seconds, 24) + if seconds == 0 and remainder == 0: + break + time_list.append(int(result)) + seconds = int(remainder) + hmm = len(time_list) + for x in range(hmm): + time_list[x] = str(time_list[x]) + time_suffix_list[x] + if len(time_list) == 4: + up_time += f"{time_list.pop()}, " + time_list.reverse() + up_time += ":".join(time_list) + return up_time + +async def delete_file(messages, client, process): + await asyncio.sleep(AUTO_DELETE_TIME) + for msg in messages: + try: + await client.delete_messages(chat_id=msg.chat.id, message_ids=[msg.id]) + except Exception as e: + await asyncio.sleep(e.x) + print(f"The attempt to delete the media {msg.id} was unsuccessful: {e}") + + await process.edit_text(AUTO_DEL_SUCCESS_MSG) + + +subscribed = filters.create(is_subscribed) From ad5affe3ea07207861b446d2449d9d25e6ac27c0 Mon Sep 17 00:00:00 2001 From: Shamil Habeeb Date: Wed, 2 Dec 2026 20:51:59 +0530 Subject: [PATCH 02/10] Use build_caption in start handler --- plugins/3-start.py | 257 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 257 insertions(+) create mode 100644 plugins/3-start.py diff --git a/plugins/3-start.py b/plugins/3-start.py new file mode 100644 index 000000000..89eab8c41 --- /dev/null +++ b/plugins/3-start.py @@ -0,0 +1,257 @@ +#(©)CodeXBotz + +import os +import asyncio +from pyrogram import Client, filters +from pyrogram.enums import ParseMode +from pyrogram.types import Message, InlineKeyboardMarkup, InlineKeyboardButton +from pyrogram.errors import FloodWait, UserIsBlocked, InputUserDeactivated + +from bot import Bot +from config import ADMINS, FORCE_MSG, START_MSG, CUSTOM_CAPTION, DISABLE_CHANNEL_BUTTON, PROTECT_CONTENT, START_PIC, AUTO_DELETE_TIME, AUTO_DELETE_MSG, JOIN_REQUEST_ENABLE,FORCE_SUB_CHANNEL +from helper_func import subscribed,decode, get_messages, delete_file, build_caption +from database.database import add_user, del_user, full_userbase, present_user + + +@Bot.on_message(filters.command('start') & filters.private & subscribed) +async def start_command(client: Client, message: Message): + id = message.from_user.id + if not await present_user(id): + try: + await add_user(id) + except: + pass + text = message.text + if len(text)>7: + try: + base64_string = text.split(" ", 1)[1] + except: + return + string = await decode(base64_string) + argument = string.split("-") + if len(argument) == 3: + try: + start = int(int(argument[1]) / abs(client.db_channel.id)) + end = int(int(argument[2]) / abs(client.db_channel.id)) + except: + return + if start <= end: + ids = range(start,end+1) + else: + ids = [] + i = start + while True: + ids.append(i) + i -= 1 + if i < end: + break + elif len(argument) == 2: + try: + ids = [int(int(argument[1]) / abs(client.db_channel.id))] + except: + return + temp_msg = await message.reply("Please wait...") + try: + messages = await get_messages(client, ids) + except: + await message.reply_text("Something went wrong..!") + return + await temp_msg.delete() + + track_msgs = [] + + for msg in messages: + + caption = build_caption(msg, CUSTOM_CAPTION) + + if DISABLE_CHANNEL_BUTTON: + reply_markup = msg.reply_markup + else: + reply_markup = None + + if AUTO_DELETE_TIME and AUTO_DELETE_TIME > 0: + + try: + copied_msg_for_deletion = await msg.copy(chat_id=message.from_user.id, caption=caption, parse_mode=ParseMode.HTML, reply_markup=reply_markup, protect_content=PROTECT_CONTENT) + if copied_msg_for_deletion: + track_msgs.append(copied_msg_for_deletion) + else: + print("Failed to copy message, skipping.") + + except FloodWait as e: + await asyncio.sleep(e.value) + copied_msg_for_deletion = await msg.copy(chat_id=message.from_user.id, caption=caption, parse_mode=ParseMode.HTML, reply_markup=reply_markup, protect_content=PROTECT_CONTENT) + if copied_msg_for_deletion: + track_msgs.append(copied_msg_for_deletion) + else: + print("Failed to copy message after retry, skipping.") + + except Exception as e: + print(f"Error copying message: {e}") + pass + + else: + try: + await msg.copy(chat_id=message.from_user.id, caption=caption, parse_mode=ParseMode.HTML, reply_markup=reply_markup, protect_content=PROTECT_CONTENT) + await asyncio.sleep(0.5) + except FloodWait as e: + await asyncio.sleep(e.value) + await msg.copy(chat_id=message.from_user.id, caption=caption, parse_mode=ParseMode.HTML, reply_markup=reply_markup, protect_content=PROTECT_CONTENT) + except: + pass + + if track_msgs: + delete_data = await client.send_message( + chat_id=message.from_user.id, + text=AUTO_DELETE_MSG.format(time=AUTO_DELETE_TIME) + ) + # Schedule the file deletion task after all messages have been copied + asyncio.create_task(delete_file(track_msgs, client, delete_data)) + else: + print("No messages to track for deletion.") + + return + else: + reply_markup = InlineKeyboardMarkup( + [ + [ + InlineKeyboardButton("😊 About Me", callback_data = "about"), + InlineKeyboardButton("🔒 Close", callback_data = "close") + ] + ] + ) + if START_PIC: # Check if START_PIC has a value + await message.reply_photo( + photo=START_PIC, + caption=START_MSG.format( + first=message.from_user.first_name, + last=message.from_user.last_name, + username=None if not message.from_user.username else '@' + message.from_user.username, + mention=message.from_user.mention, + id=message.from_user.id + ), + reply_markup=reply_markup, + quote=True + ) + else: # If START_PIC is empty, send only the text + await message.reply_text( + text=START_MSG.format( + first=message.from_user.first_name, + last=message.from_user.last_name, + username=None if not message.from_user.username else '@' + message.from_user.username, + mention=message.from_user.mention, + id=message.from_user.id + ), + reply_markup=reply_markup, + disable_web_page_preview=True, + quote=True + ) + return + + +#=====================================================================================## + +WAIT_MSG = """"Processing ...""" + +REPLY_ERROR = """Use this command as a replay to any telegram message with out any spaces.""" + +#=====================================================================================## + + +@Bot.on_message(filters.command('start') & filters.private) +async def not_joined(client: Client, message: Message): + + if bool(JOIN_REQUEST_ENABLE): + invite = await client.create_chat_invite_link( + chat_id=FORCE_SUB_CHANNEL, + creates_join_request=True + ) + ButtonUrl = invite.invite_link + else: + ButtonUrl = client.invitelink + + buttons = [ + [ + InlineKeyboardButton( + "Join Channel", + url = ButtonUrl) + ] + ] + + try: + buttons.append( + [ + InlineKeyboardButton( + text = 'Try Again', + url = f"https://t.me/{client.username}?start={message.command[1]}" + ) + ] + ) + except IndexError: + pass + + await message.reply( + text = FORCE_MSG.format( + first = message.from_user.first_name, + last = message.from_user.last_name, + username = None if not message.from_user.username else '@' + message.from_user.username, + mention = message.from_user.mention, + id = message.from_user.id + ), + reply_markup = InlineKeyboardMarkup(buttons), + quote = True, + disable_web_page_preview = True + ) + +@Bot.on_message(filters.command('users') & filters.private & filters.user(ADMINS)) +async def get_users(client: Bot, message: Message): + msg = await client.send_message(chat_id=message.chat.id, text=WAIT_MSG) + users = await full_userbase() + await msg.edit(f"{len(users)} users are using this bot") + +@Bot.on_message(filters.private & filters.command('broadcast') & filters.user(ADMINS)) +async def send_text(client: Bot, message: Message): + if message.reply_to_message: + query = await full_userbase() + broadcast_msg = message.reply_to_message + total = 0 + successful = 0 + blocked = 0 + deleted = 0 + unsuccessful = 0 + + pls_wait = await message.reply("Broadcasting Message.. This will Take Some Time") + for chat_id in query: + try: + await broadcast_msg.copy(chat_id) + successful += 1 + except FloodWait as e: + await asyncio.sleep(e.x) + await broadcast_msg.copy(chat_id) + successful += 1 + except UserIsBlocked: + await del_user(chat_id) + blocked += 1 + except InputUserDeactivated: + await del_user(chat_id) + deleted += 1 + except: + unsuccessful += 1 + pass + total += 1 + + status = f"""Broadcast Completed + +Total Users: {total} +Successful: {successful} +Blocked Users: {blocked} +Deleted Accounts: {deleted} +Unsuccessful: {unsuccessful}""" + + return await pls_wait.edit(status) + + else: + msg = await message.reply(REPLY_ERROR) + await asyncio.sleep(8) + await msg.delete() + From dde2fdb3879373936a4c777eced1887fc8b5f34e Mon Sep 17 00:00:00 2001 From: Shamil Habeeb Date: Wed, 2 Dec 2026 20:52:16 +0530 Subject: [PATCH 03/10] Add tests for build_caption --- tests/4-test_build_caption.py | 38 +++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 tests/4-test_build_caption.py diff --git a/tests/4-test_build_caption.py b/tests/4-test_build_caption.py new file mode 100644 index 000000000..4ef78f1f8 --- /dev/null +++ b/tests/4-test_build_caption.py @@ -0,0 +1,38 @@ +import sys, types +from types import SimpleNamespace as NS + +# helper_func imports config (needs env vars) and pyrogram; stub config for the unit test. +sys.modules.setdefault("config", types.SimpleNamespace( + FORCE_SUB_CHANNEL=0, ADMINS=[], AUTO_DELETE_TIME=0, AUTO_DEL_SUCCESS_MSG="")) +sys.path.insert(0, ".") +from helper_func import build_caption + +def msg(caption=None, **media): + base = dict(document=None, video=None, audio=None, animation=None) + base.update(media) + return NS(caption=NS(html=caption) if caption else None, **base) + +TPL = "{filename}\n\n{previouscaption}" + +def test_document(): + m = msg("hi", document=NS(file_name="a.pdf")) + assert build_caption(m, TPL) == "a.pdf\n\nhi" + +def test_video_and_audio_now_use_template(): + assert build_caption(msg(None, video=NS(file_name="v.mp4")), TPL) == "v.mp4\n\n" + assert build_caption(msg("x", audio=NS(file_name="s.mp3")), TPL) == "s.mp3\n\nx" + +def test_no_template_keeps_original(): + assert build_caption(msg("keep", document=NS(file_name="a")), None) == "keep" + +def test_photo_keeps_original(): + assert build_caption(msg("pic"), TPL) == "pic" + +def test_unknown_placeholder_does_not_raise(): + m = msg("c", document=NS(file_name="a.pdf")) + assert build_caption(m, "{filename} {oops}") == "a.pdf {oops}" + +def test_broken_template_falls_back(): + m = msg("c", document=NS(file_name="a.pdf")) + assert build_caption(m, "{filename") == "c" + assert build_caption(m, "{0}") == "c" From d7fd0ef92180b47586b24d54ad82c6c41298aeb2 Mon Sep 17 00:00:00 2001 From: Shamil Habeeb Date: Wed, 2 Dec 2026 20:52:56 +0530 Subject: [PATCH 04/10] Retry get_chat with a raw GetChannels on a fresh session --- bot.py | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/bot.py b/bot.py index 0956e9f5f..2f38d1ff6 100644 --- a/bot.py +++ b/bot.py @@ -5,6 +5,7 @@ import pyromod.listen from pyrogram import Client +from pyrogram import raw, utils from pyrogram.enums import ParseMode import sys from datetime import datetime @@ -54,7 +55,17 @@ async def start(self): self.LOGGER(__name__).info("\nBot Stopped. Join https://t.me/CodeXBotzSupport for support") sys.exit() try: - db_channel = await self.get_chat(CHANNEL_ID) + try: + db_channel = await self.get_chat(CHANNEL_ID) + except ValueError: + # Fresh session (no cached peers, e.g. Railway/Heroku/Docker): the bot has + # never seen the channel, so ask Telegram for it by id and retry once. + await self.invoke( + raw.functions.channels.GetChannels( + id=[raw.types.InputChannel(channel_id=utils.get_channel_id(CHANNEL_ID), access_hash=0)] + ) + ) + db_channel = await self.get_chat(CHANNEL_ID) self.db_channel = db_channel test = await self.send_message(chat_id = db_channel.id, text = "Test Message") await test.delete() From ee0badf5057e52d92820e568b949fba2d5a3f8de Mon Sep 17 00:00:00 2001 From: Shamil Habeeb Date: Wed, 2 Dec 2026 20:53:38 +0530 Subject: [PATCH 05/10] Add build_caption --- helper_func.py | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/helper_func.py b/helper_func.py index 5ce68562c..173ce4093 100644 --- a/helper_func.py +++ b/helper_func.py @@ -85,6 +85,32 @@ async def get_message_id(client, message): else: return 0 +class _SafeCaptionDict(dict): + # Unknown placeholders (e.g. a stray "{name}") are left as typed instead of raising KeyError. + def __missing__(self, key): + return "{" + key + "}" + +def build_caption(msg, custom_caption): + """Return the caption to send for a stored message. + + CUSTOM_CAPTION is applied to every media type that has a file name + (document, video, audio, animation), not only documents. A bad template + falls back to the original caption instead of dropping the file. + """ + previous = "" if not msg.caption else msg.caption.html + if not custom_caption: + return previous + media = msg.document or msg.video or msg.audio or msg.animation + if not media: + return previous + try: + return custom_caption.format_map(_SafeCaptionDict( + previouscaption=previous, + filename=getattr(media, "file_name", None) or "", + )) + except (ValueError, IndexError, AttributeError): + return previous + def get_readable_time(seconds: int) -> str: count = 0 up_time = "" From 2f3b476ff876ee630e2f5c275743f2e789e5e924 Mon Sep 17 00:00:00 2001 From: Shamil Habeeb Date: Wed, 2 Dec 2026 20:53:55 +0530 Subject: [PATCH 06/10] Use build_caption in start handler --- plugins/start.py | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/plugins/start.py b/plugins/start.py index 4ed59ca68..16342ecc6 100644 --- a/plugins/start.py +++ b/plugins/start.py @@ -9,7 +9,7 @@ from bot import Bot from config import ADMINS, FORCE_MSG, START_MSG, CUSTOM_CAPTION, DISABLE_CHANNEL_BUTTON, PROTECT_CONTENT, START_PIC, AUTO_DELETE_TIME, AUTO_DELETE_MSG, JOIN_REQUEST_ENABLE,FORCE_SUB_CHANNEL -from helper_func import subscribed,decode, get_messages, delete_file +from helper_func import subscribed,decode, get_messages, delete_file, build_caption from database.database import add_user, del_user, full_userbase, present_user @@ -62,10 +62,7 @@ async def start_command(client: Client, message: Message): for msg in messages: - if bool(CUSTOM_CAPTION) & bool(msg.document): - caption = CUSTOM_CAPTION.format(previouscaption = "" if not msg.caption else msg.caption.html, filename = msg.document.file_name) - else: - caption = "" if not msg.caption else msg.caption.html + caption = build_caption(msg, CUSTOM_CAPTION) if DISABLE_CHANNEL_BUTTON: reply_markup = msg.reply_markup @@ -257,4 +254,3 @@ async def send_text(client: Bot, message: Message): msg = await message.reply(REPLY_ERROR) await asyncio.sleep(8) await msg.delete() - From 2b5f4161c4d6ac6e15bcdec70ed0615269b8d394 Mon Sep 17 00:00:00 2001 From: Shamil Habeeb Date: Wed, 2 Dec 2026 20:54:13 +0530 Subject: [PATCH 07/10] Add tests for build_caption --- tests/{4-test_build_caption.py => test_build_caption.py} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename tests/{4-test_build_caption.py => test_build_caption.py} (100%) diff --git a/tests/4-test_build_caption.py b/tests/test_build_caption.py similarity index 100% rename from tests/4-test_build_caption.py rename to tests/test_build_caption.py From d407d3ee2701a6caf05111d7c77e8a718c2fcae9 Mon Sep 17 00:00:00 2001 From: Shamil Habeeb Date: Wed, 2 Dec 2026 20:55:26 +0530 Subject: [PATCH 08/10] Delete plugins/3-start.py --- plugins/3-start.py | 257 --------------------------------------------- 1 file changed, 257 deletions(-) delete mode 100644 plugins/3-start.py diff --git a/plugins/3-start.py b/plugins/3-start.py deleted file mode 100644 index 89eab8c41..000000000 --- a/plugins/3-start.py +++ /dev/null @@ -1,257 +0,0 @@ -#(©)CodeXBotz - -import os -import asyncio -from pyrogram import Client, filters -from pyrogram.enums import ParseMode -from pyrogram.types import Message, InlineKeyboardMarkup, InlineKeyboardButton -from pyrogram.errors import FloodWait, UserIsBlocked, InputUserDeactivated - -from bot import Bot -from config import ADMINS, FORCE_MSG, START_MSG, CUSTOM_CAPTION, DISABLE_CHANNEL_BUTTON, PROTECT_CONTENT, START_PIC, AUTO_DELETE_TIME, AUTO_DELETE_MSG, JOIN_REQUEST_ENABLE,FORCE_SUB_CHANNEL -from helper_func import subscribed,decode, get_messages, delete_file, build_caption -from database.database import add_user, del_user, full_userbase, present_user - - -@Bot.on_message(filters.command('start') & filters.private & subscribed) -async def start_command(client: Client, message: Message): - id = message.from_user.id - if not await present_user(id): - try: - await add_user(id) - except: - pass - text = message.text - if len(text)>7: - try: - base64_string = text.split(" ", 1)[1] - except: - return - string = await decode(base64_string) - argument = string.split("-") - if len(argument) == 3: - try: - start = int(int(argument[1]) / abs(client.db_channel.id)) - end = int(int(argument[2]) / abs(client.db_channel.id)) - except: - return - if start <= end: - ids = range(start,end+1) - else: - ids = [] - i = start - while True: - ids.append(i) - i -= 1 - if i < end: - break - elif len(argument) == 2: - try: - ids = [int(int(argument[1]) / abs(client.db_channel.id))] - except: - return - temp_msg = await message.reply("Please wait...") - try: - messages = await get_messages(client, ids) - except: - await message.reply_text("Something went wrong..!") - return - await temp_msg.delete() - - track_msgs = [] - - for msg in messages: - - caption = build_caption(msg, CUSTOM_CAPTION) - - if DISABLE_CHANNEL_BUTTON: - reply_markup = msg.reply_markup - else: - reply_markup = None - - if AUTO_DELETE_TIME and AUTO_DELETE_TIME > 0: - - try: - copied_msg_for_deletion = await msg.copy(chat_id=message.from_user.id, caption=caption, parse_mode=ParseMode.HTML, reply_markup=reply_markup, protect_content=PROTECT_CONTENT) - if copied_msg_for_deletion: - track_msgs.append(copied_msg_for_deletion) - else: - print("Failed to copy message, skipping.") - - except FloodWait as e: - await asyncio.sleep(e.value) - copied_msg_for_deletion = await msg.copy(chat_id=message.from_user.id, caption=caption, parse_mode=ParseMode.HTML, reply_markup=reply_markup, protect_content=PROTECT_CONTENT) - if copied_msg_for_deletion: - track_msgs.append(copied_msg_for_deletion) - else: - print("Failed to copy message after retry, skipping.") - - except Exception as e: - print(f"Error copying message: {e}") - pass - - else: - try: - await msg.copy(chat_id=message.from_user.id, caption=caption, parse_mode=ParseMode.HTML, reply_markup=reply_markup, protect_content=PROTECT_CONTENT) - await asyncio.sleep(0.5) - except FloodWait as e: - await asyncio.sleep(e.value) - await msg.copy(chat_id=message.from_user.id, caption=caption, parse_mode=ParseMode.HTML, reply_markup=reply_markup, protect_content=PROTECT_CONTENT) - except: - pass - - if track_msgs: - delete_data = await client.send_message( - chat_id=message.from_user.id, - text=AUTO_DELETE_MSG.format(time=AUTO_DELETE_TIME) - ) - # Schedule the file deletion task after all messages have been copied - asyncio.create_task(delete_file(track_msgs, client, delete_data)) - else: - print("No messages to track for deletion.") - - return - else: - reply_markup = InlineKeyboardMarkup( - [ - [ - InlineKeyboardButton("😊 About Me", callback_data = "about"), - InlineKeyboardButton("🔒 Close", callback_data = "close") - ] - ] - ) - if START_PIC: # Check if START_PIC has a value - await message.reply_photo( - photo=START_PIC, - caption=START_MSG.format( - first=message.from_user.first_name, - last=message.from_user.last_name, - username=None if not message.from_user.username else '@' + message.from_user.username, - mention=message.from_user.mention, - id=message.from_user.id - ), - reply_markup=reply_markup, - quote=True - ) - else: # If START_PIC is empty, send only the text - await message.reply_text( - text=START_MSG.format( - first=message.from_user.first_name, - last=message.from_user.last_name, - username=None if not message.from_user.username else '@' + message.from_user.username, - mention=message.from_user.mention, - id=message.from_user.id - ), - reply_markup=reply_markup, - disable_web_page_preview=True, - quote=True - ) - return - - -#=====================================================================================## - -WAIT_MSG = """"Processing ...""" - -REPLY_ERROR = """Use this command as a replay to any telegram message with out any spaces.""" - -#=====================================================================================## - - -@Bot.on_message(filters.command('start') & filters.private) -async def not_joined(client: Client, message: Message): - - if bool(JOIN_REQUEST_ENABLE): - invite = await client.create_chat_invite_link( - chat_id=FORCE_SUB_CHANNEL, - creates_join_request=True - ) - ButtonUrl = invite.invite_link - else: - ButtonUrl = client.invitelink - - buttons = [ - [ - InlineKeyboardButton( - "Join Channel", - url = ButtonUrl) - ] - ] - - try: - buttons.append( - [ - InlineKeyboardButton( - text = 'Try Again', - url = f"https://t.me/{client.username}?start={message.command[1]}" - ) - ] - ) - except IndexError: - pass - - await message.reply( - text = FORCE_MSG.format( - first = message.from_user.first_name, - last = message.from_user.last_name, - username = None if not message.from_user.username else '@' + message.from_user.username, - mention = message.from_user.mention, - id = message.from_user.id - ), - reply_markup = InlineKeyboardMarkup(buttons), - quote = True, - disable_web_page_preview = True - ) - -@Bot.on_message(filters.command('users') & filters.private & filters.user(ADMINS)) -async def get_users(client: Bot, message: Message): - msg = await client.send_message(chat_id=message.chat.id, text=WAIT_MSG) - users = await full_userbase() - await msg.edit(f"{len(users)} users are using this bot") - -@Bot.on_message(filters.private & filters.command('broadcast') & filters.user(ADMINS)) -async def send_text(client: Bot, message: Message): - if message.reply_to_message: - query = await full_userbase() - broadcast_msg = message.reply_to_message - total = 0 - successful = 0 - blocked = 0 - deleted = 0 - unsuccessful = 0 - - pls_wait = await message.reply("Broadcasting Message.. This will Take Some Time") - for chat_id in query: - try: - await broadcast_msg.copy(chat_id) - successful += 1 - except FloodWait as e: - await asyncio.sleep(e.x) - await broadcast_msg.copy(chat_id) - successful += 1 - except UserIsBlocked: - await del_user(chat_id) - blocked += 1 - except InputUserDeactivated: - await del_user(chat_id) - deleted += 1 - except: - unsuccessful += 1 - pass - total += 1 - - status = f"""Broadcast Completed - -Total Users: {total} -Successful: {successful} -Blocked Users: {blocked} -Deleted Accounts: {deleted} -Unsuccessful: {unsuccessful}""" - - return await pls_wait.edit(status) - - else: - msg = await message.reply(REPLY_ERROR) - await asyncio.sleep(8) - await msg.delete() - From c7d69bf2f209809183acb5b9b4de803508996d68 Mon Sep 17 00:00:00 2001 From: Shamil Habeeb Date: Wed, 2 Dec 2026 20:55:40 +0530 Subject: [PATCH 09/10] Delete 1-bot.py --- 1-bot.py | 91 -------------------------------------------------------- 1 file changed, 91 deletions(-) delete mode 100644 1-bot.py diff --git a/1-bot.py b/1-bot.py deleted file mode 100644 index 2f38d1ff6..000000000 --- a/1-bot.py +++ /dev/null @@ -1,91 +0,0 @@ -#(©)Codexbotz - -from aiohttp import web -from plugins import web_server - -import pyromod.listen -from pyrogram import Client -from pyrogram import raw, utils -from pyrogram.enums import ParseMode -import sys -from datetime import datetime - -from config import API_HASH, APP_ID, LOGGER, TG_BOT_TOKEN, TG_BOT_WORKERS, FORCE_SUB_CHANNEL, CHANNEL_ID, PORT - - -ascii_art = """ -░█████╗░░█████╗░██████╗░███████╗██╗░░██╗██████╗░░█████╗░████████╗███████╗ -██╔══██╗██╔══██╗██╔══██╗██╔════╝╚██╗██╔╝██╔══██╗██╔══██╗╚══██╔══╝╚════██║ -██║░░╚═╝██║░░██║██║░░██║█████╗░░░╚███╔╝░██████╦╝██║░░██║░░░██║░░░░░███╔═╝ -██║░░██╗██║░░██║██║░░██║██╔══╝░░░██╔██╗░██╔══██╗██║░░██║░░░██║░░░██╔══╝░░ -╚█████╔╝╚█████╔╝██████╔╝███████╗██╔╝╚██╗██████╦╝╚█████╔╝░░░██║░░░███████╗ -░╚════╝░░╚════╝░╚═════╝░╚══════╝╚═╝░░╚═╝╚═════╝░░╚════╝░░░░╚═╝░░░╚══════╝ -""" - -class Bot(Client): - def __init__(self): - super().__init__( - name="Bot", - api_hash=API_HASH, - api_id=APP_ID, - plugins={ - "root": "plugins" - }, - workers=TG_BOT_WORKERS, - bot_token=TG_BOT_TOKEN - ) - self.LOGGER = LOGGER - - async def start(self): - await super().start() - usr_bot_me = await self.get_me() - self.uptime = datetime.now() - - if FORCE_SUB_CHANNEL: - try: - link = (await self.get_chat(FORCE_SUB_CHANNEL)).invite_link - if not link: - await self.export_chat_invite_link(FORCE_SUB_CHANNEL) - link = (await self.get_chat(FORCE_SUB_CHANNEL)).invite_link - self.invitelink = link - except Exception as a: - self.LOGGER(__name__).warning(a) - self.LOGGER(__name__).warning("Bot can't Export Invite link from Force Sub Channel!") - self.LOGGER(__name__).warning(f"Please Double check the FORCE_SUB_CHANNEL value and Make sure Bot is Admin in channel with Invite Users via Link Permission, Current Force Sub Channel Value: {FORCE_SUB_CHANNEL}") - self.LOGGER(__name__).info("\nBot Stopped. Join https://t.me/CodeXBotzSupport for support") - sys.exit() - try: - try: - db_channel = await self.get_chat(CHANNEL_ID) - except ValueError: - # Fresh session (no cached peers, e.g. Railway/Heroku/Docker): the bot has - # never seen the channel, so ask Telegram for it by id and retry once. - await self.invoke( - raw.functions.channels.GetChannels( - id=[raw.types.InputChannel(channel_id=utils.get_channel_id(CHANNEL_ID), access_hash=0)] - ) - ) - db_channel = await self.get_chat(CHANNEL_ID) - self.db_channel = db_channel - test = await self.send_message(chat_id = db_channel.id, text = "Test Message") - await test.delete() - except Exception as e: - self.LOGGER(__name__).warning(e) - self.LOGGER(__name__).warning(f"Make Sure bot is Admin in DB Channel, and Double check the CHANNEL_ID Value, Current Value {CHANNEL_ID}") - self.LOGGER(__name__).info("\nBot Stopped. Join https://t.me/CodeXBotzSupport for support") - sys.exit() - - self.set_parse_mode(ParseMode.HTML) - self.LOGGER(__name__).info(f"Bot Running..!\n\nCreated by \nhttps://t.me/CodeXBotz") - print(ascii_art) - print("""Welcome to CodeXBotz File Sharing Bot""") - self.username = usr_bot_me.username - #web-response - app = web.AppRunner(await web_server()) - await app.setup() - bind_address = "0.0.0.0" - await web.TCPSite(app, bind_address, PORT).start() - - async def stop(self, *args): - await super().stop() - self.LOGGER(__name__).info("Bot stopped.") From c6e3fa915d525a131fe950abd673fedfe1fb0474 Mon Sep 17 00:00:00 2001 From: Shamil Habeeb Date: Wed, 2 Dec 2026 20:55:54 +0530 Subject: [PATCH 10/10] Delete 2-helper_func.py --- 2-helper_func.py | 147 ----------------------------------------------- 1 file changed, 147 deletions(-) delete mode 100644 2-helper_func.py diff --git a/2-helper_func.py b/2-helper_func.py deleted file mode 100644 index 173ce4093..000000000 --- a/2-helper_func.py +++ /dev/null @@ -1,147 +0,0 @@ -#(©)Codexbotz - -import base64 -import re -import asyncio -import logging -from pyrogram import filters -from pyrogram.enums import ChatMemberStatus -from config import FORCE_SUB_CHANNEL, ADMINS, AUTO_DELETE_TIME, AUTO_DEL_SUCCESS_MSG -from pyrogram.errors.exceptions.bad_request_400 import UserNotParticipant -from pyrogram.errors import FloodWait - -async def is_subscribed(filter, client, update): - if not FORCE_SUB_CHANNEL: - return True - user_id = update.from_user.id - if user_id in ADMINS: - return True - try: - member = await client.get_chat_member(chat_id = FORCE_SUB_CHANNEL, user_id = user_id) - except UserNotParticipant: - return False - - if not member.status in [ChatMemberStatus.OWNER, ChatMemberStatus.ADMINISTRATOR, ChatMemberStatus.MEMBER]: - return False - else: - return True - -async def encode(string): - string_bytes = string.encode("ascii") - base64_bytes = base64.urlsafe_b64encode(string_bytes) - base64_string = (base64_bytes.decode("ascii")).strip("=") - return base64_string - -async def decode(base64_string): - base64_string = base64_string.strip("=") # links generated before this commit will be having = sign, hence striping them to handle padding errors. - base64_bytes = (base64_string + "=" * (-len(base64_string) % 4)).encode("ascii") - string_bytes = base64.urlsafe_b64decode(base64_bytes) - string = string_bytes.decode("ascii") - return string - -async def get_messages(client, message_ids): - messages = [] - total_messages = 0 - while total_messages != len(message_ids): - temb_ids = message_ids[total_messages:total_messages+200] - try: - msgs = await client.get_messages( - chat_id=client.db_channel.id, - message_ids=temb_ids - ) - except FloodWait as e: - await asyncio.sleep(e.x) - msgs = await client.get_messages( - chat_id=client.db_channel.id, - message_ids=temb_ids - ) - except: - pass - total_messages += len(temb_ids) - messages.extend(msgs) - return messages - -async def get_message_id(client, message): - if message.forward_from_chat: - if message.forward_from_chat.id == client.db_channel.id: - return message.forward_from_message_id - else: - return 0 - elif message.forward_sender_name: - return 0 - elif message.text: - pattern = "https://t.me/(?:c/)?(.*)/(\d+)" - matches = re.match(pattern,message.text) - if not matches: - return 0 - channel_id = matches.group(1) - msg_id = int(matches.group(2)) - if channel_id.isdigit(): - if f"-100{channel_id}" == str(client.db_channel.id): - return msg_id - else: - if channel_id == client.db_channel.username: - return msg_id - else: - return 0 - -class _SafeCaptionDict(dict): - # Unknown placeholders (e.g. a stray "{name}") are left as typed instead of raising KeyError. - def __missing__(self, key): - return "{" + key + "}" - -def build_caption(msg, custom_caption): - """Return the caption to send for a stored message. - - CUSTOM_CAPTION is applied to every media type that has a file name - (document, video, audio, animation), not only documents. A bad template - falls back to the original caption instead of dropping the file. - """ - previous = "" if not msg.caption else msg.caption.html - if not custom_caption: - return previous - media = msg.document or msg.video or msg.audio or msg.animation - if not media: - return previous - try: - return custom_caption.format_map(_SafeCaptionDict( - previouscaption=previous, - filename=getattr(media, "file_name", None) or "", - )) - except (ValueError, IndexError, AttributeError): - return previous - -def get_readable_time(seconds: int) -> str: - count = 0 - up_time = "" - time_list = [] - time_suffix_list = ["s", "m", "h", "days"] - while count < 4: - count += 1 - remainder, result = divmod(seconds, 60) if count < 3 else divmod(seconds, 24) - if seconds == 0 and remainder == 0: - break - time_list.append(int(result)) - seconds = int(remainder) - hmm = len(time_list) - for x in range(hmm): - time_list[x] = str(time_list[x]) + time_suffix_list[x] - if len(time_list) == 4: - up_time += f"{time_list.pop()}, " - time_list.reverse() - up_time += ":".join(time_list) - return up_time - -async def delete_file(messages, client, process): - await asyncio.sleep(AUTO_DELETE_TIME) - for msg in messages: - try: - await client.delete_messages(chat_id=msg.chat.id, message_ids=[msg.id]) - except Exception as e: - await asyncio.sleep(e.x) - print(f"The attempt to delete the media {msg.id} was unsuccessful: {e}") - - await process.edit_text(AUTO_DEL_SUCCESS_MSG) - - -subscribed = filters.create(is_subscribed)