如何让Telegram Bot指定发送消息到群组的message_thread_id(话题)
解决Telegram Bot发送消息到指定话题的问题
要让Bot把消息发送到群组内指定的话题,只需在调用send_message方法时额外传入message_thread_id参数即可,分两种场景处理:
场景1:固定发送到某个指定话题
如果想让Bot的所有指令回复都固定到某个特定话题,直接把该话题的ID填入参数:
async def add_point(update: Update, context: ContextTypes.DEFAULT_TYPE): user = update.effective_user chat = update.effective_chat # 替换成你目标话题的ID TARGET_THREAD_ID = 123456 is_admin = user.id in [admin.user.id for admin in await context.bot.get_chat_administrators(chat.id)] if not is_admin: await context.bot.send_message( chat_id=chat.id, text="Only admins use this command.", message_thread_id=TARGET_THREAD_ID # 添加话题ID参数 ) return # check if the message is a reply to another message if not update.message.reply_to_message: await context.bot.send_message( chat_id=update.effective_chat.id, text="Please reply to a player to award a point.", message_thread_id=TARGET_THREAD_ID # 添加话题ID参数 ) return
场景2:回复到用户发送指令所在的话题
如果希望Bot自动回复到用户发送指令的那个话题,直接从update.effective_message中获取当前的话题ID:
async def add_point(update: Update, context: ContextTypes.DEFAULT_TYPE): user = update.effective_user chat = update.effective_chat # 获取用户发送指令所在的话题ID current_thread_id = update.effective_message.message_thread_id is_admin = user.id in [admin.user.id for admin in await context.bot.get_chat_administrators(chat.id)] if not is_admin: await context.bot.send_message( chat_id=chat.id, text="Only admins use this command.", message_thread_id=current_thread_id # 使用当前话题ID ) return # check if the message is a reply to another message if not update.message.reply_to_message: await context.bot.send_message( chat_id=update.effective_chat.id, text="Please reply to a player to award a point.", message_thread_id=current_thread_id # 使用当前话题ID ) return
注意:只有当群组开启了话题功能(forum)时,message_thread_id才会生效,否则该参数会被忽略。
内容的提问来源于stack exchange,提问作者David Henson
相关产品推荐
相关产品推荐

