You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

python-telegram-bot v21.x.x版本实现Telegram机器人下载图片的问题求助

python-telegram-bot v21.x.x版本实现Telegram机器人下载图片的问题求助

我现在想搭建一个Telegram机器人,用来接收并保存发给它的图片。之前手动用requests试过,但更想用python-telegram-bot库来做。不过麻烦的是,网上大部分示例都是针对v20以下版本的,而官方文档只讲v20以上的内容,而且没有详细覆盖这个场景,导致我写不出能正常运行的代码。我不想降级库版本,就是想搞懂当前v21.x.x版本的写法

当前的核心代码

from dotenv import load_dotenv
import os
import asyncio
import telegram
import logging  # 补充原代码遗漏的logging导入
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] 取分辨率最高的图片版本
    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) # 这里是过滤器设置
    application.add_handler(downloader_handler)

    #file_handler = MessageHandler(filters.Document.JPG, downloader)   # 另一次尝试,也试过Document.ALL 
    #application.add_handler(file_handler)

    application.run_polling()

我目前遇到的问题

  • 当过滤器设为filters.Document.ALL时,发送PDF文件好像能进入下载函数,但有时候找不到保存的PDF,不知道存到哪个路径去了
  • 发送JPG图片时,完全不会触发下载函数(连调试日志/打印语句都没输出)
  • 尝试过其他帖子里的代码片段,但大多是旧版本的写法,一堆报错

我看过一些相关的技术帖子,其中有个专门针对v20语法的示例片段,对PDF文件有效(但有上面说的奇怪问题),但对图片完全没用,所以我觉得问题可能出在过滤器上。

我试过的过滤器

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

我的疑问

  • 针对JPG图片,应该用什么正确的过滤器?
  • 还有其他我可能忽略的问题吗?

真心求各位帮忙,我觉得这个功能不该这么难实现...而且我肯定不是唯一一个在库大改版后遇到这个问题的人。提前谢谢大家,祝各位编码愉快 :)

备注:内容来源于stack exchange,提问作者Sigger

火山引擎 最新活动