使用python-bale-bot在Bale机器人中无法上传音频文件求助
问题
在类Telegram的即时通讯工具Bale中开发可发送音频文件的机器人,使用python-bale-bot库调用Bale Messenger API。尝试读取MP3文件并传入对应方法时触发序列化错误。
相关代码:
"""keyboard handler""" @client.listen(EventType.CALLBACK) async def when_receive_callback(callback: CallbackQuery): if callback.data == "audio": audio_file = open("/path_to/audio_file.mp3","rb") audio = audio_file.read() await callback.message.reply_document(audio)
触发的错误信息:
error on_callback Can not serialize value type: <class 'int'> headers: {} value: 800646076
解决思路
- 不要直接传入文件读取后的字节流,
reply_document方法需要的是文件对象而非字节数据。删除audio = audio_file.read(),直接传入打开的文件对象:await callback.message.reply_document(audio_file) - 用
with语句处理文件,自动关闭资源避免泄漏:if callback.data == "audio": with open("/path_to/audio_file.mp3","rb") as audio_file: await callback.message.reply_document(audio_file) - 确认
python-bale-bot的参数要求,部分库支持直接传入文件路径字符串,可简化代码:await callback.message.reply_document("/path_to/audio_file.mp3") - 错误中的整数800646076是字节流的长度,说明库误将字节数据当成了需要序列化的整数参数,核心原因是参数类型不匹配,只要传对参数类型即可解决。
内容的提问来源于stack exchange,提问作者okaeiz
相关产品推荐
相关产品推荐

