I built a working Telegram bot using Python and it can send messages fine. But now I want to send pictures too. I looked at the official Bot API docs and saw methods for sending photos and videos but I can’t figure out how to use them properly.
Here’s what I tried:
if message_text == '/photo':
picture = Image.new('RGB', (256, 256))
color_base = random.randint(0, 16777215)
pixel_data = [color_base+x*y for x in range(256) for y in range(256)]
picture.putdata(pixel_data)
buffer = BytesIO()
picture.save(buffer, format='PNG')
send_photo(image_data=buffer.getvalue())
I also tried loading an existing file:
my_img = Image.open('test.jpg')
my_img.show()
But nothing gets sent to the chat. The bot just ignores the command. What am I doing wrong? How do I properly send image files through a Telegram bot in Python?
You’re not actually calling the Telegram API to send the photo. Your send_photo function needs to use bot.send_photo with the chat_id parameter. Here’s what fixed it for me:
if message_text == '/photo':
picture = Image.new('RGB', (256, 256))
color_base = random.randint(0, 16777215)
pixel_data = [color_base+x*y for x in range(256) for y in range(256)]
picture.putdata(pixel_data)
buffer = BytesIO()
picture.save(buffer, format='PNG')
buffer.seek(0)
bot.send_photo(chat_id=update.message.chat_id, photo=buffer)
Don’t forget buffer.seek(0) to reset the buffer position and make sure you’re passing chat_id correctly. If you’re sending existing files, just pass the file path directly to the photo parameter instead of using a buffer.
yep, it looks like your send_photo function ain’t linked to the Telegram API. you gotta use bot.send_photo() with the chat_id. for existing files, do with open('test.jpg', 'rb') as photo: bot.send_photo(chat_id, photo). Image.open() just opens the file and doesn’t send it.
Your custom send_photo function isn’t hooked up to the Telegram Bot API. You’ve got to use the actual bot instance method. I hit this exact issue when I started with file uploads. For generated images, reset the buffer pointer after writing - add buffer.seek(0) before sending. Then use bot.send_photo(chat_id=chat_id, photo=buffer) where chat_id comes from the incoming message. For existing files, just pass the file path directly instead of opening it manually. That Image.open() approach only loads the image into memory - it doesn’t actually send anything to Telegram.