PHPackages                             mateodioev/tg-handler - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. mateodioev/tg-handler

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

mateodioev/tg-handler
=====================

Library for created telegram bots more easy

v5.12.2(1y ago)23351MITPHPPHP &gt;=8.1

Since Aug 22Pushed 1mo ago2 watchersCompare

[ Source](https://github.com/Mateodioev/telegram-bot-handler)[ Packagist](https://packagist.org/packages/mateodioev/tg-handler)[ RSS](/packages/mateodioev-tg-handler/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (10)Dependencies (11)Versions (93)Used By (0)

Telegram bot handler
====================

[](#telegram-bot-handler)

[![CodeFactor](https://camo.githubusercontent.com/fec9ef157c865d7b632b38734429e0f4f4dc9de0854443fe48d4b7eb821cf7d2/68747470733a2f2f7777772e636f6465666163746f722e696f2f7265706f7369746f72792f6769746875622f6d6174656f64696f65762f74656c656772616d2d626f742d68616e646c65722f6261646765)](https://www.codefactor.io/repository/github/mateodioev/telegram-bot-handler)

Documentation
-------------

[](#documentation)

Installation
------------

[](#installation)

```
composer require mateodioev/tg-handler:"~5.3"
```

```
use Mateodioev\TgHandler\Bot;
```

Usage
-----

[](#usage)

Create new instance and add your command

```
$bot = new Bot($botToken);

$bot->onEvent(YourCommandInstance);

$bot->byWebhook();
// or
$bot->longPolling($timeout); // No needs server with ssl
```

### Creating new command instance

[](#creating-new-command-instance)

All text commands need to extend `Mateodioev\TgHandler\Commands\MessageCommand` class, and put the logic in the method `handle`.

```
use Mateodioev\TgHandler\Commands\MessageCommand;
use Mateodioev\Bots\Telegram\Api;
use Mateodioev\TgHandler\Context;

class MyCommand extends MessageCommand
{
    protected string $name = 'start';
    protected string $description = 'Start the bot';

    public function execute(array $args = []){
         $this->api()->sendMessage($this->ctx()->getChatId(), 'Hello!!!');
    }
}

$bot->onEvent(MyCommand::get());
```

This command works with `/start any text here` or `/start`. If you need another prefixes (/, !) you can add with method `addPrefix` or with property `prefix`

```
class MyCommand extends MessageCommand
{
    protected string $name = 'start';
    protected string $description = 'Start the bot';
    protected array $prefix = ['/', '!'];

    // Additionally you can add command aliases
    protected array $alias = ['help'];

    ...
}

// or
$myCommand = MyCommand::get();
$myCommand->setPrefixes(['/', '!']); // Set prefix, no need to set `$prefix` property
```

### Using middlewares

[](#using-middlewares)

You can add middlewares to your command. Middlewares will be executed before the command. All middlewares results will be passed to the command as an array with the name of the middleware as a key.

For example, you can create a middleware that will check if the user is authorized, and if not, the command will not be executed.

```
class MyCommand extends MessageCommand
{
    protected string $name = 'start';
    protected string $description = 'Start the bot';
    protected array $middlewares = [
        AuthUserMiddleware::class,
    ];

    public function execute(array $args = []){
        $authenticatedUser = $args[AuthUserMiddleware::class];
    }
}
$cmd = MyCommand::get();
$cmd->addMiddleware(new AuthUserMiddleware); // This works too

// Your middleware definition
class AuthUserMiddleware extends \Mateodioev\TgHandler\Middleware\Middleware
{
    public function __invoke(\Mateodioev\TgHandler\Context $ctx,\Mateodioev\Bots\Telegram\Api $api, array $args = [])****{
        $user = User::find($ctx->getUserId());
        if (!$user) {
            $bot->replyTo($ctx->getChatId(), 'You are not authorized', $ctx->getMessageId())
            throw new \Mateodioev\TgHandler\Commands\StopCommand(); // Stop command execution
        }
        return $user;
    }
}
```

> You can use `StopCommand` exception to stop command execution

### Using filters

[](#using-filters)

Now you can set custom filters to you event for validate, all filters need to extends the interface `Mateodioev\TgHandler\Filters\Filter`

```
use Mateodioev\Bots\Telegram\Api;
use Mateodioev\TgHandler\Context;

[\Mateodioev\TgHandler\Filters\FilterFromUserId(996202950)];
class FilterCommand extends \Mateodioev\TgHandler\Commands\MessageCommand
{
    protected string $name = 'filter';

    public function execute(array $args = []) {
        // TODO: Implement execute() method.
    }
}
```

Now this command only respond to the user ID `996202950`

#### Using multiple filters

[](#using-multiple-filters)

```
use Mateodioev\TgHandler\Events\Types\MessageEvent;
use Mateodioev\TgHandler\Filters\{FilterCollection, FilterMessageChat, FilterMessageRegex};

#[FilterMessageChat(TestChat::CHAT_ID), FilterMessageRegex('/.*(filters).*/i')]
class TestChat extends MessageEvent {
    const CHAT_ID = 1111111111111;
    public function execute(array $args = []) {
        // your logic here
    }
}
```

If your filters cannot be validated you must implement the `Mateodioev\TgHandler\Commands\Command::onInvalidFilters` method, this method must return true. This is optional

```
