0

I have a telegram bot with a minimum number of functions. The task now is to upload files from users in telegram-chat and send to S3.

I use Heroku by server. But I need the fraa place, where I can store my files (S3)

Here is the bot.py code

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;

And so I use another python code, where connect to 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")

The problem - python cant find the file (FileIsNotFound). Help me pleade understand: 1. How correctly connect to S3? 2. How I can use the files (images) from telegram-bot ?

1 Answers1

0

Edit: Sorry I misunderstood what was happening when I first read this.

Instead of using put_object I would use the upload_file, read the description. Also see a post about the difference.

Also regarding the function, you might try something like

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

To my original point, make sure your IAM user has adequate privileges. It sounds like if you're able to do it using aws s3 .. locally, then you should be good to go.

Taylor Turner
  • 198
  • 1
  • 1
  • 8
  • I use free plan of Heroku. Because it was easy to deploy. 1. You might be missing an S3 Bucket Policy that allows your user to PUT or GET files from it. - I didnt see smthg like that in boto3. Can you send me documentation plz? 2. My first problem is find the image. I tried in test and could upload in s3 the image from os. – Levon Sargsyan Feb 16 '20 at 20:47
  • I refactored the original answer, let me know if that helps. – Taylor Turner Feb 16 '20 at 22:45