You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取通过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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 04:57:19