Telegram bot无法发送音频文件 代码运行异常问题求助
问题原因及解决方法
1. 代码基础错误修复
你提供的代码里存在3个直接导致发送失败的低级错误:
- 参数传递错误:
reply_audio方法第一个位置参数就是音频对象,你把说明文字放在了第一个参数的位置,音频参数反而放到了后面,顺序完全颠倒 - 文件打开模式错误:读取二进制的音频文件需要指定
rb模式,你没有指定模式会默认用文本模式读取,导致文件解析失败 - 主函数调用缩进错误:你把
main()的调用写在了def main()函数内部,永远不会被执行到,需要取消该行的缩进顶格放置
修正后的yes_command写法参考:
def yes_command(update, context): time.sleep(5) update.message.reply_text("Let's test here, press play to listen.") time.sleep(3) # 用with上下文自动关闭文件,指定rb读取二进制 with open("C:/Users/0836/Documents/omsk/bot2/song/bootgong.mp3", "rb") as f: # 正确传递参数:第一个传音频对象,caption参数放说明文字 update.message.reply_audio(f, caption="press play")
修正后的主函数结尾写法参考:
def main(): updater = Updater(keys.API_KEY, use_context=True) dp = updater.dispatcher dp.add_handler(CommandHandler("start", start_command)) dp.add_handler(CommandHandler("play", play_command)) dp.add_handler(CommandHandler("no", no_command)) dp.add_handler(CommandHandler("yes", yes_command)) dp.add_handler(MessageHandler(Filters.text, handle_message)) dp.add_handler(MessageHandler(Filters.photo, photo_command)) updater.start_polling() updater.idle() # 顶格调用主函数 if __name__ == '__main__': main()
2. 用Telegram文件ID发送的操作方法
提前上传音频到TG服务器拿ID发送的方式更稳定,不需要每次读取本地文件,操作步骤如下:
- 手动将你要发送的音频文件发送给你的bot
- 新增一个临时消息处理器获取音频ID,代码如下:
# 新增handler函数 def get_file_id(update, context): if update.message.audio: audio_id = update.message.audio.file_id update.message.reply_text(f"当前音频ID:{audio_id}") print(f"音频ID已输出:{audio_id}") # 在main函数的handler注册部分新增一行 dp.add_handler(MessageHandler(Filters.audio, get_file_id))
- 运行bot后给bot发音频,就能拿到对应的ID字符串,之后直接传ID给
reply_audio即可,参考写法:
update.message.reply_audio("你拿到的音频ID字符串", caption="press play")
3. 额外注意事项
- Telegram bot发送单文件大小上限为50MB,超过该大小的文件无法发送
- 请确认本地音频文件路径正确,程序对该路径有读取权限
- 确认你的bot API_KEY正确,且账号没有被Telegram限制功能
内容的提问来源于stack exchange,提问作者sade mae
相关产品推荐
相关产品推荐

