Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Telegram Bot Laravel Package

aymericcucherousset/telegram-bot

A simple PHP Telegram Bot library for sending messages, handling updates, and interacting with Telegram’s Bot API. Includes helpers for requests, webhooks/long polling, keyboards, and common methods to build bots quickly and cleanly.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require aymericcucherousset/telegram-bot
    

    Add the service provider to config/app.php:

    'providers' => [
        // ...
        AymericCucherousset\TelegramBot\TelegramBotServiceProvider::class,
    ],
    
  2. Configuration Publish the config file:

    php artisan vendor:publish --provider="AymericCucherousset\TelegramBot\TelegramBotServiceProvider"
    

    Update config/telegram-bot.php with your bot token and webhook URL:

    'token' => env('TELEGRAM_BOT_TOKEN'),
    'webhook_url' => env('APP_URL') . '/telegram/webhook',
    
  3. First Use Case: Basic Command Handling Define a command in a controller or service:

    use AymericCucherousset\TelegramBot\TelegramBot;
    
    class TelegramController extends Controller
    {
        public function handleCommand(TelegramBot $bot)
        {
            $bot->onCommand('start', function ($bot, $update) {
                $bot->sendMessage($update->getChat()->getId(), 'Welcome!');
            });
        }
    }
    

    Register the route in routes/web.php:

    Route::post('/telegram/webhook', [TelegramController::class, 'handleCommand']);
    

Implementation Patterns

Workflows

  1. Command-Based Interactions Use onCommand() to handle /start, /help, or custom commands:

    $bot->onCommand('custom', function ($bot, $update) {
        $bot->sendMessage($update->chat->id, 'Custom command triggered!');
    });
    
  2. Message Handling Listen for all messages (text, media, etc.) with onMessage():

    $bot->onMessage(function ($bot, $update) {
        $bot->sendMessage($update->message->chat->id, "You said: " . $update->message->text);
    });
    
  3. Inline Keyboards Create interactive buttons:

    $keyboard = [
        ['Yes', 'No'],
    ];
    $replyMarkup = $bot->replyKeyboardMarkup($keyboard, ['resize_keyboard' => true]);
    $bot->sendMessage($chatId, 'Choose:', $replyMarkup);
    
  4. Middleware for Authentication Use middleware to validate users before processing:

    $bot->onCommand('secure', function ($bot, $update) use ($middleware) {
        $middleware->authenticate($update->message->chat->id);
        $bot->sendMessage($update->chat->id, 'Access granted!');
    });
    
  5. Modular Design Split logic into services:

    // TelegramService.php
    class TelegramService {
        public function __construct(private TelegramBot $bot) {}
    
        public function handleOrderUpdate($chatId, $orderData) {
            $this->bot->sendMessage($chatId, "Order updated: " . $orderData);
        }
    }
    

Integration Tips

  • Laravel Events: Dispatch events for complex workflows:
    event(new OrderUpdated($orderData));
    
  • Queues: Offload heavy tasks:
    TelegramJob::dispatch($bot, $chatId, $data)->onQueue('telegram');
    
  • Logging: Log interactions for debugging:
    \Log::info('Telegram interaction', ['chat_id' => $update->chat->id, 'text' => $update->message->text]);
    

Gotchas and Tips

Pitfalls

  1. Webhook SSL Requirements Telegram requires HTTPS for webhooks. Use a reverse proxy (e.g., Nginx) or a service like ngrok for local testing:

    ngrok http 8000
    

    Update webhook_url to https://your-ngrok-url.ngrok.io/telegram/webhook.

  2. Rate Limits Avoid flooding Telegram’s API. Use delay() between messages:

    $bot->sendMessage($chatId, 'Message 1');
    sleep(1); // Respect rate limits
    $bot->sendMessage($chatId, 'Message 2');
    
  3. Update Handling Always validate updates to prevent malicious requests:

    if (!$update->validate()) {
        abort(403, 'Invalid update');
    }
    
  4. Session Management Store user sessions in the database or cache to persist state:

    $user = User::firstOrCreate(['telegram_id' => $update->message->chat->id]);
    

Debugging

  • Enable Debug Mode Set debug to true in config/telegram-bot.php to log raw updates:

    'debug' => env('APP_DEBUG', false),
    
  • Update Dumping Log raw updates for inspection:

    \Log::debug('Raw update:', $update->toArray());
    

Extension Points

  1. Custom Update Types Extend the Update class to handle custom payloads:

    class CustomUpdate extends \AymericCucherousset\TelegramBot\Update {
        public function getCustomData() { ... }
    }
    
  2. Middleware Create middleware for cross-cutting concerns (e.g., logging, auth):

    $bot->onMessage(function ($bot, $update) {
        $bot->middleware->run($update);
        // ...
    });
    
  3. Database Models Attach Telegram data to Eloquent models:

    class User extends Model {
        public function telegramUpdates() {
            return $this->hasMany(TelegramUpdate::class);
        }
    }
    
  4. Testing Use mocks for unit tests:

    $bot = Mockery::mock(TelegramBot::class);
    $bot->shouldReceive('sendMessage')->once();
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle