Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to send photo by telegram bot using multipart/form-data

I have a telegram bot (developed in python) and i wanna to send/upload photo by it from images that are in my computer.

so i should do it via multi part form data.

but i don't know ho to do it. also i didn't find useful source for this on Internet and on telegram documentation .

i tried to do that by below codes. but it was wrong

data = {'chat_id', chat_id}
files = {'photo': open("./saved/{}.jpg".format(user_id), 'rb')}
status = requests.post("https://api.telegram.org/bot<TOKEN>/sendPhoto", data=data, files=files)

can anyone help me?

like image 797
mmsamiei Avatar asked May 14 '17 21:05

mmsamiei


People also ask

Can Telegram BOT send pictures?

Photo to send. Pass a file_id as String to send a photo that exists on the Telegram servers (recommended), pass an HTTP URL as a String for Telegram to get a photo from the Internet, or upload a local photo by passing a file path.

Can Telegram BOT send files?

Bots can currently send video files of up to 50 MB in size, this limit may be changed in the future. Use this method to send video files that are already on the Telegram servers.

How do I download a file or photo that was sent to my Telegram bot?

The file can then be downloaded via the link https://api.telegram.org/file/bot/, where is taken from the response. It is guaranteed that the link will be valid for at least 1 hour. When the link expires, a new one can be requested by calling getFile again. For the moment, bots can download files of up to 20MB in size.


2 Answers

Try this line of code

status = requests.post("https://api.telegram.org/bot<TOKEN>/sendPhoto?chat_id=" + data['chat_id'], files=files)
like image 76
Pyae Hlian Moe Avatar answered Oct 05 '22 19:10

Pyae Hlian Moe


Both answers by Delimitry and Pyae Hlian Moe are correct in the sense that they work, but neither address the actual problem with the code you supplied.

The problem is that data is defined as:

data = {'chat_id', chat_id}

which is a set (not a dictionary) with two values: a string 'chat_id' and the content of chat_id, instead of

data = {'chat_id' : chat_id}

which is a dictionary with a key: the string 'chat_id' and a corresponding value stored in chat_id.

chat_id can be defined as part of the url, but similarly your original code should work as well - defining data and files as parameters for requests.post() - as long as both data and files variables are dictionaries.

like image 41
vander Avatar answered Oct 05 '22 19:10

vander