使用telegram机器人(python-telegram-bot)下载文件(特别是图片)

0 投票
1 回答
38 浏览
提问于 2025-04-11 22:58

目标: 我想设置一个Telegram机器人,它可以下载发送给它的图片。

在用requests库进行了一些手动尝试后,我更想使用python-telegram-bot这个库。不过不幸的是,大多数在文档之外的例子都是针对版本低于20的,而官方文档则完全是为版本高于20编写的,遗憾的是没有详细讲解到让我能写出可用代码的程度。我不想降级我的库版本,我想理解当前的版本(v21.x.x)。

我目前的代码看起来是这样的:

from dotenv import load_dotenv
import os
import asyncio
import telegram
from telegram import Update
from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes, ApplicationBuilder
from telegram.ext import InlineQueryHandler, ExtBot

load_dotenv()
TOKEN = os.getenv('TOKEN')


### **Downloader**
async def downloader(update: Update, context: ContextTypes.DEFAULT_TYPE):
    logging.DEBUG("in downloader app!")
    new_file = await update.message.effective_attachment[-1].get_file() # [-1] for largest size of photo
    file = await new_file.download_to_drive()
    # file2 = await ExtBot.get_file()
    return file

### **Main**
if __name__ == '__main__':
    application = ApplicationBuilder().token(TOKEN).build()

    downloader_handler = MessageHandler(filters.Document.IMAGE, downloader) #**here are the filters**;
    application.add_handler(downloader_handler)

    #file_handler = MessageHandler(filters.Document.JPG, downloader)   # another try, also Document.ALL 
    #application.add_handler(file_handler)

    application.run_polling()

到目前为止我的观察:

  • 当我设置过滤器为Document.ALL并发送一个pdf文件时,它似乎进入了下载器,但我并不总能获取到下载的pdf(有时它似乎保存到了我不知道的路径)
  • 当我发送一张图片(jpg)时,下载器似乎从未被进入(没有调试或打印语句)
  • 当我尝试用其他帖子中的代码片段替换代码时,我遇到了很多错误,因为大多数代码似乎依赖于版本大于20的写法。

对我来说,这似乎不应该这么麻烦……


任何帮助都将非常感激。我觉得在这个库进行大规模改版后,我不会是唯一一个遇到这个问题的人。提前感谢大家,祝大家编码愉快 :)

我尝试了与此相关的各种StackOverflow帖子,从我所读到的内容来看,这个示例代码,专门为v20语法设计应该可以工作。对于pdf文件是可以的(见上面奇怪的行为),但对于图片却不行,这让我觉得可能是与过滤器有关的问题。

我尝试过的过滤器

  • filters.Document.IMAGE
  • filters.Document.JPG
  • filters.Document.ALL

问题

  • 哪个过滤器适合jpg文件?
  • 我可能还遗漏了什么?

1 个回答

暂无回答

撰写回答