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

如何用Pyrogram Python库输出指定类型频道列表?排查代码无输出问题

无法输出指定类型的聊天对话内容

初始化会话后遍历聊天列表,尝试打印ChatType.PRIVATE类型的聊天,但控制台没有输出符合条件的内容。

测试遍历所有聊天的代码:

async for dialog in app.get_dialogs():
    print(dialog.chat)

得到的单条聊天数据格式示例:

{
    "_": "Chat",
    "id": -4031246626,
    "type": "ChatType.GROUP",
    "is_creator": true,
    "title": "comments",
    "has_protected_content": false,
    "members_count": 0
}

完整问题代码:

async def main():
    async with app:
        print("[LOG] --- [INFO] ---> The client has Started.")
        
        # Get all dialogs (chats) the user is involved with
        
        try:
            async for dialog in app.get_dialogs():
                print(dialog.chat)
                if dialog.chat.type == "ChatType.PRIVATE":
                    print(f"Private Chat: {dialog.chat.title} | ID: {dialog.chat.id}")
                
        except Exception as e:
            print(f"[LOG] --- [ERROR] ---> {e}")
            
app.run(main())

问题原因

dialog.chat.type是枚举类型成员,不是字符串。直接用字符串"ChatType.PRIVATE"和它比较永远不相等,因此不会执行打印逻辑。

修改后的代码

# 根据使用的Telegram API库导入枚举类型,以Telethon为例
from telethon.tl.types import ChatType

async def main():
    async with app:
        print("[LOG] --- [INFO] ---> The client has Started.")
        
        try:
            async for dialog in app.get_dialogs():
                # 可选:调试时打印类型的实际信息
                # print(type(dialog.chat.type), dialog.chat.type)
                if dialog.chat.type == ChatType.PRIVATE:
                    # 私聊无群组标题,优先用对方昵称/用户名避免空值
                    chat_name = dialog.chat.title or dialog.chat.first_name or dialog.chat.username or "Unknown"
                    print(f"Private Chat: {chat_name} | ID: {dialog.chat.id}")
                
        except Exception as e:
            print(f"[LOG] --- [ERROR] ---> {e}")
            
app.run(main())

额外说明

  • 不同库的ChatType枚举导入路径不同,根据实际使用的库调整导入语句
  • 私聊对话的title字段通常为空,优先使用first_name或username显示聊天名称
  • 若不确定类型匹配方式,可先打印type(dialog.chat.type)和dialog.chat.type的值,确认枚举成员的正确引用格式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 16:10:05