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

andrew-gos/telegram-bot

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps to First Use

  1. Install the Package

    composer require andrew-gos/telegram-bot
    
  2. Configure Laravel Service Provider Create a service provider to initialize the bot:

    // app/Providers/TelegramBotServiceProvider.php
    namespace App\Providers;
    
    use AndrewGos\TelegramBot\TelegramBot;
    use Illuminate\Support\ServiceProvider;
    
    class TelegramBotServiceProvider extends ServiceProvider
    {
        public function register()
        {
            $this->app->singleton(TelegramBot::class, function ($app) {
                $bot = new TelegramBot(config('telegram.bot_token'));
                $bot->addHandlerGroup(new \AndrewGos\TelegramBot\Handler\HandlerGroup());
                return $bot;
            });
        }
    }
    

    Register it in config/app.php under providers.

  3. Set Up Basic Configuration Add to config/telegram.php:

    return [
        'bot_token' => env('TELEGRAM_BOT_TOKEN'),
        'webhook_url' => env('TELEGRAM_WEBHOOK_URL'),
    ];
    
  4. Create a Simple Command Handler

    // app/Handlers/StartCommandHandler.php
    namespace App\Handlers;
    
    use AndrewGos\TelegramBot\Handler\CommandHandler;
    use AndrewGos\TelegramBot\Types\Update;
    use AndrewGos\TelegramBot\Types\Message;
    
    class StartCommandHandler implements CommandHandler
    {
        public function handle(Update $update): void
        {
            $message = $update->getMessage();
            if ($message && $message->getText() === '/start') {
                $message->reply('Hello! I am your bot.');
            }
        }
    }
    
  5. Register the Handler

    // In your service provider's boot method
    public function boot()
    {
        $bot = $this->app->make(TelegramBot::class);
        $bot->getHandlerGroup()->addCommandHandler('/start', new StartCommandHandler());
    }
    
  6. Run the Bot For polling:

    php artisan telegram:bot
    

    Or set up a webhook in routes/web.php:

    Route::post('/telegram/webhook', function () {
        $bot = app(TelegramBot::class);
        $bot->processWebhookUpdate();
    });
    

Implementation Patterns

Core Workflows

1. Command Handling

  • Use CommandHandler for /command messages.
  • Example:
    $bot->getHandlerGroup()->addCommandHandler('/help', new HelpCommandHandler());
    

2. Message Handling

  • Use MessageHandler for text/callback queries.
  • Example:
    $bot->getHandlerGroup()->addMessageHandler(new TextMessageHandler());
    

3. Middleware Pipeline

  • Add middleware globally or per-handler:
    $bot->getMiddlewareStack()->add(new LoggingMiddleware());
    $bot->getHandlerGroup()->addMiddleware('/start', new AuthMiddleware());
    

4. Webhook vs. Polling

  • Polling: Use TelegramBot::run() in a Laravel command.
  • Webhook: Configure in TelegramBot constructor:
    $bot = new TelegramBot(config('telegram.bot_token'), null, null, config('telegram.webhook_url'));
    

5. Async Processing with Queues

  • Dispatch updates to Laravel queues:
    $bot->getHandlerGroup()->addUpdateHandler(new QueuedUpdateHandler());
    
  • Create a job:
    // app/Jobs/ProcessTelegramUpdate.php
    public function handle()
    {
        $bot = app(TelegramBot::class);
        $bot->processUpdate($this->update);
    }
    

Integration Tips

Laravel-Specific Patterns

  • Service Container Binding: Bind the bot to Laravel’s container for dependency injection:

    $this->app->bind(TelegramBot::class, function ($app) {
        return new TelegramBot(config('telegram.bot_token'));
    });
    
  • Event Dispatching: Trigger Laravel events from handlers:

    // In a handler
    event(new TelegramMessageReceived($message));
    
  • Middleware Integration: Reuse Laravel middleware in bot middleware:

    use Illuminate\Http\Middleware\ThrottleRequests;
    
    $bot->getMiddlewareStack()->add(new class extends ThrottleRequests {
        protected function handle($request, Closure $next)
        {
            // Custom logic
            return $next($request);
        }
    });
    
  • Artisan Commands: Create a command to manage the bot:

    // app/Console/Commands/RunTelegramBot.php
    public function handle()
    {
        $bot = app(TelegramBot::class);
        $bot->run();
    }
    

Advanced Patterns

  • Dynamic Handler Registration: Register handlers dynamically based on config:

    foreach (config('telegram.handlers') as $command => $handler) {
        $bot->getHandlerGroup()->addCommandHandler($command, new $handler());
    }
    
  • Plugin System: Extend the bot with plugins:

    // app/Plugins/AnalyticsPlugin.php
    class AnalyticsPlugin
    {
        public function register(TelegramBot $bot)
        {
            $bot->getMiddlewareStack()->add(new AnalyticsMiddleware());
        }
    }
    
  • Testing: Mock the bot in tests:

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

Gotchas and Tips

Pitfalls

  1. Strict Typing Quirks:

    • The library uses PHP 8.2+ strict types. Ensure your handlers implement the correct interfaces (e.g., CommandHandler, MessageHandler).
    • Fix: Use implements and IDE autocompletion to avoid runtime errors.
  2. Webhook Configuration:

    • Forgetting to set the webhook URL or verify the bot token can cause silent failures.
    • Fix: Use Laravel’s env() and validate in the service provider:
      if (!config('telegram.webhook_url')) {
          throw new \RuntimeException('Webhook URL not configured.');
      }
      
  3. Middleware Order:

    • Middleware runs in the order they are added. Auth middleware should run before handlers.
    • Fix: Add middleware early in the pipeline:
      $bot->getMiddlewareStack()->prepend(new AuthMiddleware());
      
  4. Update Processing Delays:

    • Polling may miss updates if the bot is offline. Webhooks are more reliable but require HTTPS.
    • Fix: Use Laravel’s queue system for async processing:
      $bot->getHandlerGroup()->addUpdateHandler(new QueuedUpdateHandler());
      
  5. Dependency Conflicts:

    • The library’s andrew-gos/serializer may conflict with Laravel’s symfony/serializer.
    • Fix: Use Composer’s replace:
      "replace": {
          "andrew-gos/serializer": "symfony/serializer"
      }
      
  6. Error Handling:

    • Uncaught exceptions in handlers can crash the bot. Use middleware to catch and log errors:
      $bot->getMiddlewareStack()->add(new ErrorHandlingMiddleware());
      

Debugging Tips

  1. Enable Debug Logging:

    $bot->setLogger(new \Monolog\Logger('telegram', [
        new \Monolog\Handler\StreamHandler(storage_path('logs/telegram.log'))
    ]));
    
  2. Inspect Updates: Use a middleware to log raw updates:

    $bot->getMiddlewareStack()->add(new class {
        public function __invoke($update, Closure $next)
        {
            \Log::debug('Raw update:', $update->toArray());
            return $next($update);
        }
    });
    
  3. Test Locally: Use ngrok to expose a local webhook for testing:

    ngrok http 8000
    

    Set the webhook URL to https://your-ngrok-url.ngrok.io/telegram/webhook.

  4. Validate API Responses: Telegram’s API may return unexpected data. Use a middleware to validate responses:

    $bot->getMiddlewareStack()->add(new class {
        public function __invoke($response, Closure $next)
        {
            if (!$response->isOk()) {
                throw new \RuntimeException('API error: ' . $response->getDescription());
            }
            return $next($response);
        }
    });
    

Extension Points

  1. Custom Checkers: Extend Checker to validate updates:
    class AdminChecker implements Checker
    {
        public function check(Update $update):
    
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor