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

如何通过Telethon判断已加入的对话/频道是否为私密?

判断Telethon对话是否为私密的方法

要判断通过iter.dialogs()获取的对话是否为私密,核心是根据dialog.entity的不同类型,使用对应的属性或标志位来判断,具体方案如下:

  • 区分实体类型判断:Telegram的对话实体分为三类,不同类型的私密判断逻辑不同:

    • 一对一私聊(PrivateChat):本身就是私密对话,直接判定为私密。
    • 普通群聊(Chat):若没有公开用户名(entity.username为None),即为私密群。
    • 频道/超级群(Channel):优先用entity.flags.private标志位判断,该位直接标识频道是否私密;若使用旧版Telethon不支持属性式访问,可通过位掩码计算(entity.flags & 1) != 0来判断。无公开用户名(entity.username为None)可作为辅助判断依据。
  • 代码实现示例:

from telethon import TelegramClient
from telethon.tl.types import Channel, PrivateChat, Chat

async def is_dialog_private(dialog):
    entity = dialog.entity
    if isinstance(entity, PrivateChat):
        return True
    elif isinstance(entity, Channel):
        # 兼容新旧版本的判断方式
        try:
            return entity.flags.private
        except AttributeError:
            return (entity.flags & 1) != 0
    elif isinstance(entity, Chat):
        return not entity.username
    return False

async def main():
    # 替换为你的api_id和api_hash
    client = TelegramClient('my_session', 12345, 'abcdefghijklmnopqrstuvwxyz')
    await client.start()
    
    # 遍历对话并输出私密状态
    async for dialog in client.iter_dialogs():
        is_private = await is_dialog_private(dialog)
        print(f"对话名称:{dialog.title} | 是否私密:{'是' if is_private else '否'}")

if __name__ == '__main__':
    import asyncio
    asyncio.run(main())
  • 注意事项:
    • 建议使用较新版本的Telethon,旧版本部分属性的访问逻辑可能存在差异。
    • 频道无公开用户名不等于绝对私密(比如未设置用户名的公开频道),因此flags.private是更准确的判断依据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 20:32:20