Combining text and photo in single Telegram bot message

I need help with my Telegram bot implementation. Currently I can send text messages using the sendMessage endpoint and images using sendPhoto, but I want to combine them into one request.

Here’s my current code for sending text:

response = requests.get(f'https://api.telegram.org/bot{token}/sendMessage?chat_id={channel_id}&text=hello world')

I also have an image URL that I want to include. Is there a way to send both the image and text together in a single API call? I’ve been looking through the documentation but can’t figure out how to merge these two operations. Any suggestions would be really helpful!

Use the sendPhoto method instead. It has a caption parameter that lets you send text and image together in one API call. Change your code to:

response = requests.get(f'https://api.telegram.org/bot{token}/sendPhoto?chat_id={channel_id}&photo={image_url}&caption=hello world')

I’ve used this in my own bots and it works great. You get up to 1024 characters for the caption and can use HTML or Markdown formatting just like regular messages.

definitely agree! encoding the image_url is crucial. i had a similar issue before, and it was so frustrating to deal with the silent failures. glad you’re on the right track now!

Watch out for caption length limits. I hit this building a news bot - some articles had long descriptions and Telegram’s API cuts off captions at 1024 characters without telling you, which breaks your formatting. Also, POST requests work better than GET for larger images. I use requests.post(url, data={'chat_id': channel_id, 'photo': image_url, 'caption': text}) - it’s way more stable when you’re dealing with dynamic content and image URLs that have special characters.

This topic was automatically closed 4 days after the last reply. New replies are no longer allowed.