DEV Community

Cover image for Sending images and more with Telegram bot
Rajitha Gunathilake
Rajitha Gunathilake

Posted on

Sending images and more with Telegram bot

Hi everyone,

This is a follow-up tutorial on my previous tutorial about Sending messages with Telegram bot. make sure you check that before following this tutorial.

in the last tutorial, we talked about sending messages, but telegram has a powerful API that allows us to send more than just text messages.
so in this tutorial, we will get to know how to send images with a telegram bot.This procedure is really simple. we need to send a post request to telegram API with our photo as multipart/form-data.

This is similar to what we used previously, the change is now we are using a different route, and sending form-data with our image attached

Using the follwoing API endpoint https://api.telegram.org/bot<token>/sendPhoto?chat_id=<group chat id >

in multipart form data attach an image file with the name photo

insomnia send request

and after sending this we can get a response with "ok": true, and if we look at the chat, we can see that the photo is received.

chat image

This can also be done programmatically, I will use nodejs to demonstrate in this example.

const fetch = require("node-fetch");
const fs = require("fs");
const FormData = require("form-data");

let readStream = fs.createReadStream("./image.png");

let form = new FormData();
form.append("photo", readStream);

fetch(
  `https://api.telegram.org/bot<token>/sendPhoto?chat_id=-<chat id>`,

  {
    method: "POST",
    body: form,
  }
)
  .then((res) => res.json())
  .then((response) => {
    console.log(response);
  })
  .catch((error) => {
    console.log(error);
  });

Enter fullscreen mode Exit fullscreen mode

we have used node-fetch package to send the HTTP request from nodejs and form-data package to append formdata to the request.

and after running the script we can see that we get "ok": true, just like before.

bash output

chat image

there are some limits provided by the telegram when using sendPhoto API
"The photo must be at most 10 MB in size. The photo's width and height must not exceed 10000 in total. Width and height ratio must be at most 20".

Telegram API reference sendphoto method

we can use sendAudio just like the last example to send audio files.

const fetch = require("node-fetch");
const fs = require("fs");
const FormData = require("form-data");

let readStream = fs.createReadStream("./audio.mp3");

let form = new FormData();

form.append("audio", readStream);
form.append("title", "audio dev test");// to show as the title in chat

fetch(
  `https://api.telegram.org/bot<token>/sendAudio?chat_id=-<chat id>`,

  {
    method: "POST",
    body: form,
  }
)
  .then((res) => res.json())
  .then((response) => {
    console.log(response);
  })
  .catch((error) => {
    console.log(error);
  });
Enter fullscreen mode Exit fullscreen mode

limits provided by the telegram when using sendAudio API

"Your audio must be in the .MP3 or .M4A format. On success, the sent Message is returned. Bots can currently send audio files of up to 50 MB in size, this limit may be changed in the future."

Telegram API reference sendaudio method

audio chat

And the list goes on and on for documents, voice messages,animations , videos etc. you can find all the provided methods in the Telegram reference.

Thanks for reading till the end 🙌

share your thoughts in the comments section.

Top comments (22)

Collapse
 
nileshkawar profile image
Nilesh Kawar

Hey buddy I need help regarding telegram bot development
I'm new to telegram bot development i have been stuck in one issue for 5 days and I can't figure it out It'd be great if you could help me pls

Collapse
 
rizkyrajitha profile image
Rajitha Gunathilake

can you specify the issue ?

Collapse
 
nileshkawar profile image
Nilesh Kawar

So basically I have an array i want to show elements from an array in inlineKeyboard buttons

I have explained it on stackoverflow:
stackoverflow.com/questions/676461...

Pls help

Thread Thread
 
rizkyrajitha profile image
Rajitha Gunathilake

I'll take a look , and let you know .

Thread Thread
 
nileshkawar profile image
Nilesh Kawar

Yes please

Thread Thread
 
