PHP code example of tbot / laravel

1. Go to this page and download the library: Download tbot/laravel 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/ */

    

tbot / laravel example snippets


// В коде бота
$bot = Bot::find(1);

// Получение токена
$token = $bot->token;

// Получение webhook URL
$webhookUrl = $bot->webhook_url;

// Проверка наличия токена
if ($bot->hasToken()) {
    // Бот имеет токен
}

// Проверка наличия webhook URL
if ($bot->hasWebhookUrl()) {
    // Бот имеет настроенный webhook
}

return [
    'multibot' => [
        'enabled' => true,
        'auto_create_classes' => true,
        'bots_path' => 'App\\Bots',
    ],
    
    'webhook' => [
        'base_url' => env('BOT_WEBHOOK_BASE_URL', env('APP_URL')),
        'auto_generate_secret' => true,
    ],
    
    'security' => [
        'webhook_secret' => env('BOT_WEBHOOK_SECRET'),
        'admin_ids' => array_filter(explode(',', env('BOT_ADMIN_IDS', ''))),
    ],
];

use Bot\Modules\I18nModule;

class MyBot extends LightBot
{
    use I18nModule;
    
    public function start()
    {
        // Автоматический перевод в sendSelf/sendOut
        $this->sendSelf('messages.welcome', [
            ['messages.button.start'],
            ['messages.button.help']
        ]);
    }
}

// Перевод с параметрами
$greeting = $this->translate('messages.user.greeting', ['name' => 'John']);

// Перевод массивов
$buttons = $this->translateArray([
    ['messages.button.start'],
    ['messages.button.help']
]);

// resources/lang/en/messages.php
return [
    'welcome' => 'Welcome to our bot!',
    'button' => [
        'start' => 'Start',
        'help' => 'Help',
    ],
    'user' => [
        'greeting' => 'Hello, :name!',
    ],
];



namespace App\Bots;

class MyBot extends AbstractBot
{
    public function main(): void
    {
        $this->commands();
        
        if ($this->hasMessageText() && $this->isMessageCommand()) {
            $this->handleCommand($this->getMessageText());
        }
    }

    public function commands(): void
    {
        $this->registerCommand('start', function () {
            $this->sendSelf('🎉 Привет! Я бот MyBot');
        }, [
            'description' => 'Запуск бота'
        ]);

        $this->registerCommand('help', function () {
            $this->sendSelf([
                '📋 Доступные команды:', 
                '', 
                '/start - Запуск бота', 
                '/help - Помощь'
            ]);
        }, [
            'description' => 'Помощь'
        ]);
    }
}
bash
php artisan bot:publish
bash
php artisan bot:publish --force
bash
php artisan bot:publish --tag=bot-config --force
bash
php artisan bot:publish --tag=bot-app --force
bash
php artisan migrate
bash
php artisan bot:new
bash
# Список всех ботов
php artisan bot:manage list

# Информация о конкретном боте
php artisan bot:manage show mybot

# Активация/деактивация бота
php artisan bot:manage enable mybot
php artisan bot:manage disable mybot

# Тестирование бота
php artisan bot:manage test mybot
bash
# Установка домена для окружения
php artisan bot:domain set mybot dev https://dev.example.com
php artisan bot:domain set mybot prod https://example.com

# Просмотр доменов бота
php artisan bot:domain show mybot

# Список всех доменов
php artisan bot:domain list
bash
# Настройка webhook (автоматически использует домен из БД)
php artisan bot:webhook set mybot

# Информация о webhook
php artisan bot:webhook info mybot

# Удаление webhook
php artisan bot:webhook delete mybot

# Тестирование webhook
php artisan bot:webhook test mybot
bash
# Публикация всех файлов
php artisan bot:publish

# Принудительное обновление всех файлов
php artisan bot:publish --force

# Обновление конкретных компонентов
php artisan bot:publish --tag=bot-config --force
php artisan bot:publish --tag=bot-app --force
php artisan bot:publish --tag=bot-routes --force
bash
# Проверка здоровья всех ботов
php artisan bot:health

# Статистика
php artisan bot:stats

# Конфигурация
php artisan bot:config show