如何将电报机器人与Amazon S3连接?

时间:2020-02-16 13:52:21

标签: python amazon-web-services amazon-s3 telegram-bot python-telegram-bot

我有一个电报机器人,其功能最少。现在的任务是通过电讯聊天从用户上传文件,然后将其发送到S3。

我通过服务器使用Heroku。但是我需要一个可以存储文件(S3)的地方

这是bot.py代码

import config
import telebot
import checking
import s3upload

bot = telebot.TeleBot(config.TOKEN)

@bot.message_handler(content_types=['photo'])
def download_photo(message):
    bot.send_message(message.chat.id, 'please wait')
    image_file_path = save_image_from_message(message)
    s3upload.image_upload(image_file_path)
    bot.send_message(message.chat_id, image_file_path)


def get_image_id_from_message(message):
    # there are multiple array of images, check the biggest
    return message.photo[len(message.photo) - 1].file_id


def get_image_path(message):
    image_id = get_image_id_from_message(message)
    file_path = bot.get_file(image_id).file_path
    print(file_path)
    return file_path;

所以我用了另一个python代码,在那里连接到S3(s3upload.py)

import boto3
import config
from botocore.client import Config

# S3 Connect
s3_bucket = boto3.resource(
    's3',
    aws_access_key_id=config.AWS_ACCESS_KEY_USER_2,
    aws_secret_access_key=config.AWS_SECRET_KEY_USER_2,
    config=Config(signature_version='s3v4')
)

def image_upload(my_file):
    data = open(my_file, 'rb')
    s3_bucket.Bucket(config.S3_BUCKET_NAME).put_object(Key=my_file, Body=data, ACL='public-read')
    print("done")

问题-python无法找到文件(FileIsNotFound)。帮助我请理解: 1.如何正确连接到S3? 2.如何使用电报机器人的文件(图像)?

1 个答案:

答案 0 :(得分:0)

编辑:对不起,我第一次读这篇文章时误会了。

我将使用put_objectread the description而不是使用upload_file。另请参见post关于区别。

关于功能,您可以尝试类似

def image_upload(my_file):
  file_key = s3_file_name
  s3_bucket.meta.client.upload_file(my_file, mybucket, file_key)

就我的原始观点而言,请确保您的IAM用户具有足够的特权。听起来好像您可以在本地使用aws s3 ..一样,那么您应该就很好了。