Skip to main content
CakeDC Blog

Integrating Telegram Bot with CakePHP using TeBo

This article is part of the CakeDC Advent Calendar 2024 (December 9th 2024)

Want to add a Telegram bot to interact with your users? TeBo is a great plugin that simplifies the process. In this guide, I’ll walk you through integrating a Telegram bot into your CakePHP 5 application with a practical example using the Pokémon public API. The bot will respond with details about a Pokémon when users send the command /pokemon <name>.

TeBo is a plugin designed specifically for managing bots in CakePHP, focusing on easy configuration and custom commands. GitHub Repository for TeBo

Step 1: Install the Plugin

Start by installing the TeBo plugin in your CakePHP project. You’ll need Composer, the PHP dependency manager. Run this command in the root of your project:

composer require arodu/tebo

After the plugin is installed, load it into your application:

bin/cake plugin load TeBo

That’s it! You’re ready to use the plugin.

Step 2: Set Up the Telegram Token

Every Telegram bot requires an authentication token, which you get by creating a bot on Telegram. Follow these steps:

  1. Open Telegram and search for BotFather, the official bot for creating and managing other bots.
  2. Send the command /newbot and follow the instructions. BotFather will ask for a bot name and a unique username.
  3. When you’re done, BotFather will give you an authentication token that looks like this: 1234567890:ABCDefghIJKlmNoPQRstuVWXyz.

Add this token to your .env file in your project:

export TELEGRAM_TOKEN="1234567890:ABCDefghIJKlmNoPQRstuVWXyz"

Step 3: Configure the Webhook

For your bot to receive updates from Telegram, you need to set up a webhook. This tells Telegram where to send messages for your bot in real time. TeBo provides commands to easily manage webhooks from the terminal:

  • Get webhook URL: Shows the current webhook URL.
  • Set webhook: Links your bot to a URL.
  • Remove webhook: Deletes the webhook configuration.
  • Get webhook info: Displays connection details.
  • Get bot info: Shows basic bot information.

To manage the webhook, use the following command and select option 2 from the menu:

bin/cake tebo

Or, set the webhook directly with this command:

bin/cake tebo webhook -s

Step 4: Create a Custom Command

Now that your bot is set up, let’s create a command to respond with Pokémon information when it receives /pokemon <name>.

4.1 Create the Command Action

In your project’s src/Actions folder, create a file named PokemonAction.php with the following code:

<?php
declare(strict_types=1);

namespace App\TeBo\Action;

use Cake\Cache\Cache;
use Cake\Http\Client;
use Cake\Utility\Hash;
use TeBo\Action\Action;
use TeBo\Action\Command\MessageCommandTrait;
use TeBo\Response\HtmlMessage;
use TeBo\Response\TextMessage;

class PokemonAction extends Action
{
    use MessageCommandTrait;

    public function description(): ?string
    {
        return __('Get information about a Pokémon');
    }

    public function execute(): void
    {
        $pokemonName = $this->getMessageCommand()->getArgument(0);

        if (!$pokemonName) {
            $this->getChat()->send(new TextMessage(__('Please provide a Pokémon name.')));
            return;
        }

        $pokemonData = $this->getPokemonData($pokemonName);

        if (isset($pokemonData['name'])) {
            $types = Hash::extract($pokemonData, 'types.{n}.type.name');
            $message = [
                'Name: ' . $pokemonData['name'],
                'Order: ' . $pokemonData['order'],
                'Types: ' . implode(', ', $types),
            ];
            $this->getChat()->send(new HtmlMessage($message));
        } else {
            $this->getChat()->send(new TextMessage(__('Pokémon not found.')));
        }
    }

    private function getPokemonData($pokemonName)
    {
        return Cache::remember('pokemon_' . $pokemonName, function () use ($pokemonName) {
            $url = "https://pokeapi.co/api/v2/pokemon-form/{$pokemonName}";
            $http = new Client();
            return $http->get($url)->getJson();
        });
    }
}

4.2 Register the Command

Add this command to your plugin configuration file (config/tebo.php):

return [
    'tebo.actions.command' => [
        'pokemon' => \App\TeBo\Action\PokemonAction::class,
    ],
];

This associates the pokemon command with the action you just created, you can add as many commands as you need.

4.3 Test the Command

Send the command /pokemon pikachu to your bot, and it should respond with details about Pikachu.

4.4 Customize the Response

You can make the response more engaging by including images or additional details:

if (isset($pokemonData['name'])) {
    $sprite = $pokemonData['sprites']['front_default'];
    $message = new \TeBo\Response\Photo($sprite, [
        'Name: ' . $pokemonData['name'],
        'Types: ' . implode(', ', $types),
    ]);
}

Step 5: Deploy the Bot to Production

For production, ensure your server is HTTPS-enabled, as Telegram requires secure webhooks. During development, you can use a tool like ngrok to temporarily expose your local server.

Update your .env file with your server’s domain:

export WEBHOOK_BASE="mydomain.com"

Make sure to test your bot thoroughly in the production environment.

Additional Resources

Conclusion

And that’s it! You’ve successfully integrated a Telegram bot into your CakePHP application. Your bot can now interact with users and provide useful information, like Pokémon details. TeBo makes it easy to add custom commands and manage user interactions. Feel free to explore and expand your bot with more features!

This article is part of the CakeDC Advent Calendar 2024 (December 9th 2024)

Back to all articles
We Bake with CakePHP