Skip to content
13 changes: 12 additions & 1 deletion bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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()
Expand Down
26 changes: 26 additions & 0 deletions helper_func.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 = ""
Expand Down
8 changes: 2 additions & 6 deletions plugins/start.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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()

38 changes: 38 additions & 0 deletions tests/test_build_caption.py
Original file line number Diff line number Diff line change
@@ -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"