Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I upload an image to Telegram's sever

I'm writing a telegram bot (in Python) that sends images. I'm sending every images several times, and the documentation recommends to sent send a file_id of a file that is already stored in Telegram's sever.

But I can't find any documentation about storing a file In the sever and getting a file_id. I can try to send an image (to myself? to the bot?) and get it's file_id, but it seems sooo hacky.

like image 825
Ronen Avatar asked Oct 28 '25 05:10

Ronen


2 Answers

OK, I got it.. you do have to send an image once, but it easy to get the file_id:

msg = bot.send_photo(chat_id=chat_id, photo=open("filename", "rb"))
file_id = msg.photo[0].file_id
 ...
bot.send_photo(photo=file_id)
like image 169
Ronen Avatar answered Oct 30 '25 15:10

Ronen


Here is a vanilla python solution:

from io import BytesIO
import requests
from PIL import Image

CHAT_ID = 'id'
SEND_PHOTO = f'https://api.telegram.org/bot{TOKEN}/sendPhoto'

image = Image.open('photo.jpg')

with BytesIO() as output:
    image.save(output, format='JPEG')
    output.seek(0)
    requests.post(SEND_PHOTO, data={'chat_id': CHAT_ID}, files={'photo': output.read()})

Note that chat_id should be passed via data parameter (not json) and bytes via file parameter of requests.post. It also has to include photo key.

like image 21
Aray Karjauv Avatar answered Oct 30 '25 14:10

Aray Karjauv



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!