Skip to content

Create your own commands

Valeriy Grechukha edited this page Oct 25, 2022 · 12 revisions

Before creating your custom commands, you have to install the PHP Telegram Bot library. Head over to the example-bot repository for basic installation instructions.


Step One

Create a folder where your custom commands will be living (e.g. Commands in the current (root) directory). Then add your custom commands path to the list of command locations in your hook.php or manager.php (depending on which method you are using):

// hook.php
...
// Define all paths for your custom commands in this array (leave as empty array if not used)
$commands_paths = [
    __DIR__ . '/Commands',
];
// Add this line inside the try{}
$telegram->addCommandsPaths($commands_paths);
...

// manager.php
...
'commands' => [
    // Define all paths for your custom commands
    'paths'   => [
        __DIR__ . '/Commands',
    ],
],
...

Step Two

Assume that we want to create a test command with usage /test.

Create a new .php file named TestCommand.php in your custom commands folder (that we added in Step One): ./Commands/TestCommand.php

NOTE: The first letter of the filename and the word "Command" must be in uppercase. All other letters are lower case (e.g. TestCommand.php, TestwithmultiplewordsCommand.php)

Step Three

Decide if the command you want to create is for all users or only admins.

  • User command: Command needs to belong to the UserCommands namespace and extend the UserCommand class.
  • Admin command: Command needs to belong to the AdminCommands namespace and extend the AdminCommand class.

First of all define namespace and use dependencies for the new command class in TestCommand.php file (our TestCommand should be available to all users, so it will belong to the UserCommands namespace):

namespace Longman\TelegramBot\Commands\UserCommands;

use Longman\TelegramBot\Commands\UserCommand;
use Longman\TelegramBot\Request;

Step Four

Now create a class named TestCommand (identical to your filename) that extends the UserCommand class:

class TestCommand extends UserCommand
{

Step Five

Define required properties:

    protected $name = 'test';                      // Your command's name
    protected $description = 'A command for test'; // Your command description
    protected $usage = '/test';                    // Usage of your command
    protected $version = '1.0.0';                  // Version of your command

Step Six

Every command must have a method called execute, which gets executed when your command is called. You can create your own methods inside your new command class, but you have to call them from within execute.

execute method:

    public function execute(): \Longman\TelegramBot\Entities\ServerResponse
    {
        $message = $this->getMessage();            // Get Message object

        $chat_id = $message->getChat()->getId();   // Get the current Chat ID

        $data = [                                  // Set up the new message data
            'chat_id' => $chat_id,                 // Set Chat ID to send the message to
            'text'    => 'This is just a Test...', // Set message to send
        ];

        return Request::sendMessage($data);        // Send message!
    }
}

Now the library will automatically find your new command and when a user types /test, the bot will answer with This is just a Test....

Conclusion

So as you can see, creating a custom command is very easy. For more complex commands, be sure to check out the example commands.

Here is the full TestCommand.php for reference:

<?php

namespace Longman\TelegramBot\Commands\UserCommands;

use Longman\TelegramBot\Commands\UserCommand;
use Longman\TelegramBot\Request;

class TestCommand extends UserCommand
{
    protected $name = 'test';                      // Your command's name
    protected $description = 'A command for test'; // Your command description
    protected $usage = '/test';                    // Usage of your command
    protected $version = '1.0.0';                  // Version of your command

    public function execute(): \Longman\TelegramBot\Entities\ServerResponse
    {
        $message = $this->getMessage();            // Get Message object

        $chat_id = $message->getChat()->getId();   // Get the current Chat ID

        $data = [                                  // Set up the new message data
            'chat_id' => $chat_id,                 // Set Chat ID to send the message to
            'text'    => 'This is just a Test...', // Set message to send
        ];

        return Request::sendMessage($data);        // Send message!
    }
}