代码之家  ›  专栏  ›  技术社区  ›  iaMeisam

Bot未响应Telegram中的频道帖子Bot API(python-Telegram-Bot)

  •  3
  • iaMeisam  · 技术社区  · 11 月前

    我正在开发一个电报机器人,使用python电报机器人来处理和回复特定渠道中的帖子。机器人成功启动并显示“机器人正在运行…”,但它从不回复频道中的帖子。

    以下是处理频道帖子的相关代码:

    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}")
    

    主要方法如下:

    async def main():
        BOT_TOKEN = "<MT_BOT_TOKEN>"
        CHANNEL_USERNAME = "@TestTGBot123"
        
        bot = ChannelBot(BOT_TOKEN, CHANNEL_USERNAME)
    
        await bot.start()
    

    我尝试了另一个频道和不同的频道类型,但仍然不起作用。该机器人是管理员,也有在频道中发布的权限。

    1 回复  |  直到 11 月前
        1
  •  2
  •   Hr.Panahi    11 月前

    问题在于代码的这一部分:

    if message.chat.username != self.channel_username:
        return
    

    这个 message.chat.username 返回不带“@”的频道用户名和您的 self.channel.username 包括“@”

    试试这个:

    if message.chat.username != self.channel_username.replace("@", ""):
        return
    

    它从中删除“@” self.channel.用户名 你的机器人应该按预期工作。