如何使用Telethon获取聊天文件夹?技术求助
如何用Telethon获取聊天文件夹
要获取Telegram的聊天文件夹(即对话过滤器),你可以直接调用Telethon封装的底层API请求GetDialogFiltersRequest,以下是具体实现步骤和代码示例:
实现步骤
- 确保已完成Telethon客户端的初始化与登录认证
- 导入对应的请求类
GetDialogFiltersRequest - 调用请求获取所有聊天文件夹数据
- 解析返回的结果对象,提取文件夹的标题、包含的对话ID等信息
完整代码示例
from telethon import TelegramClient from telethon.tl.functions.messages import GetDialogFiltersRequest # 替换为你的API凭证和会话文件名 api_id = 你的API_ID api_hash = '你的API_HASH' session_name = 'telethon_session' async def fetch_chat_folders(): async with TelegramClient(session_name, api_id, api_hash) as client: # 获取所有聊天文件夹 chat_folders = await client(GetDialogFiltersRequest()) # 遍历输出每个文件夹的详细信息 for index, folder in enumerate(chat_folders, start=1): print(f"文件夹 {index}") print(f" 标题: {folder.title}") print(f" 表情图标: {folder.emoticon}") print(f" 包含的对话: {folder.include_peers}") print(f" 排除的对话: {folder.exclude_peers}") print("-" * 40) # 执行异步函数 import asyncio asyncio.run(fetch_chat_folders())
关键字段说明
folder.title: 聊天文件夹的显示名称folder.emoticon: 文件夹对应的表情图标folder.include_peers: 该文件夹包含的所有对话/聊天的ID集合folder.exclude_peers: 被排除在该文件夹外的对话ID集合folder.pinned_peers: 文件夹内设置为固定的对话ID
如果使用同步客户端,只需去掉await关键字直接调用client(GetDialogFiltersRequest())即可。
内容的提问来源于stack exchange,提问作者Shards-7
相关产品推荐
相关产品推荐

