如何使用Telethon获取普通聊天(PeerChat)的管理员列表
问题原因
TypeError: Cannot cast InputPeerChat to any kind of InputChannel.
该报错是因为你使用的GetParticipantsRequest属于仅适用于频道、超级群(对应InputChannel类型实体)的底层API,无法直接用于未升级的普通基础群(对应InputPeerChat类型实体)。
全场景兼容解决方案
方案1:使用Telethon封装的高层API(推荐)
Telethon内置的client.get_participants方法已经自动适配了所有聊天类型,不需要手动判断群类型,只需同时兼容普通群和超级群的管理员类型即可,示例代码如下:
from telethon.tl.types import ( ChannelParticipantCreator, ChannelParticipantAdmin, ChatParticipantCreator, ChatParticipantAdmin ) # 普通群、超级群、频道均可直接调用 participants = await client.get_participants(chat) for p in participants: participant_info = p.participant if type(participant_info) in [ ChannelParticipantCreator, ChannelParticipantAdmin, ChatParticipantCreator, ChatParticipantAdmin ]: print(p)
方案2:手动判断实体类型调用对应底层API
如果你需要使用底层API做自定义逻辑,可以先判断聊天实体类型,分别调用对应接口:
from telethon.tl.functions.channels import GetParticipantsRequest from telethon.tl.functions.messages import GetFullChatRequest from telethon.tl.types import ( Channel, Chat, ChannelParticipantsSearch, ChannelParticipantCreator, ChannelParticipantAdmin, ChatParticipantCreator, ChatParticipantAdmin ) chat_entity = await client.get_entity(chat) if isinstance(chat_entity, Channel): # 超级群/频道走原有逻辑 parts = await client(GetParticipantsRequest( chat_entity, ChannelParticipantsSearch(''), 0, 1000, hash=0 )) for i in parts.participants: if type(i) in [ChannelParticipantCreator, ChannelParticipantAdmin]: print(i) elif isinstance(chat_entity, Chat): # 普通群调用GetFullChatRequest获取参与者 full_chat = await client(GetFullChatRequest(chat_entity.id)) for i in full_chat.full_chat.participants.participants: if type(i) in [ChatParticipantCreator, ChatParticipantAdmin]: print(i)
注意事项
- 普通基础群的成员上限为200人,无需分页即可拉取全部成员
- 普通群的群主、管理员类型为
ChatParticipantCreator、ChatParticipantAdmin,和超级群的对应类型不同,判断时不要遗漏
内容的提问来源于stack exchange,提问作者Alexey Posikera
相关产品推荐
相关产品推荐

