Telethon中如何区分用户、群组与频道的实体类型?
问题:如何用Telethon准确区分@标识对应的用户、群组和频道?
我有多个@格式的账号标识(如@xyz),想用Telethon判断它们属于用户、群组还是频道,写了如下代码:
from telethon.sync import TelegramClient from telethon.tl.types import Channel, Chat, User async def check_handle(client,handle): username = handle try: entity = await client.get_entity(username) if entity: if isinstance(entity, User): # Check if it's a User (private chat) print(f"{username} is a private chat.") elif isinstance(entity, Channel): # Check if it's a Channel print(f"{username} is a channel.") elif isinstance(entity, Chat): # Check if it's a Chat (group) print(f"{username} is a group.") else: print(f"Unable to determine the type of {username}.") except ValueError as e: print(f"Error: {e}") # 调用示例 await check_handle(client,'@aim4pg')
运行后发现@aim4pg被识别为频道,但实际它是一个有多名成员的群组。测试后发现,群组和频道都会返回Channel实体,只有用户会返回User实体。请问怎么准确判断标识对应的类型?
解决方法
Telethon中,Channel实体其实包含两种类型:超级群组和频道,而Chat仅对应未升级的旧版普通群组。要准确区分,需要通过Channel实体的两个核心属性判断:
broadcast:值为True时,对应频道(仅管理员可发消息的广播型载体)megagroup:值为True时,对应超级群组(支持大量成员、管理员精细化管理的群组)
修改后的代码如下:
from telethon.sync import TelegramClient from telethon.tl.types import Channel, Chat, User async def check_handle(client, handle): username = handle try: entity = await client.get_entity(username) if isinstance(entity, User): print(f"{username} 是普通用户") elif isinstance(entity, Channel): if entity.broadcast: print(f"{username} 是频道") elif entity.megagroup: print(f"{username} 是超级群组") else: print(f"{username} 是未知类型的Channel实体") elif isinstance(entity, Chat): print(f"{username} 是旧版普通群组") else: print(f"无法识别 {username} 的类型") except ValueError as e: print(f"错误:{e}") # 调用示例 await check_handle(client, '@aim4pg')
逻辑说明
- 优先判断
User:直接识别为普通用户 - 若为
Channel:- 通过
broadcast属性识别频道 - 通过
megagroup属性识别超级群组(即你遇到的成员较多的群组类型)
- 通过
- 若为
Chat:对应未升级的旧版普通群组,这类群组目前已较少见 - 兜底分支:处理极少数未知类型的实体
内容的提问来源于stack exchange,提问作者Anon
相关产品推荐
相关产品推荐

