Aiogram3无法发送音频文件问题求助
解决Aiogram机器人发送MP3链接音频的错误问题
错误原因
你遇到的Can't instantiate abstract class InputFile with abstract method read异常,是因为InputFile是抽象基类,不能直接实例化使用,需要采用正确的文件传递方式。
解决方案
以下是三种无需本地保存文件的有效解决方法:
方法一:直接传递BytesIO对象并指定文件名
send_audio方法可直接接收实现了read方法的IO对象(如BytesIO),只需补充指定文件名让Telegram识别音频格式:
import requests from io import BytesIO from aiogram import Bot, Dispatcher from aiogram.types import Message from config_weather import TOKEN_BOT bot = Bot(token=TOKEN_BOT) dp = Dispatcher() @dp.message(lambda link: '.mp3' in link.text) async def process_mp3_link(message: Message): try: mp3_file = BytesIO(requests.get(message.text).content) # 直接传入BytesIO,指定文件名 await bot.send_audio(chat_id=message.chat.id, audio=mp3_file, filename="audio.mp3") except Exception as ex: await message.answer('Error!') print(ex) if __name__ == '__main__': dp.run_polling(bot)
方法二:使用URLInputFile直接传入链接(推荐)
无需下载音频文件,直接让Telegram服务器拉取MP3链接,效率更高:
from aiogram import Bot, Dispatcher from aiogram.types import Message from aiogram.types.input_file import URLInputFile from config_weather import TOKEN_BOT bot = Bot(token=TOKEN_BOT) dp = Dispatcher() @dp.message(lambda link: '.mp3' in link.text) async def process_mp3_link(message: Message): try: # 直接用URLInputFile包装链接 await bot.send_audio(chat_id=message.chat.id, audio=URLInputFile(message.text)) except Exception as ex: await message.answer('Error!') print(ex) if __name__ == '__main__': dp.run_polling(bot)
方法三:给BytesIO添加文件名后使用InputFile
如果坚持使用InputFile,需要为BytesIO对象设置name属性,满足InputFile的实例化要求:
import requests from io import BytesIO from aiogram import Bot, Dispatcher from aiogram.types import Message from aiogram.types.input_file import InputFile from config_weather import TOKEN_BOT bot = Bot(token=TOKEN_BOT) dp = Dispatcher() @dp.message(lambda link: '.mp3' in link.text) async def process_mp3_link(message: Message): try: mp3_file = BytesIO(requests.get(message.text).content) # 为BytesIO设置文件名 mp3_file.name = "audio.mp3" await bot.send_audio(chat_id=message.chat.id, audio=InputFile(mp3_file)) except Exception as ex: await message.answer('Error!') print(ex) if __name__ == '__main__': dp.run_polling(bot)
内容的提问来源于stack exchange,提问作者Elliot DeWitt
相关产品推荐
相关产品推荐

