I'm developing a Telegram bot using python-telegram-bot to handle and reply to posts in a specific channel. The bot starts successfully and shows "Bot is running...", but it never replies to posts in the channel.
Here's the relevant code for handling channel posts:
async def handle_channel_post(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle new channel posts by adding the message link as a reply."""
try:
# Get the message and channel info
message = update.channel_post or update.message
if not message:
return
# Verify this is from our target channel
if message.chat.username != self.channel_username:
return
channel_id = message.chat.id
message_id = message.message_id
# Construct the message link
if str(channel_id).startswith("-100"):
# Private channels (or supergroups)
link = f"https://t.me/c/{str(channel_id)[4:]}/{message_id}"
else:
# Public channels
link = f"https://t.me/{self.channel_username.replace('@', '')}/{message_id}"
# Create the reply text
reply_text = f"View message: [Click here]({link})"
# Reply to the channel post
await context.bot.send_message(
chat_id=channel_id,
text=reply_text,
reply_to_message_id=message_id,
parse_mode="Markdown"
)
except Exception as e:
print(f"Error handling channel post: {e}")
This is the main method:
async def main():
BOT_TOKEN = "<MT_BOT_TOKEN>"
CHANNEL_USERNAME = "@TestTGBot123"
bot = ChannelBot(BOT_TOKEN, CHANNEL_USERNAME)
await bot.start()
I tried with another channel and different channel types but still not working. The bot is admin and also has privileges to post in the channel.
The issue is with this part of the code:
if message.chat.username != self.channel_username:
return
The message.chat.username
returns the channel username without the '@' and your self.channel.username
includes '@'
Try this:
if message.chat.username != self.channel_username.replace("@", ""):
return
It removes '@' from self.channel.username
and your bot should work as expected.