如何获取通过KeyboardButtonRequestChat发送的Telegram频道ID?
问题分析与解决方案
你的问题核心是对用户选择频道后发送的消息类型判断错误:
- 用户通过
KeyboardButtonRequestChat选择频道后,发送的不是普通文本消息,而是带有chat_shared字段的消息,所以你原来监听content_types=['text']的处理器根本不会触发。 - 消息是在你和机器人的私人聊天中发送的,不是频道内的消息,所以
chat_type=['channel']的过滤条件完全不适用。
修正后的代码
from aiogram import Bot as AiogramBot, Dispatcher, executor, types from aiogram.types.reply_keyboard import (ReplyKeyboardMarkup, KeyboardButton, KeyboardButtonRequestChat, KeyboardButtonRequestUser) bot_token = "" bot = AiogramBot(bot_token) dp = Dispatcher(bot) @dp.message_handler(content_types=['text']) async def text_handler(message: types.Message): await message.answer("I'm here", reply_markup=ReplyKeyboardMarkup( [ [ KeyboardButton("test1", request_chat=KeyboardButtonRequestChat( request_id=1, user_is_bot=False, chat_is_channel=True, chat_is_forum=False )), KeyboardButton("test2", request_user=KeyboardButtonRequestUser( request_id=2, user_is_bot=False )), ] ] )) # 处理用户分享的频道信息 @dp.message_handler(content_types=['chat_shared']) async def handle_shared_channel(message: types.Message): # 从chat_shared字段中获取频道ID channel_id = message.chat_shared.chat_id # 给用户发送频道ID,目标为用户与机器人的私人聊天 await bot.send_message(message.chat.id, f"Channel ID: {channel_id}") if __name__ == "__main__": executor.start_polling(dp)
关键修改点
- 新增监听
content_types=['chat_shared']的处理器,专门处理用户通过按钮分享的频道/群组信息。 - 通过
message.chat_shared.chat_id获取真实的频道ID,而非message.chat.id(后者是用户与机器人的聊天ID)。 - 移除无效的
chat_type=['channel']过滤条件,因为消息来自私人聊天而非频道本身。
内容的提问来源于stack exchange,提问作者XTLSREALITY
相关产品推荐
相关产品推荐

