2.19.8. Example of hosting a Telegram bot on PHP

Attention!

The bot can only send messages to users who have sent it any message and have not stopped it or blocked it.

To work with a Telegram bot, it is recommended to use Webhook. This method is preferable to Long Polling for several reasons:

  • A script that runs using Webhook is slightly faster than a script that updates information at a specific interval.
  • On shared and business hosting, there is a time limit on the process execution, so the script cannot be run all the time and is automatically terminated by the system. This limitation cannot be bypassed, so using a script that is always running may result in data loss if the script terminates while processing an event.
  1. Initialize the creation of a new bot — send to the @BotFather Telegram bot the message /newbot.
  2. The bot will ask for a new bot name — send a message that will be accepted as the bot name.
  3. Send a message with the name of the bot. The name differs from the title in that it is a unique identifier with which you can use invitations, create links to it, etc. The name must have the word bot at the end (for example, examplebot or example_bot).
  4. The new message will contain a token that you will need to use for the bot to work. Save this token.

Attention!

For Webhook to work, a valid SSL certificate (for example, a certificate from Let's Ecnrypt) must be used on the site.

There are several ways to set a Webhook:

Follow the link of the form:
https://api.telegram.org/bottoken/setWebhook?url=https://domain.com/path/to/file.php

In the link, use your data:

  • token — token that you received when creating the bot. ⚠️ You do not need to change the word bot before token.
  • domain.com — your domain, which Telegram will use to send requests to your bot. It is not recommended to specify an address with or without www in case a redirect to the opposite address is set.
  • path/to/file.php — path to the bot file that will process requests.

After following the link, a message like "Webhook has been set" should appear in the browser. If this message appears, Webhook has been set correctly, otherwise recheck the URL used and the SSL certificate.

Attention!

In the script there must be a condition that limits the number of runs to install and test Webhook, because frequent access to Telegram will produce an error and terminate the script.

Add this code at the beginning of your script (after declaring variables with token data and bot name):

if(!json_decode(file_get_contents("https://api.telegram.org/name:token/setWebhook?url=https://domain.com/path/to/file.php"))->ok){die('webhook is not set');}
An example of a simple bot that will respond to the message /start:
<?php
define('token','XXXXXXXXXXXXXXXXXXXXXXXXX'); // instead of ''XXXXXXXXXXXXXXXXXXXXXXXXX'', specify your token
$result = json_decode(file_get_contents('php://input'), true); // pass full information about the user's message to the $result variable
if ($result['message']['text'] == '/start') {
    file_get_contents("https://api.telegram.org/bot" . token . "/sendMessage?chat_id=" . $result['message']['chat']['id'] . "&text=" . urlencode('Hi')); // send a reply to the user using his unique identifier $result['message']['chat']['id'] as the recipient
}

Attention!

In order for the Telegram Bot SDK library to work, you must change PHP version to 8.0 or higher.
  1. Connect to the hosting via SSH.
  2. Go to your site's catalog:
    cd ~/example.com/www
  3. Install the Telegram Bot SDK library:
    composer require irazasyed/telegram-bot-sdk
  4. Create a file and put in it an example of a simple bot using the Telegram Bot SDK library:
    <?php
    include('vendor/autoload.php'); // connect the library
    use Telegram\Bot\Api; 
    
    $telegram = new Api('XXXXXXXXXXXXXXXXXXXXXXXXX'); // instead of ''XXXXXXXXXXXXXXXXXXXXXXX'', specify your token
    $result = $telegram -> getWebhookUpdates(); // pass full information about the user's message to the $result variable
    
    $text = $result["message"]["text"]; // message text
    $chat_id = $result["message"]["chat"]["id"]; // unique user identifier
    $name = $result["message"]["from"]["username"]; // user name
    
    if ($text) {
        if ($text == "/start") {
            $reply = "Hi!";
            $telegram->sendMessage(['chat_id' => $chat_id, 'text' => $reply]);
        }
    }
Content

    (5)