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

4

12

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?

Joachim answered 14/5, 2017 at 21:38 Comment(0)
S
10

Try this line of code

status = requests.post("https://api.telegram.org/bot<TOKEN>/sendPhoto?chat_id=" + data['chat_id'], files=files)
Standoffish answered 22/10, 2017 at 7:6 Comment(0)
R
3

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.

Rubiaceous answered 29/3, 2020 at 14:8 Comment(1)
How can i define files as a part of the url and not as a parameter?Bain
Y
2

You need to pass chat_id parameter in URL:

files = {'photo': open('./saved/{}.jpg'.format(user_id), 'rb')}
status = requests.post('https://api.telegram.org/bot<TOKEN>/sendPhoto?chat_id={}'.format(chat_id), files=files)
Yawata answered 10/2, 2018 at 21:13 Comment(0)
T
0

Your problem already solved by aiogram python framework.

This is full example. Just edit TOKEN and PHOTO_PATH, run the code and send /photo command to the bot :)

from aiogram import Bot, Dispatcher, executor
from aiogram.types import InputFile, Message

TOKEN = "YourBotToken"
PHOTO_PATH = "img/photo.png"

bot = Bot(TOKEN)
dp = Dispatcher(bot)


@dp.message_handler(commands=["photo"])
async def your_command_handler(message: Message):
    photo = InputFile(PHOTO_PATH)
    await message.answer_photo(photo)


if __name__ == '__main__':
    executor.start_polling(dp)

Therefor answered 29/11, 2021 at 8:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.