You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在aiogram中使用telethon批量发送文件失败问题求助

问题:Telethon结合Aiogram多次发送文件仅成功第一个

在Aiogram框架中使用Telethon发送文件时,多次发送"send_file"命令请求发送两个及以上文件,Telethon客户端仅会发送第一个文件。

原问题代码

main.py

@dp.message(F.text == 'send_file')
async def send_file(message: Message):
    await message.answer('sending file...')

    async with client:
        await client.send_file(message.from_user.id, "vid.mp4")

file_sender.py

from telethon.sync import TelegramClient, events
import asyncio

api_id = 123
api_hash = "1234"

client = TelegramClient('name', api_id, api_hash)

另一种尝试写法:

main.py

@dp.message(F.text == 'send_file')
async def send_file(message: Message):
    await message.answer('sending file...')
    await send_file(message.from_user.id)

file_sender.py

async def send_file(user_id):
    async with client:
        await client.send_file(user_id, "vid.mp4")

问题原因

每次处理请求时都通过async with client:启动并关闭Telethon客户端,当多个请求同时到来时,第一个请求的客户端还未完成关闭,第二个请求就尝试重新启动同一个客户端实例,导致Telethon内部出现冲突,后续请求的文件发送操作被阻塞或失败。

解决方案

只需要启动Telethon客户端一次,后续请求直接复用已连接的客户端,无需每次都通过async with重新初始化。

修改后的代码

file_sender.py

from telethon import TelegramClient
import asyncio

api_id = 123
api_hash = "1234"

client = TelegramClient('name', api_id, api_hash)

# 提前启动客户端,在Aiogram Bot启动时完成连接
async def start_telethon_client():
    await client.start()

main.py

from aiogram import Bot, Dispatcher, F
from aiogram.types import Message
from file_sender import client, start_telethon_client
import asyncio

# 初始化Aiogram Bot
bot = Bot(token="YOUR_BOT_TOKEN")
dp = Dispatcher()

@dp.message(F.text == 'send_file')
async def send_file(message: Message):
    await message.answer('sending file...')
    # 直接使用已启动的客户端发送文件
    await client.send_file(message.from_user.id, "vid.mp4")

async def main():
    # 先启动Telethon客户端
    await start_telethon_client()
    # 启动Aiogram Bot
    await dp.start_polling(bot)

if __name__ == "__main__":
    asyncio.run(main())

补充说明

  • 确保Telethon客户端是单例实例,整个应用生命周期内只启动一次。
  • 如果需要处理客户端断开重连,可以在代码中添加重连逻辑,但一般情况下保持长连接即可满足需求。

内容的提问来源于stack exchange,提问作者madjetmax

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 09:11:00