如何用Telethon获取Telegram中非联系人的最新聊天列表
用Telethon获取非联系人的最近聊天列表
要实现这个需求,核心思路是先获取你的所有联系人ID,再拉取最近聊天列表,最后过滤掉属于联系人的聊天对象。以下是具体实现步骤和代码:
实现步骤
- 初始化Telethon客户端并完成登录验证
- 获取所有联系人的ID集合,用于快速比对
- 拉取最近的聊天对话框列表
- 过滤出属于非联系人用户的聊天,并提取关键信息
完整代码示例
from telethon import TelegramClient from telethon.tl.types import PeerUser from telethon.tl.functions.messages import GetDialogsRequest from telethon.tl.types import InputPeerEmpty # 替换为你的Telegram API信息 api_id = 123456 api_hash = "your_api_hash_here" phone_number = "+1234567890" # 初始化客户端 client = TelegramClient("session_name", api_id, api_hash) async def fetch_non_contact_recent_chats(): await client.start(phone_number) # 获取所有联系人ID,存入集合用于快速查找 contact_list = await client.get_contacts() contact_ids = {contact.id for contact in contact_list} # 拉取最近的聊天对话框(limit可按需调整) dialogs_response = await client(GetDialogsRequest( offset_date=None, offset_id=0, offset_peer=InputPeerEmpty(), limit=100, hash=0 )) non_contact_chats = [] for dialog in dialogs_response.dialogs: chat_peer = dialog.peer # 仅处理用户类型的聊天,且排除联系人 if isinstance(chat_peer, PeerUser) and chat_peer.id not in contact_ids: user_info = await client.get_entity(chat_peer) # 提取需要的信息,可根据需求增减字段 non_contact_chats.append({ "user_id": user_info.id, "username": user_info.username, "full_name": f"{user_info.first_name or ''} {user_info.last_name or ''}".strip(), "last_chat_time": dialog.date }) return non_contact_chats # 执行并输出结果 if __name__ == "__main__": with client: result = client.loop.run_until_complete(fetch_non_contact_recent_chats()) for chat in result: print(f"用户ID: {chat['user_id']} | 用户名: @{chat['username'] or '无'} | 昵称: {chat['full_name']} | 最后聊天: {chat['last_chat_time']}")
关键说明
- API信息:需要先在Telegram开发者平台申请
api_id和api_hash - 过滤逻辑:通过
isinstance(chat_peer, PeerUser)确保只处理个人聊天,排除群组、频道;用集合contact_ids快速判断是否为联系人,提升效率 - 扩展过滤:如果需要排除机器人,可在过滤条件中添加
and not user_info.bot - limit参数:控制拉取的最近聊天数量,可根据需求调整为更大的值
内容的提问来源于stack exchange,提问作者karoakhgar82
相关产品推荐
相关产品推荐

