How to send message on Telegram using API

Spread the love

To send a message on Telegram using telegram official api we need to do these things.

Create a Telegram Bot

Now lets understand how to create a bot on telegram?

  • Open Telegram and search @BotFather in search bar.
  • Type /start and then click on /newbot command
  • Bot is asking to give your bot name for example : VidyaRays
  • Now you have to enter a unique username of your bot example : @vidyarays_bot ( must include _bot or bot in last of your username else its not supported)
  • Now after following these instructions you get a bot token.
  • Your bot token look like : 123456789:ABCdefGhIJKlmNoPQRstuvWxyZ

Get your CHAT ID of your account.

There are two method that we can find our chat id of our account.

  1. Search @getids bot on telegram search bar and then /start and then you can see your chat id look like : 12345678
  2. Start your bot that you had been created.
  3. Now hits this api https://api.telegram.org/bot<YOUR_BOT_TOKEN>/getUpdates with your following bot token then you can see json response and it you will find "chat":{"id":123456789,…} and thats you chat id.

Now we use sendMessage API to send message

This api url support both POST and GET request https://api.telegram.org/bot/sendMessage hit this api using these parameters.

  1. chat_id: your account chat id,
  2. text: your message you want to send using telegram api.

Example using cURL (GET)

curl "https://api.telegram.org/bot123456789:ABCdefGhIJKlmNoPQRstuvWxyZ/sendMessage?chat_id=123456789&text=Hello%20VidyaRays"

Example using PHP

<?php
$token = "123456789:ABCdefGhIJKlmNoPQRstuvWxyZ";
$chat_id = "123456789";
$message = urlencode("Hello vidyarays!");

$url = "https://api.telegram.org/bot$token/sendMessage?chat_id=$chat_id&text=$message";

file_get_contents($url);
?>

Example using Python (with request)

import requests

token = '123456789:ABCdefGhIJKlmNoPQRstuvWxyZ'
chat_id = '123456789'
message = 'Hello vidyarays!'

url = f'https://api.telegram.org/bot{token}/sendMessage'
params = {'chat_id': chat_id, 'text': message}

response = requests.get(url, params=params)
print(response.json())

And thats it. now you can send message anyone using Telegram official API.

Pro Tips:

  1. Never getting known your bot token to anyone protect your bot token like your secret password.
  2. Bot cant initiate a message. you have to start the bot first then you are able to find your chat id and send message.

I hope this article helpful for you. If you want to learn how to send images, files and button using telegram api then must read this.