PHP code example of php-brasil / telegram

1. Go to this page and download the library: Download php-brasil/telegram library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

php-brasil / telegram example snippets


use PhpBrasil\Telegram\Bot;

$telegram = new Bot(env('BOT_TOKEN'));

$input = File::read('php://input');
$body = JSON::decode($input, true);

$telegram = new Bot(environment('APP_TOKEN'));

if (environment('APP_DEBUG')) {
    $telegram->info(
        get($body, 'message.message_id'),
        $body
    );
}

$bot->on('text', '^Hello|^Hi', function($bot, $match) {
    $message = $match->get('$message');
    $chatId = get($message, 'chat.id');
    /** @var Bot $bot */
    return $bot->apiRequest(
        'sendMessage', ['chat_id' => $chatId, "text" => 'Nice to meet you']
    );
});

$input = File::read('php://input');
$body = JSON::decode($input, true);

// add actions to bot
$bot->text(/* regex over message */, /* callable */);
$bot->text(/* regex over message */, /* callable */);

// apply the actions
$telegram->handleText($body);

$bot->text('/start', Start::class);

/**
 * Class Start
 */
class Start
{
    /**
     * @param Bot $bot
     * @param Match $match
     * @param array $message
     * @throws Exception
     * @SuppressWarnings(Unused)
     */
    function __invoke($bot, $match, $message)
    {
        $chatId = get($message, 'chat.id');
        $parameters = [
            'chat_id' => $chatId,
            "text" => 'Hello',
            'reply_markup' => ['keyboard' => [['Hello', 'Hi']], 'one_time_keyboard' => true, 'resize_keyboard' => true]
        ];
        $bot->answer($parameters);
    }
}

$telegram->actions(dirname(__DIR__) . '/actions/text.php');



use App\Actions\OtherWise;
use App\Telegram\Bot;

return function (Bot $bot) {
    $bot->text('.*', OtherWise::class);
};

$bot->text('^Hello|^Hi', function($bot) {
    return $bot->reply('Nice to meet you');
});

$bot->text('How much is (?<n1>.*) \+ (?<n2>.*)\?', function (Bot $bot, Match $match) {
    $parameters = $match->get('$parameters');
    if (count($parameters) !== 2) {
        return $bot->reply('Can`t resolve this math');
    }
    $sum = get($parameters, 'n1') + get($parameters, 'n2');
    return $bot->reply("That is easy, the answer is `{$sum}`");
});