如何让UserBot在Telegram帖子讨论区发消息及处理动态聊天链接?
如何让Telegram UserBot向帖子评论区发送消息
方法一:直接提取评论区聊天ID
Telegram帖子的评论区本质是关联的讨论组/超级群,你可以通过帖子的Message对象直接获取对应的聊天ID,无需解析链接:
以Pyrogram为例,代码示例:
from pyrogram import Client app = Client("your_userbot_session") async def post_comment(): # 替换为目标频道ID/用户名和帖子ID target_channel = "@your_target_channel" post_id = 456 # 获取帖子的Message对象 post_message = await app.get_messages(target_channel, post_id) # 检查是否存在关联的评论区聊天 if post_message.linked_chat_id: # 直接向评论区聊天发送消息 await app.send_message(post_message.linked_chat_id, "这是UserBot发送的评论") else: print("该帖子未开启评论功能") app.run(post_comment())
如果使用Telethon,逻辑类似,通过GetMessagesRequest获取帖子后,访问message.linked_chat_id即可。
方法二:解析「发表评论」按钮链接
如果需要从帖子的「发表评论」按钮提取目标聊天,可解析按钮的URL并跳转:
from pyrogram import Client app = Client("your_userbot_session") async def parse_comment_button(): target_channel = "@your_target_channel" post_id = 456 post_message = await app.get_messages(target_channel, post_id) # 遍历帖子的内联键盘按钮 if post_message.reply_markup and post_message.reply_markup.inline_keyboard: for row in post_message.reply_markup.inline_keyboard: for button in row: if "发表评论" in button.text: # 解析tg://协议链接 url = button.url if "tg://resolve?domain=" in url: # 提取评论区聊天的域名/用户名 chat_identifier = url.split("domain=")[1].split("&")[0] # 发送评论 await app.send_message(chat_identifier, "通过按钮解析发送的评论") break app.run(parse_comment_button())
注意事项
- 确保UserBot已经加入目标评论区聊天(部分私有讨论组需要手动加入或获取邀请)
- 部分频道的评论区可能限制发言权限,需确保UserBot有发言权限
内容的提问来源于stack exchange,提问作者Eugene Sidorenko
相关产品推荐
相关产品推荐

