繁体   English   中英

无法使用 Python 电报机器人将文件保存在自定义路径目录中

[英]Not able to save the file in custom path directory using Python Telegram bot

我正在使用 Telegram 机器人下载文件,我当前的代码如下所示:

def file_handler(Update, context: CallbackContext):
    file = context.bot.getFile(Update.message.document.file_id)
    print("file_id: " + str(Update.message.document.file_id))
    file.download(custom_path='C:/Users/User/Desktop/python/projects/Telegram-Database/files')

def main():
    updater = Updater(token, use_context=True)
    dispatcher = updater.dispatcher
    dispatcher.add_handler(MessageHandler(Filters.document, file_handler))
    updater.start_polling()
    updater.idle()

if __name__ == '__main__':
    main()

当我这样做时:

file.download()

它下载当前目录中的文件,但我想下载文件夹中的所有文件。 所以我在这里查看了文档: https://python-telegram-bot.readthedocs.io/en/stable/telegram.file.html ,实际上我可以设置自定义路径来下载该文件夹中的文件。 但是,当我使用当前代码时,出现权限错误:

    with open(filename, 'wb') as fobj:
PermissionError: [Errno 13] Permission denied: 'C:/Users/User/Desktop/python/projects/Telegram-Database/files'

我不确定为什么。 我尝试重新创建文件夹并重新启动程序,但我总是遇到同样的错误。 我在 Telegram 机器人中查找了这个特定的错误,但没有显示任何内容。 你能帮忙吗?

解释

您不能将文件夹视为文件, download方法采用文件的路径。 如文档中所述:

下载此文件。 默认情况下,该文件以 Telegram 报告的原始文件名保存在当前工作目录中。 如果文件没有文件名,则文件 ID 将用作文件名。 如果提供了custom_path ,它将被保存到该路径。 如果定义了 out,文件内容将使用out.write方法保存到 object 中。

代码

代码变更

您可以使用更改以下代码:

custom_path='C:/Users/User/Desktop/python/projects/Telegram-Database/files'

custom_path='C:/Users/User/Desktop/python/projects/Telegram-Database/files/file1.txt'

完整代码

def file_handler(Update, context: CallbackContext):
    file = context.bot.getFile(Update.message.document.file_id)
    print("file_id: " + str(Update.message.document.file_id))
    file.download(custom_path='C:/Users/User/Desktop/python/projects/Telegram-Database/files/file1.txt')

def main():
    updater = Updater(token, use_context=True)
    dispatcher = updater.dispatcher
    dispatcher.add_handler(MessageHandler(Filters.document, file_handler))
    updater.start_polling()
    updater.idle()

if __name__ == '__main__':
    main()

暂无
暂无

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

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