繁体   English   中英

使用 Python-Telegram-bot 下载文件

[英]Download files using Python-Telegram-bot

我试图使用 python 脚本下载用户通过电报应用程序发送的文件,我正在使用 Python-telegram-bot 库,我无法下载该文件,下面是我的代码。

from telegram.ext import ApplicationBuilder, MessageHandler, filters

BOT_TOKEN = '...'

# Enable logging
logging.basicConfig(
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
)
logger = logging.getLogger(__name__)

def downloader(bot, update, context):
    logger.info(update.message.document.file_name)
    logger.info(update.message.document.file_id)
    context.bot.get_file(update.message.document).download()

    # writing to a custom file
    with open("custom/file.doc", 'wb') as f:
        context.bot.get_file(update.message.document).download(out=f)

application = ApplicationBuilder().token(BOT_TOKEN).build()

# on different commands - answer in Telegram
application.add_handler(MessageHandler(filters.Document.ALL, downloader))

# Run the bot until the user presses Ctrl-C
application.run_polling()

处理程序回调正好接受 2 个位置 arguments,而不是三个。 有关详细信息,请参阅MessageHandler的文档。

此外,请记住,在最近的版本中, telegram.File的方法已被重命名。 特别是,现在有File.download_to_memoryFile.download_to_drive ,不再有File.download了。


免责声明:我目前是python-telegram-bot的维护者

def start_function(update, context): update.message.reply_text("你好。我是 AskPython Bot。")

def help_function(update, context): update.message.reply_text( """ 可用命令:

/start : Starts up the bot
/help : Help topics
/about : About text
/askpython : Go to AskPython Offical Website
/custom : Other custom commands 

"""
)

def about_function(update, context): update.message.reply_text("我是一个机器人,也是一个 Python 精灵。")

def ask_python_function(update, context): update.message.reply_text("AskPython Website: https://www.askpython.com/" )

def custom_function(更新,上下文):update.message.reply_text(

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM