如何通过Telethon根据用户ID获取其加入的所有群组/频道?
获取目标用户已加入的群组/频道(Telethon实现)
权限说明
Telegram的隐私机制限制,你无法获取其他用户的私密群组/频道,仅能获取两类内容:
- 你与目标用户共同加入的群组/频道
- 目标用户设置为公开可见的频道
1. 获取共同群组/频道
遍历你的所有对话,检查每个群组/频道的参与者是否包含目标用户ID:
from telethon import TelegramClient from telethon.tl.types import Channel, Chat async def get_common_chats(client, target_user_id): common_chats = [] # 遍历自身所有对话 async for dialog in client.iter_dialogs(): chat = dialog.entity # 筛选群组和频道(排除私人聊天) if isinstance(chat, (Channel, Chat)): try: # 检查目标用户是否在当前对话中 participant = await client.get_participants(chat, ids=target_user_id) if participant: common_chats.append({ 'id': chat.id, 'title': chat.title, 'type': '频道' if isinstance(chat, Channel) else '群组' }) except: # 无权限查看成员的对话直接跳过 continue return common_chats # 调用示例(需先初始化并登录client) # async with client: # common_groups = await get_common_chats(client, 123456789) # print(common_groups)
2. 获取目标用户的公开频道
方法A:通过用户绑定信息获取
如果用户有绑定公开频道,可通过完整用户信息提取:
from telethon.tl.functions.users import GetFullUserRequest async def get_linked_public_channels(client, target_user_id): public_channels = [] full_user_info = await client(GetFullUserRequest(target_user_id)) # 提取绑定的频道ID linked_chat_id = full_user_info.full_user.linked_chat_id if linked_chat_id: try: channel = await client.get_entity(linked_chat_id) if isinstance(channel, Channel): public_channels.append({ 'id': channel.id, 'title': channel.title, 'username': channel.username }) except: pass return public_channels
方法B:全局搜索公开频道
通过用户名全局搜索关联的公开频道:
from telethon.tl.functions.messages import SearchGlobalRequest from telethon.tl.types import Channel async def search_user_public_channels(client, target_username): public_channels = [] search_result = await client(SearchGlobalRequest(q=target_username, limit=50)) for item in search_result.results: if hasattr(item, 'peer') and isinstance(item.peer, Channel): channel = item.peer public_channels.append({ 'id': channel.id, 'title': channel.title, 'username': channel.username }) # 去重处理 return list({chan['id']: chan for chan in public_channels}.values())
注意事项
- 需确保Telethon客户端已完成初始化(配置api_id、api_hash并完成登录流程)
- 私密群组/频道因权限限制无法获取,代码会自动跳过无权限的对话
- 公开频道的获取依赖于频道是否开启公开可见及可搜索设置
内容的提问来源于stack exchange,提问作者daji ren
相关产品推荐
相关产品推荐

