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 Bundle Laravel Package

egormanakin/telegram-bot-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require boshurik/telegram-bot-bundle
    

    Ensure TELEGRAM_BOT_TOKEN is set in your environment (e.g., .env).

  2. Register the Bundle: Add new BoShurik\TelegramBotBundle\BoShurikTelegramBotBundle to app/AppKernel.php (or config/bundles.php for Symfony 4+).

  3. Configure Routing: Add the webhook route in config/routes.yaml:

    BoShurikTelegramBotBundle:
        resource: "@BoShurikTelegramBotBundle/Resources/config/routing.yml"
        prefix: /_telegram/<your-secret-key>
    
  4. Basic Configuration: Define the bot token and optional proxy in config/packages/boshurik_telegram_bot.yaml:

    boshurik_telegram_bot:
        api:
            token: "%env(TELEGRAM_BOT_TOKEN)%"
            proxy: "socks5://127.0.0.1:8888" # Optional
    
  5. First Use Case: Use the BotApi to send a test message:

    use TelegramBot\Api\BotApi;
    
    $api = $this->container->get(BotApi::class);
    $api->sendMessage([
        'chat_id' => '123456789',
        'text' => 'Hello from Laravel!',
    ]);
    

Implementation Patterns

Core Workflows

  1. Polling Updates (Development/Testing): Use the CLI command to fetch updates locally:

    bin/console telegram:updates
    

    Ideal for testing without configuring webhooks.

  2. Webhook Setup (Production):

    • Set the webhook URL (e.g., https://yourdomain.com/_telegram/secret-key):
      bin/console telegram:webhook:set https://yourdomain.com/_telegram/secret-key [path/to/cert.pem]
      
    • Ensure your server has a valid SSL certificate (Telegram requires HTTPS).
    • Use a reverse proxy (e.g., Nginx) to route /_telegram/secret-key to your Laravel app.
  3. Handling Updates:

    • Extend the UpdateHandler service to process incoming updates:
      // src/Service/TelegramUpdateHandler.php
      namespace App\Service;
      
      use BoShurik\TelegramBotBundle\Event\UpdateEvent;
      use Symfony\Component\EventDispatcher\EventSubscriberInterface;
      
      class TelegramUpdateHandler implements EventSubscriberInterface
      {
          public static function getSubscribedEvents()
          {
              return [
                  'telegram.update' => 'onUpdate',
              ];
          }
      
          public function onUpdate(UpdateEvent $event)
          {
              $update = $event->getUpdate();
              if (isset($update['message']['text'])) {
                  $text = $update['message']['text'];
                  $chatId = $update['message']['chat']['id'];
      
                  $api = $this->container->get(BotApi::class);
                  $api->sendMessage([
                      'chat_id' => $chatId,
                      'text' => "You said: {$text}",
                  ]);
              }
          }
      }
      
    • Register the handler as a service in config/services.yaml:
      services:
          App\Service\TelegramUpdateHandler:
              tags: ['telegram.update_handler']
      
  4. Sending Rich Content: Leverage the underlying telegram-bot/api library for advanced features:

    $api->sendPhoto([
        'chat_id' => '123456789',
        'photo' => 'https://example.com/image.jpg',
        'caption' => 'Check this out!',
    ]);
    
    $api->sendDocument([
        'chat_id' => '123456789',
        'document' => 'https://example.com/file.pdf',
    ]);
    
  5. Command-Line Interaction: Use the BotApi in console commands for admin tasks:

    // src/Command/SendBroadcastCommand.php
    namespace App\Command;
    
    use Symfony\Component\Console\Command\Command;
    use Symfony\Component\Console\Input\InputInterface;
    use Symfony\Component\Console\Output\OutputInterface;
    use TelegramBot\Api\BotApi;
    
    class SendBroadcastCommand extends Command
    {
        protected static $defaultName = 'telegram:broadcast';
    
        protected function execute(InputInterface $input, OutputInterface $output)
        {
            $api = $this->getContainer()->get(BotApi::class);
            $api->sendMessage([
                'chat_id' => '@your_channel_username',
                'text' => 'Broadcast message!',
                'parse_mode' => 'Markdown',
            ]);
            $output->writeln('Message broadcasted!');
        }
    }
    

Gotchas and Tips

Pitfalls

  1. Webhook SSL Requirements:

    • Telegram requires HTTPS for webhooks. Use a valid certificate (e.g., Let’s Encrypt) or a tool like ngrok for local testing.
    • If using a self-signed certificate, Telegram will reject the webhook. Always test with a publicly trusted certificate.
  2. Secret Key Exposure:

    • The webhook prefix (/_telegram/<your-secret-key>) should not be guessable. Use a strong, random string (e.g., 32-character UUID).
    • Avoid hardcoding secrets in routes; use environment variables or Symfony’s parameter bag.
  3. Update Handling Race Conditions:

    • If multiple handlers process the same update, ensure idempotency (e.g., by storing processed update IDs in a database).
    • Example:
      // In your UpdateHandler
      $updateId = $update['update_id'];
      if (!$this->updateRepository->exists($updateId)) {
          $this->updateRepository->save($updateId);
          // Process update...
      }
      
  4. Rate Limits:

    • Telegram enforces rate limits. Handle TelegramBot\Api\Exceptions\TelegramException gracefully:
      try {
          $api->sendMessage([...]);
      } catch (TelegramException $e) {
          $this->logger->error('Telegram API error: ' . $e->getMessage());
          // Implement retry logic or queue the message
      }
      
  5. Proxy Configuration:

    • If using a proxy (e.g., socks5://), ensure it’s stable. Proxy failures will break all API calls.
    • Test proxy connectivity separately:
      curl --proxy socks5://127.0.0.1:8888 https://api.telegram.org/bot<token>/getMe
      

Debugging Tips

  1. Log Updates: Enable debug mode in config/packages/boshurik_telegram_bot.yaml:

    boshurik_telegram_bot:
        debug: true
    

    This logs raw updates to var/log/dev.log.

  2. Webhook Verification:

    • Use telegram:webhook:set with verbose output:
      bin/console telegram:webhook:set https://yourdomain.com/_telegram/secret-key --verbose
      
    • Check Telegram’s webhook status endpoint.
  3. Update Validation:

    • Validate incoming updates in your handler to avoid malicious payloads:
      public function onUpdate(UpdateEvent $event)
      {
          $update = $event->getUpdate();
          if (!isset($update['update_id']) || !is_numeric($update['update_id'])) {
              throw new \RuntimeException('Invalid update payload');
          }
          // Process update...
      }
      
  4. Environment-Specific Config:

    • Use separate configs for dev and prod (e.g., config/packages/boshurik_telegram_bot{dev,prod}.yaml):
      # config/packages/boshurik_telegram_botdev.yaml
      boshurik_telegram_bot:
          api:
              token: "%env(TELEGRAM_BOT_TOKEN_DEV)%"
              debug: true
      

Extension Points

  1. Custom Update Types: Extend the bundle to handle non-standard update types (e.g., custom games or payments):
    // src/EventListener/CustomUpdateListener.php
    use BoShurik\TelegramBotBundle\Event\UpdateEvent;
    
    class CustomUpdateListener
    {
        public function onUpdate(UpdateEvent $event)
        {
            if (isset($event->getUpdate()['custom_game'])) {
                // Handle custom game logic
            }
        }
    }
    
    Register the listener in services.yaml:
    services:
        App\EventListener\CustomUpdateListener:
    
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.
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
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope
anil/file-picker
broqit/fields-ai