我正在使用 python-telegram-bot 开发一个 Telegram 机器人来处理和回复特定频道中的帖子。机器人成功启动并显示“机器人正在运行...”,但它从未回复频道中的帖子。
以下是处理频道帖子的相关代码:
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()
我尝试了另一个频道和不同的频道类型,但仍然不起作用。该机器人是管理员,也有在频道中发帖的权限。
问题出在这部分代码上:
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.username
中删除“@”,您的机器人应该按预期工作。