A Practical Guide to Building a Telegram Bot with Slim in PHP

Telegram bots are an increasingly popular tool used for a variety of purposes. A Telegram bot is essentially a program that runs inside the Telegram messaging app, allowing users to interact with it through commands or other input.

With the ability to send messages, images, videos, and other types of media, Telegram bots can be used for a wide range of use cases, from business and marketing to personal productivity and entertainment.

Some popular use cases for Telegram bots include automated customer service, news and content delivery, e-commerce, language learning, and even games and quizzes. With the ability to integrate with other web services and APIs, the possibilities for Telegram bots are virtually limitless, making them an increasingly popular tool for developers and businesses alike.

Set up your environment

To start building your Telegram bot, you will first need to set up your development environment. Follow these steps to get started:

Install PHP and Composer, which is a dependency manager for PHP. You can find instructions on how to do this on the Composer website.

Create a new project directory for your bot and navigate to it using your terminal.

Initialize a new Composer project by running the following command in your terminal:

composer init

Install the Slim framework by running the following command:

composer require slim/slim slim/psr7

Create a Telegram bot

To create a Telegram bot using Botfather, follow these steps:

Open the Telegram app and search for Botfather by typing @Botfather in the search bar.

Start a chat with Botfather by clicking the "Start" button and send the command /newbot to Botfather.

Choose a name and a username for your bot. Botfather will provide you with a token that you can use to connect your bot to the Telegram API and start building your bot's functionality.

Keep the token safe since it acts as a password for your bot.

Set up your Slim application

To set up a basic Slim application in your project directory, follow these steps:

Create a new file called index.php in your project directory. Copy and paste the following code into index.php:

<?php

use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Factory\AppFactory;

require __DIR__ . '/vendor/autoload.php';

$app = AppFactory::create();

$app->get('/', function (Request $request, Response $response) {
    $response->getBody()->write("Hello, World!");

    return $response;
});

$app->run();

This code sets up a basic Slim application with a single route that returns a "Hello, World!" message when you navigate to the root URL.

Start your web server by running the following command in your terminal:

php -S localhost:8000

Navigate to localhost:8000 in your web browser to make sure your application is working.

Connect your Telegram bot to your Slim application

To connect your Telegram bot to your Slim application, follow these steps:

Install the irazasyed/telegram-bot-sdk package by running the following command:

composer require irazasyed/telegram-bot-sdk

Update the following code inside your index.php file:

$app->get('/', function (Request $request, Response $response) {
    $telegram = new Telegram\Bot\Api("TELEGRAM_BOT_TOKEN");

    if ($telegram->setWebhook(["url" => "TELEGRAM_WEBHOOK_URL"])) {
        $message = "Webhook updated successfully!";
    } else {
        $message = "It seems something went wrong!";
    }

    $response->getBody()->write($message);

    return $response;
});

This code initializes the Telegram Bot API with your API token and uses it to set the webhook URL for your bot.

Start your web server by running the following command in your terminal:

php -S localhost:8000

Handle user input

To handle user input, you'll need to modify the route in your index.php file to handle incoming messages. Here's an example:

$app->post('/hook', function (Request $request, Response $response) {
    $telegram = new Telegram\Bot\Api("TELEGRAM_BOT_TOKEN");

    $input = json_decode($request->getBody(), true);

    $chat_id = $input['message']['chat']['id'];
    $text = $input['message']['text'];

    $telegram->sendMessage([
        'chat_id' => $chat_id,
        'text' => 'You said: ' . $text,
    ]);

    return $response->withStatus(200);
});

This code modifies the root route to accept POST requests, extracts the chat ID and message text from the request body, sends a message back to the user using the Telegram API, and returns a 200 status code to indicate success.

Congratulations! By now, you should have a good understanding of the basic concepts involved in building a Telegram bot with Slim in PHP. With this knowledge, you can explore the possibilities of building more complex and advanced bots, using the tools and resources available in the Slim and Telegram communities.

Telegram bots are a powerful tool that can be used for a variety of purposes, from automating customer service to delivering news and content. With the knowledge you've gained in this guide, you're now equipped to build your own bots and explore the possibilities of this exciting technology. Good luck and happy bot building!