9

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?

maslick
  • 2,903
  • 3
  • 28
  • 50
mmsamiei
  • 165
  • 1
  • 2
  • 10

4 Answers4

8

Try this line of code

status = requests.post("https://api.telegram.org/bot<TOKEN>/sendPhoto?chat_id=" + data['chat_id'], files=files)
AndreyF
  • 1,798
  • 1
  • 14
  • 25
Pyae Hlian Moe
  • 339
  • 3
  • 3
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.

vander
  • 548
  • 7
  • 15
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)
Delimitry
  • 2,987
  • 4
  • 30
  • 39
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)

Oleg
  • 523
  • 2
  • 10