Violet Asked:2020-01-17 17:19:34 +0000 UTC2020-01-17 17:19:34 +0000 UTC 2020-01-17 17:19:34 +0000 UTC 保存用户发送给机器人的图像 772 需要保存用户发送给机器人的图像。据我了解,您需要获取 file_id 并使用 getFile,但我无法弄清楚( 你能告诉我如何实施吗? 最近熟悉的pyTelegramBotAPI telegram-bot 3 个回答 Voted Artur 2020-01-07T02:25:20Z2020-01-07T02:25:20Z 我试过上面的代码,但它不适用于照片。修改代码得到以下结果。 file_info = bot.get_file(message.photo[0].file_id) downloaded_file = bot.download_file(file_info.file_path) src = filepath + message.photo[0].file_id with open(src, 'wb') as new_file: new_file.write(downloaded_file) Best Answer Violet 2020-01-17T19:10:01Z2020-01-17T19:10:01Z @bot.message_handler(content_types=['document']) def handle_docs_photo(message): try: chat_id = message.chat.id file_info = bot.get_file(message.document.file_id) downloaded_file = bot.download_file(file_info.file_path) src = 'C:/Python/Project/tg_bot/files/received/' + message.document.file_name; with open(src, 'wb') as new_file: new_file.write(downloaded_file) bot.reply_to(message, "Пожалуй, я сохраню это") except Exception as e: bot.reply_to(message, e) 接受所有类型的文件,保存到指定目录,机器人以引用上一条消息和标题“也许我会保存这个”的形式给出答案 更新: 如果有几个文件,包括。不同种类: @bot.message_handler(content_types=['photo', 'document']) def handler_file(message): from pathlib import Path Path(f'files/{message.chat.id}/').mkdir(parents=True, exist_ok=True) if message.content_type == 'photo': file_info = bot.get_file(message.photo[len(message.photo) - 1].file_id) downloaded_file = bot.download_file(file_info.file_path) src = f'files/{message.chat.id}/' + file_info.file_path.replace('photos/', '') with open(src, 'wb') as new_file: new_file.write(downloaded_file) elif message.content_type == 'document': file_info = bot.get_file(message.document.file_id) downloaded_file = bot.download_file(file_info.file_path) src = f'files/{message.chat.id}/' + message.document.file_name with open(src, 'wb') as new_file: new_file.write(downloaded_file) Дмитрий 2020-04-25T13:55:42Z2020-04-25T13:55:42Z 也许有人需要它。 @bot.message_handler(content_types=['photo']) def handle_docs_photo(message): try: file_info = bot.get_file(message.photo[len(message.photo)-1].file_id) downloaded_file = bot.download_file(file_info.file_path) src='/mnt/files/tmp/'+file_info.file_path; with open(src, 'wb') as new_file: new_file.write(downloaded_file) bot.reply_to(message,"Фото добавлено") except Exception as e: bot.reply_to(message,e )
我试过上面的代码,但它不适用于照片。修改代码得到以下结果。
接受所有类型的文件,保存到指定目录,机器人以引用上一条消息和标题“也许我会保存这个”的形式给出答案
更新:
如果有几个文件,包括。不同种类:
也许有人需要它。