How to Create a Telegram Bot for Sending Notifications using PHP

Do you want to build a Telegram bot and 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 create a Telegram bot and send messages to the Telegram channel and group through the bot with the help of PHP.

The Telegram API provides endpoints to perform certain operations like getting updates of your group/channel, posting plain text, or rich text messages on the channel. For this, you need to hit Telegram API endpoints along with the required parameters.

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

Create a Telegram Bot

You can create your private bot by interacting with the official Telegram’s @BotFather bot. Open the Telegram app on 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 demo purposes, I have given sajidtelegram2021_bot.
  • In the same chat session, you will receive an API token. Copy this token as it will require while interacting with Telegram API.
create-telegram-bot

Following the above steps, you can create your private Telegram bot. After this, you must interact with this private bot from your own Telegram account.

Visit your bot. You can use the link which is something like 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 build a PHP script to send notifications on your Telegram group and channel. We can do it with the help of the private bot we just created. This private bot must be added to the Telegram channel and group. You need to promote the bot as an admin.

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

Get List of Telegram Channels and Groups

To send notifications on Telegram through API, 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.

Install the Guzzle HTTP Client using the command below.

composer require guzzlehttp/guzzle

Now, by hitting the Telegram endpoint we get a list of chat ids where a bot has access to write 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();
}

Upon running this code, you would get an array containing chat ids and titles.

Post Messages to Telegram using PHP

Once you get the chat ids, we can easily post messages via Telegram API. It requires you to hit the API endpoint and send chat id, text 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";
    $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

The Telegram allows you to send rich text messages styled either with HTML or the 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 use parse_mode with 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 Telegram using PHP. For more details, check out the official documentation of Telegram API.

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 *