如何在AWS Lambda中直接将Telegram语音消息保存到S3?
解决Telegram语音消息直接上传AWS S3(Lambda环境)的问题
错误原因分析
- 第一个错误:
s3.upload_file()要求传入本地文件路径字符串,但你传入的是Telegram Bot API返回的File对象,类型不匹配,所以抛出ValueError。 - 第二个错误:
BytesIO()需要传入字节类对象,直接传入File对象不符合要求,导致TypeError。
正确实现代码
Lambda环境下无需落地磁盘,直接通过字节流上传即可,核心是先把Telegram语音文件下载为字节数据,再用upload_fileobj上传:
from io import BytesIO import boto3 from telegram import Update from telegram.ext import ContextTypes async def audio_handler(update: Update, context: ContextTypes.DEFAULT_TYPE): message = update.effective_message # 获取Telegram文件对象 file = await message.voice.get_file() # 下载文件为字节数据 file_bytes = await file.download_as_bytearray() # 初始化S3客户端 s3 = boto3.client('s3') # 将字节数据包装为可读取的流对象,上传到S3 s3.upload_fileobj(BytesIO(file_bytes), Bucket='mybucket', Key='onelove.ogg')
关键说明
- 注意使用
await:Telegram Bot API的异步方法(get_file()、download_as_bytearray())需要配合async/await使用,确保函数定义为async。 download_as_bytearray():直接将文件内容下载为字节数组,避免写入本地磁盘,完美适配Lambda无持久化存储的环境。BytesIO(file_bytes):把字节数组包装成类文件对象,满足s3.upload_fileobj()对输入流的要求。
内容的提问来源于stack exchange,提问作者Sergio Lucero
相关产品推荐
相关产品推荐

