How to Create a Telegram Bot for Sending Notifications using PHP

Do you want to build a Telegram bot that can send notifications to the entire Telegram group or channel? It can be useful when you want to inform your Telegram group about some events. In this article, I’ll show you how to send notification to the group or channel through the Telegram bot using PHP.

The Telegram API provides endpoints to perform certain operations like getting updates on your group, fetching your channel ID, posting plain text or rich text messages, etc. To incorporate such tasks you need to hit Telegram API endpoints along with the required parameters.

I am going to use a Guzzle HTTP Client library to interact with the Telegram API. This package allows you to send HTTP requests on an external application and receive a response.

Create a Telegram Bot

To get started, you first require to create a Bot. You can create it by interacting with the official Telegram @BotFather bot. Open the Telegram app on a desktop or mobile and search for this @BotFather bot.

  • Start the chat session with @BotFather and type the command /newbot to create a Telegram bot.
  • Give a title to your bot and then a username. For instance, I have given sajidtelegram2021_bot.
  • In the same chat session, you will receive an API token. Copy this token as it will require in later steps.
create-telegram-bot

After creating a Telegram bot, you must interact with the bot from your own Telegram account. Visit your bot at the link t.me/username_bot. Click the Start button and type any warmup message.

Add Bot to Telegram Group and Channel

The purpose of this tutorial is to send notifications to your Telegram group or channel. It can be done via a private bot you just created. This private bot must be added to the Telegram channel and group. Also, you need to promote the bot as an admin.

Once you added the bot to the group, post a welcome message from your own Telegram account.

Get List of Telegram Channels and Groups

For sending notifications, you first need to grab the chat ids of a group or channel. With these chat ids, you can post a message to a specific channel. Each channel or group has a unique chat id.

Now, to fetch these chat ids you need to call the API endpoints. So install the Guzzle package using the command below.

composer require guzzlehttp/guzzle

Write the code below which will get your chat ids by hitting the Telegram API endpoints. These are the chat ids where your private bot has access to post messages.

<?php
require_once "vendor/autoload.php";
 
use GuzzleHttp\Client;

try {
    $client = new Client([
        // Base URI is used with relative requests
        "base_uri" => "https://api.telegram.org",
    ]);

    $bot_token = "BOT_TOKEN_HERE";
    
    $response = $client->request("GET", "/bot$bot_token/getUpdates");

    $body = $response->getBody();
    $arr_body = json_decode($body);

    if (!($arr_body->ok)) {
        throw new Exception("The API token is invalid.");
    }

    if (empty($arr_body->result)) {
        throw new Exception("Please add this bot to a Telegram group or channel and promote as an admin.");
    }

    $arr_result = array();
    foreach ($arr_body->result as $result) {
        $arr_result[] = [
            'chat_id' => $result->message->chat->id,
            'title' => $result->message->chat->title,
        ];
    }

    print_r($arr_result);

} catch(Exception $e) {
    echo $e->getMessage();
}

Here, along with the chat id, I’m also printing the title. Copy the chat id where you want to send notifications.

Post Messages to Telegram using PHP

Once you get the chat ids, you can easily post messages using the Telegram API. It requires you to hit the API endpoint and send the chat id, and your message as a parameter.

<?php
require_once "vendor/autoload.php";
 
use GuzzleHttp\Client;

try {
    $client = new Client([
        // Base URI is used with relative requests
        "base_uri" => "https://api.telegram.org",
    ]);

    $bot_token = "BOT_TOKEN_HERE";
    $chat_id = "-783112577"; //replace with yours
    $message = "How are you? I am Sajid.";
    $response = $client->request("GET", "/bot$bot_token/sendMessage", [
        "query" => [
            "chat_id" => $chat_id,
            "text" => $message
        ]
    ]);

    $body = $response->getBody();
    $arr_body = json_decode($body);

    if ($arr_body->ok) {
        echo "Message posted.";
    }
} catch(Exception $e) {
    echo $e->getMessage();
}

If you want to post multi-line messages then use the \n. For example, your multi-line message would be something like

$message = "How are you?\nI am Sajid.";

Post Rich Text Notification to Telegram

Telegram also allows you to send rich text messages styled either with HTML or markdown format.

Before writing rich text messages, check out the full list of HTML tags supported by Telegram. You must use only supported tags in the message else it will be rejected. To send these messages, you need to set parse_mode to either HTML or Markdown.

<?php
require_once "vendor/autoload.php";
 
use GuzzleHttp\Client;

try {
    $client = new Client([
        // Base URI is used with relative requests
        "base_uri" => "https://api.telegram.org",
    ]);

    $bot_token = "BOT_TOKEN_HERE";
    $chat_id = "-652336449";
    $message = 'Telegram supports different HTML tags like <a href="https://artisansweb.net">Anchor Tag</a>, <b>bold</b>, <em>emphasis</em>, <strong>strong</strong>, <s>strikethrough</s>, <u>underlines</u>, and <code>preformatted code</code>.';

    $response = $client->request("GET", "/bot$bot_token/sendMessage", [
        "query" => [
            "chat_id" => $chat_id,
            "text" => $message,
            "parse_mode" => "HTML",
        ]
    ]);

    $body = $response->getBody();
    $arr_body = json_decode($body);

    if ($arr_body->ok) {
        echo "Message posted.";
    }
} catch(Exception $e) {
    echo $e->getMessage();
}

I hope you understand how to post messages to the Telegram group and channel using PHP. For more details, check out the official documentation.

Related Articles

If you liked this article, then please subscribe to our YouTube Channel for video tutorials.

Leave a Reply

Your email address will not be published. Required fields are marked *