How to send message using Telegram Bot

January 22, 2023

Even wondered to use your Telegram to keep on track of your important events in real-time or just use it to get custom push notifications across all your devices?

Well, that’s actually quite simple and free by using your own Telegram Bot.

Let’s get started!

Step 0: Creating Telegram Bot

You can use @BotFather (just search for it) to create your own Telegram bot.

You can start the process by sending /join and then /newbot command

telegram create bot using botfather

Note down the access token once your bot is created. We’ll be using it to send a message.

We’re also disabling the privacy of the bot so that it can listen to all the messages sent to it without having to create a custom command for our bot. (This step is optional)

Step 1: Getting Chat ID to send a message

We can send messages either to a person (in our case us) or to a group/channel to which the bot has access to send messages.

Our only dependency is to figure out the chat id which is needed to send a message.

To get the chat id, just send a message to your bot (or to the group to where you’ve added the bot)

Then go to the following endpoint there you can get the chat id.

https://api.telegram.org/bot/getUpdates

telegram chat id using http api private

telegram chat id using http api group

Step #3: Sending a message using HTTP API

Now that we’ve both the API Key and Chat Id, we can send messages pretty easily by using their API.

Here’s a snippet that I use in my projects

import axios from 'axios'; // or, you can use fetch. It's up to you :)
// 
const authToken = process.env.TELEGRAM_BOT_TOKEN;
const chatId = process.env.TELEGRAM_CHAT_ID;


const sendTelegramNotification = async (message) => {
    const url = `https://api.telegram.org/bot${authToken}/sendMessage`;
    const payload = {
        chat_id: chatId,
        text: message,
        // https://core.telegram.org/bots/api#html-style
        parse_mode: 'html' // html | markdown
    }
    
  return  axios.post(url, payload)
}

export default sendTelegramNotification;

Happy Telegram Notifications!


👋 I'm Ashik Nesin • Principal Software Engineer 👨‍💻• I write about web development and share insights into the behind-the-scenes of the projects that I'm building.

© 2023 Nesin Technologies LLP