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

Telethon获取私聊未读消息数异常:返回0或空列表问题求助

解决Telethon对话未读消息数获取异常的办法
  • 强制刷新对话数据
    调用client.get_dialogs()时加上force_update=True参数,跳过本地缓存直接从服务器拉取最新数据,避免缓存导致的未读数错误:

    dialogs = client.get_dialogs(force_update=True)
    
  • 修正对话类型判断逻辑
    别用is_private属性来判断私人对话,直接通过Peer类型判断更靠谱,比如:

    from telethon.tl.types import PeerUser
    
    for d in dialogs:
        if isinstance(d.peer, PeerUser):
            # 处理私人对话,获取未读数
            print(f"{d.name} 未读消息数: {d.unread_count}")
    

    部分用户实体的is_private属性可能未被正确赋值,会导致原判断逻辑失效。

  • 直接封装GetPeerDialogsRequest批量获取
    既然单独调用GetPeerDialogsRequest能拿到正确数据,可以批量获取所有对话的peer后再批量请求:

    from telethon.tl.functions.messages import GetPeerDialogsRequest
    
    # 先获取所有对话的peer列表
    dialog_peers = [d.peer for d in client.get_dialogs(force_update=True)]
    # 批量请求对话信息
    result = client(GetPeerDialogsRequest(peers=dialog_peers))
    # 遍历结果提取未读数
    for dialog in result.dialogs:
        if dialog.unread_count > 0:
            print(f"未读消息数: {dialog.unread_count}")
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 11:25:59