rizkyrajitha profile image
Rajitha Gunathilake
const { Telegraf } = require("telegraf");
const axios = require("axios");

const bot = new Telegraf("XXXXX");
bot.start((ctx) => ctx.reply("Welcome"));
bot.help((ctx) => ctx.reply("Send me a sticker"));
bot.on("sticker", (ctx) => ctx.reply("👍"));
bot.hears("hi", (ctx) => ctx.reply("Hey there"));
bot.hears("Wow", async (ctx) => {
  let stateNames = await getStates();
  console.log(stateNames);

  let listt = [];

  for (let index = 0; index < stateNames.length - 1; index += 2) {
    listt.push([
      { text: stateNames[index], callback_data: String(index) },
      { text: stateNames[index + 1], callback_data: String(index + 1) },
    ]);
  }

  console.log(listt);

  ctx.telegram.sendMessage(ctx.chat.id, "nani", {
    reply_markup: {
      inline_keyboard: listt,
    },
  });
});

bot.launch();

// Enable graceful stop
process.once("SIGINT", () => bot.stop("SIGINT"));
process.once("SIGTERM", () => bot.stop("SIGTERM"));

async function getStates() {
  url = "https://api.covid19india.org/data.json";
  res = await axios.get(url);

  stateArr = res.data.statewise;
  totalStates = stateArr.length;

  let stateName = new Array();

  for (let i = 0; i < totalStates; i++) {
    stateName[i] = stateArr[i].state;
  }

  // console.log(stateName);

  return stateName;
}

Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
rizkyrajitha profile image
Rajitha Gunathilake

Thread Thread
 
rizkyrajitha profile image
Rajitha Gunathilake

hope this helps

Thread Thread
 
nileshkawar profile image
Nilesh Kawar

Thank you so much, sir. I have been stuck for one week on this issue. Thank you so much for resolving and providing a solution.

I tried myself but couldn't solve it. I googled it, asked so many peoples but no one replied, and finally, you solved it.
Again Thank you so much.

Thread Thread
 
rizkyrajitha profile image
Rajitha Gunathilake

your welcome ✌

Collapse
 
samifolio profile image
Sami Folio

Hello Rajitha, I need to receive specific photos from Telegram to a Telegram widget on my site. I can pay $100 if you can help. I will have lots of other things to do after that. The chat ID i want photos from has lots of images, and i only want those with a word before them. Suppose there are photos of animals and i only want the ones with cats, so the sentence before has to start with "cat" . And it can only be from the Channel owner, not people who comment.

Collapse
 
rizkyrajitha profile image
Rajitha Gunathilake

hi sami,
thanks for your offer but these days i am a bit busy , and not available for work .

Collapse
 
samifolio profile image
Sami Folio

Ok, thank you.

Collapse
 
bmvavinash profile image
avinash

Hi Sami Folio, Is the issue resolved, or can we discuss further on it

Collapse
 
Sloan, the sloth mascot
Comment deleted
Collapse
 
rizkyrajitha profile image
Rajitha Gunathilake

can you state the error

Collapse
 
taaltos profile image
Nagy László

Image description

ezzel a háttérrel :

Image description

ezt a férfit árnyékkal

Collapse
 
taaltos profile image
Nagy László

Image description

Image description

Collapse
 
3ehzad profile image
Behzad Amirinezhad

Thank you for your great post. Is it possible to send image in edit_message_text() or somehow append the image to it?

Collapse
 
rizkyrajitha profile image
Rajitha Gunathilake

if you want to send image with a caption , you can use caption in parameter in formdata

refer this documentation - core.telegram.org/bots/api#sendphoto

Collapse
 
boptional19813 profile image
Bluestone Optional

Can telegram bot store data? Of yes what about if I send a photo to telegram bot will it save it forever???? Or do they delete it .

Collapse
 
taaltos profile image
Nagy László

Hello
Azt szertném tudni, hogy két fotoból tudna-e egy hiteles montázst készíteni ?