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

使用Telethon获取Telegram最新帖子评论为何返回频道ID而非评论者ID

问题原因

你看到的PeerChannel(channel_id=1162560626)是因为comment.from_id返回的是Peer类型对象,而非单纯的用户ID。出现频道ID的情况有两种可能:

  • comments.messages里包含了原频道帖子本身(原帖子由频道发布,所以from_id是频道Peer)
  • 部分评论由其他频道账号发出,而非普通用户
解决方案

需要做两个关键处理:

  1. 过滤掉原帖子本身,只保留真正的评论消息
  2. 仅提取来自普通用户(PeerUser类型)的ID

修改后的代码如下:

async def main():
    if not await client.is_user_authorized():
        await client.start(bot_token=os.getenv('BOT_TOKEN'))

    subscribed_channels = await get_my_channels(client=client)
    from telethon.tl.types import PeerUser  # 导入PeerUser类型用于判断

    for channel in subscribed_channels:
        print(f"Channel name: {channel.title}, ID: {channel.id}")
        message = await client.get_messages(channel.id, limit=1)
        target_msg_id = message[0].id
        if message[0].replies is not None:
            commenters = []

            try:
                comments = await client(functions.messages.GetDiscussionMessageRequest(
                    peer=channel.id,
                    msg_id=target_msg_id
                ))

                for comment in comments.messages:
                    # 跳过原帖子本身,只处理评论
                    if comment.id == target_msg_id:
                        continue
                    # 只提取普通用户的评论者ID
                    if isinstance(comment.from_id, PeerUser):
                        commenters.append(comment.from_id.user_id)
                
                for commenter_id in commenters:
                    print(f"User ID: {commenter_id}")
            except Exception as e:
                print(f"Error getting commenters for the channel {channel.title}: {e}")
                continue

await client.disconnect()
补充说明
  • 导入PeerUser是为了精准判断评论者是否为普通用户,若需处理来自群组(PeerChat)的评论,可额外导入并判断该类型
  • 跳过原帖子是因为GetDiscussionMessageRequest的返回结果默认包含触发讨论的原消息,这条消息的发布者是频道本身,因此会返回频道Peer

内容的提问来源于stack exchange,提问作者kuchuluk

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 19:13:41