使用Python-Telegram-bot实现文件下载的问题及优化需求
Python-Telegram-Bot 多文件下载问题修复
问题剖析
你当前的可运行代码存在三个核心问题:
- 触发条件受限:看似仅支持带斜杠
/的命令触发下载,实际是因为使用filters.ALL会匹配所有消息类型,当发送非文档消息时,代码因访问update.message.document失败而崩溃,导致bot无法响应正常的文档发送请求; - 不支持多文件批量下载:仅处理单个文档,用户一次性发送多个文件时,只会下载第一个;
- 缺乏错误处理:单个文件下载失败会导致整个逻辑中断,且无反馈。
修复后的代码
import logging from telegram.ext import ApplicationBuilder, MessageHandler, filters, ContextTypes from telegram import Document BOT_TOKEN = '你的Bot令牌' # 配置日志 logging.basicConfig( format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO ) logger = logging.getLogger(__name__) async def downloader(update, context: ContextTypes.DEFAULT_TYPE): # 获取消息中的所有附件 attachments = update.message.effective_attachment # 统一处理单个文件和多文件的格式 if isinstance(attachments, Document): attachments = [attachments] saved_files = [] for doc in attachments: try: file_name = doc.file_name # 获取文件资源并下载到本地 file_obj = await doc.get_file() await file_obj.download_to_drive(file_name) saved_files.append(file_name) logger.info(f"文件 {file_name} 保存成功") except Exception as e: error_msg = f"文件 {doc.file_name} 保存失败: {str(e)}" logger.error(error_msg) await update.message.reply_text(error_msg) # 给用户发送保存结果反馈 if saved_files: await update.message.reply_text(f"已成功保存以下文件:\n{chr(10).join(saved_files)}") else: await update.message.reply_text("未找到可保存的文档") if __name__ == "__main__": # 构建bot应用 application = ApplicationBuilder().token(BOT_TOKEN).build() # 仅监听文档类型消息,避免无效消息触发报错 application.add_handler(MessageHandler(filters.Document.ALL, downloader)) # 启动bot application.run_polling()
关键修改说明
- 修正消息过滤规则:用
filters.Document.ALL替代filters.ALL,确保只有用户发送文档(单个或多个)时才触发下载逻辑,彻底解决非文档消息导致的bot崩溃问题,无需斜杠命令即可触发; - 多文件支持:通过判断
effective_attachment的类型,将单个文档转为列表格式,遍历处理所有附件,实现批量下载; - 增加异常捕获:单个文件下载失败时,会记录日志并给用户反馈,不影响其他文件的处理;
- 优化结构:添加
if __name__ == "__main__"确保脚本作为主程序运行时才初始化bot,符合Python规范。
使用方法
直接向bot发送单个或多个文档,bot会自动下载所有文件到当前运行目录,并回复保存结果。
内容的提问来源于stack exchange,提问作者Bhuvan Kumar
相关产品推荐
相关产品推荐

