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

如何通过chat_id与access_hash获取群组消息(解决ChannelInvalidError)

解决Telethon获取群组消息时的ChannelInvalidError问题

你遇到的问题是因为InputPeerChannel仅适用于频道(包括超级群组),普通群组需要用对应的InputPeerChat构造实体,或者用更通用的方式自动处理:

两种解决方法:

  • 普通群组(非超级群):使用InputPeerChat,无需access_hash,仅传入chat_id即可:

    entity = InputPeerChat(int(chat_id))
    
    async for message in client.iter_messages(entity, reverse=True, offset_date=offset_date):
        # 保存消息的逻辑
    
  • 通用方案(兼容频道、超级群、普通群):直接用client.get_entity自动获取正确实体,不用手动区分类型:

    entity = await client.get_entity(int(chat_id))
    
    async for message in client.iter_messages(entity, reverse=True, offset_date=offset_date):
        # 保存消息的逻辑
    

get_entity会根据传入的chat_id自动识别对应的聊天类型,返回适配的实体对象,能避免手动构造InputPeer时的类型错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 23:34:51