如何在现有Telethon代码中正确使用FastTelethonHelper的fast_download?
解决Telethon集成fast_download的异步适配问题
你的核心问题是现有代码用了同步版Telethon,但fast_download是异步函数必须用await调用,所以需要把整个代码切换到异步模式,以下是修改后的完整可运行代码:
import asyncio from telethon import TelegramClient from telethon.tl.functions.messages import GetDialogsRequest from telethon.tl.functions.channels import GetFullChannelRequest from FastTelethonhelper import fast_download from telethon.tl.types import InputPeerEmpty from tqdm import tqdm api_id = 你的api_id # 填入实际api_id api_hash = '你的api_hash' # 填入实际api_hash def callback(current, total): global pbar global prev_curr pbar.update(current - prev_curr) prev_curr = current async def download_media(group, cl, name): global pbar global prev_curr # 异步获取消息,必须加await messages = await cl.get_messages(group, limit=2000) start = 0 print(start) for i, message in enumerate(messages[start:]): prev_curr = 0 if message.video: print(f"\n{i + start} / {len(messages)} : {message.file.name}") pbar = tqdm(total=message.document.size, unit='B', unit_scale=True) # 替换原同步download_media为异步fast_download,加await await fast_download( client=cl, file=message.video, download_folder=f'./{name}/', progress_bar_function=callback ) pbar.close() async def main(): async with TelegramClient('name', api_id, api_hash) as client: result = await client(GetDialogsRequest( offset_date=None, offset_id=0, offset_peer=InputPeerEmpty(), limit=500, hash=0, )) title = 'channel_name' # 填入目标频道名称 channel = await client(GetFullChannelRequest(title)) await download_media(channel.full_chat, client, "directory_name") if __name__ == "__main__": asyncio.run(main())
关键修改说明:
- 切换异步客户端:移除
telethon.sync导入,改用标准telethon.TelegramClient,所有客户端方法(如get_messages、调用GetFullChannelRequest)都需要加await - 异步函数改造:把
download_media改成async def,主逻辑封装到main异步函数中,用asyncio.run启动 - fast_download调用:给
fast_download加await关键字,参数保持和你注释里的一致,注意file参数传入message.video是正确的 - 全局变量保留:暂时保留了你原来的全局
pbar和prev_curr,如果想优化可以改成函数内的非局部变量,避免全局污染
额外优化建议:
去掉全局变量,把pbar和prev_curr放到download_media函数内,避免多消息下载时的状态冲突:
async def download_media(group, cl, name): messages = await cl.get_messages(group, limit=2000) start = 0 print(start) for i, message in enumerate(messages[start:]): if message.video: print(f"\n{i + start} / {len(messages)} : {message.file.name}") prev_curr = 0 pbar = tqdm(total=message.document.size, unit='B', unit_scale=True) def callback(current, total): nonlocal prev_curr pbar.update(current - prev_curr) prev_curr = current await fast_download( client=cl, file=message.video, download_folder=f'./{name}/', progress_bar_function=callback ) pbar.close()
内容的提问来源于stack exchange,提问作者Kthway
相关产品推荐
相关产品推荐

