6.11 How to host a Telegram bot

Banner

Messengers have become an integral part of our lives, and Telegram occupies a special place among them. One of Telegram’s unique features is the ability to create bots – special accounts managed by programs. These bots can perform various tasks: from simple message responses to complex data operations.

Installing a Telegram bot on a virtual server opens up wide opportunities for process automation, improving customer communication, or simply for entertainment. This process may seem complicated for beginners, but by following our step-by-step guide, You will be able to easily manage this task.

Important: before starting the installation, make sure You have root access to Your virtual server and basic command line operation skills.

Installation and Setup of a Telegram Bot in PHP

This article describes a step-by-step installation and setup of a Telegram bot using PHP. We will review how to create and register a bot through BotFather, configure a Webhook, and use the PHP Telegram Bot library to automate the process.

Creating a Bot through BotFather

To start working with the Telegram API, you need to create a new bot and obtain a unique API token:

1. Open Telegram and find @BotFather. Send the /newbot command and follow the instructions. You will need to specify a name and a unique bot name (the name must end with bot, for example, example_bot).

2. After creating the bot, @BotFather will issue an API token that will be required to connect your bot to the Telegram API. Save it in a secure place.

Installing the PHP Telegram Bot Library

To work with the Telegram API in PHP, add the longman/telegram-bot library to the project using Composer. Run the following command in the terminal:

  1. composer require longman/telegram-bot

This library will simplify interaction with the API and allow processing commands and messages.

Setting up a Webhook for the Bot

Webhook allows receiving real-time updates from Telegram, but for its operation, a server with HTTPS support is needed. Create a set.php file to set up the Webhook:

set.php
<?php
require __DIR__ . '/vendor/autoload.php';

$bot_api_key  = 'YOUR_API_TOKEN';
$bot_username = 'YOUR_BOT_NAME';
$hook_url     = 'https://your-domain/path/to/hook.php';

try {
    $telegram = new Longman\TelegramBot\Telegram($bot_api_key, $bot_username);
    $result = $telegram->setWebhook($hook_url);
    echo $result->isOk() ? $result->getDescription() : 'Webhook installation error';
} catch (Longman\TelegramBot\Exception\TelegramException $e) {
    // Handling Telegram errors
}

Then create a hook.php file that will process requests coming from Telegram:

hook.php
[label getUpdatesCLI.php]
<?php
require __DIR__ . '/vendor/autoload.php';

$bot_api_key  = 'YOUR_API_TOKEN';
$bot_username = 'YOUR_BOT_NAME';

try {
    $telegram = new Longman\TelegramBot\Telegram($bot_api_key, $bot_username);
    $telegram->handle();
} catch (Longman\TelegramBot\Exception\TelegramException $e) {
    // Handling Telegram errors
}

Upload both files to the server and open set.php in the browser to register the Webhook. If everything is configured correctly, you will see the message Webhook was set.

Using the getUpdates Method (Webhook Alternative)

If your server does not support HTTPS, instead of Webhook, you can use the getUpdates method. It will manually request messages from Telegram. Configure the getUpdatesCLI.php file and add database connection details if you want to save messages and users:

$mysql_credentials = [
    'host'     => 'localhost',
    'port'     => 3306,
    'user'     => 'dbuser',
    'password' => 'dbpass',
    'database' => 'dbname',
];

$telegram->enableMySql($mysql_credentials);

To run the script, execute:

  1. php getUpdatesCLI.php

Informing: When using Composer to install PHP Telegram Bot, manual bot auto-launch is not required for each new message, as the bot’s operation is automated using Webhook or getUpdates.

Once the Webhook is set, Telegram automatically sends updates to your server by calling the hook.php script. This file contains a handler for Telegram requests and works in real-time. The main condition for Webhook is that your server must support HTTPS so that Telegram can send updates. If the Webhook is configured correctly, the bot will automatically respond to messages, and no additional actions will be required to launch it.

An alternative to Webhook is getUpdates — a polling method that can be used on servers without HTTPS. When using it, the script needs to be launched manually (for example, via cron) so that the bot can regularly check for new messages.

Usage Examples

The PHP Telegram Bot library supports many commands and methods for managing the bot and interacting with the Telegram API. Here are a few examples of capabilities that can be used:

  1. Media Sending: You can send photos, documents, and videos.

    use Longman\TelegramBot\Request;
    
    $result = Request::sendPhoto([
        'chat_id' => $chat_id,
        'photo'   => 'https://example.com/image.jpg',
        'caption' => 'Here is your photo!',
    ]);
    
  2. Creating Inline Buttons: You can add inline buttons for more interactive user interaction.

    $keyboard = [
        'inline_keyboard' => [
            [
                ['text' => 'Go to website', 'url' => 'https://example.com'],
                ['text' => 'Get more information', 'callback_data' => 'info']
            ],
        ],
    ];
    
    $result = Request::sendMessage([
        'chat_id'      => $chat_id,
        'text'         => 'Choose an option:',
        'reply_markup' => json_encode($keyboard),
    ]);
    
  3. Command Processing: You can customize commands that the bot will automatically process.

    $telegram->addCommand('/start', function ($chat_id) {
        return Request::sendMessage([
            'chat_id' => $chat_id,
            'text'    => 'Welcome to our bot!',
        ]);
    });
    
  4. Auto-Responders and Notifications: You can set up automatic responses to specific messages or periodic notifications.

    // Auto-responder example
    $telegram->addCommand('/help', function ($chat_id) {
        return Request::sendMessage([
            'chat_id' => $chat_id,
            'text'    => 'Available commands: /start, /help',
        ]);
    });
    

For detailed information about library capabilities and command usage examples, visit the official documentation PHP Telegram Bot on GitHub.