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.
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With