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

andrew-gos/telegram-bot-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Bundle

    composer require andrew-gos/telegram-bot-bundle
    

    The bundle auto-enables via Symfony Flex.

  2. Configure a Bot Add a minimal config to config/packages/andrew_gos_telegram_bot.yaml:

    andrew_gos_telegram_bot:
        bots:
            my_bot:
                factory:
                    method: 'getUpdates'  # or 'default' for webhooks
                    arguments:
                        $token: '%env(TELEGRAM_BOT_TOKEN)%'
                handlers:
                    - handler: App\Telegram\Handler\DefaultMessageHandler
    
  3. Define a Handler Create a basic handler (e.g., app/Telegram/Handler/DefaultMessageHandler.php):

    use AndrewGos\TelegramBot\Kernel\Handler\HandlerInterface;
    use AndrewGos\TelegramBot\Entity\Update;
    use AndrewGos\TelegramBot\Telegram;
    
    class DefaultMessageHandler implements HandlerInterface {
        public function handle(Update $update, Telegram $telegram): void {
            $telegram->getApi()->sendMessage(
                $update->getMessage()->getChat()->getId(),
                'Hello!'
            );
        }
    }
    
  4. Run the Bot Start long-polling:

    php bin/console andrew-gos:telegram-bot:listen my_bot
    

Implementation Patterns

Core Workflow

  1. Update Processing Pipeline

    • PluginsCheckerMiddlewaresHandler (executed in priority order).
    • Use CheckerInterface to filter updates (e.g., /start command, media types).
    • Chain MiddlewareInterface for cross-cutting logic (e.g., auth, logging).
  2. Bot Lifecycle

    • Development: Use getUpdates (long-polling) for testing.
    • Production: Deploy with webhooks (default factory) for scalability.
    • Toggle between modes via config:
      factory:
          method: 'default'  # Webhook
          arguments:
              $token: '%env(TOKEN)%'
              $webhookUrl: '%env(WEBHOOK_URL)%'
      
  3. Service Organization

    • Checkers: Group logic (e.g., CommandChecker, MediaTypeChecker).
    • Handlers: Implement HandlerInterface for bot responses.
    • Plugins: Global logic (e.g., RequestLoggerPlugin).
    • Middlewares: Pre/post-processing (e.g., UserAuthMiddleware).
  4. Configuration-Driven Routing Leverage priority to control handler execution order:

    handlers:
        - checker: App\Checker\AdminCommandChecker
          handler: App\Handler\AdminHandler
          priority: 100  # Highest priority
        - handler: App\Handler\FallbackHandler
          priority: -100 # Lowest priority
    

Integration Tips

  • Symfony Events: Dispatch custom events in handlers/plugins:
    $this->eventDispatcher->dispatch(new TelegramUpdateEvent($update));
    
  • Dependency Injection: Inject services (e.g., UserRepository) into handlers.
  • Testing: Mock Telegram and Update objects for unit tests:
    $update = new Update([...]);
    $handler = new MyHandler();
    $handler->handle($update, $this->createMock(Telegram::class));
    

Gotchas and Tips

Common Pitfalls

  1. Webhook HTTPS Requirement

    • Telegram mandates HTTPS for webhooks. Use a reverse proxy (e.g., Nginx) or local tools like ngrok during development.
    • Debug with:
      php bin/console andrew-gos:telegram-bot:set-webhook my_bot https://your-domain.com/webhook
      
  2. Long-Polling Timeouts

    • Long-polling (getUpdates) may fail if the script runs too long. Use pcntl for background processes or deploy as a systemd service.
  3. Checker Logic Errors

    • Ensure CheckerInterface::check() returns bool. Non-boolean values may cause silent failures.
    • Test checkers with edge cases (e.g., null updates).
  4. Priority Collisions

    • Handlers with the same priority execute in arbitrary order. Use distinct values (e.g., 100, 50, -50).
  5. Token Validation

    • Always validate tokens via:
      php bin/console andrew-gos:telegram-bot:bot-info my_bot
      
    • Invalid tokens cause silent failures in production.

Debugging Tips

  • Log Updates: Use the RequestLoggerPlugin to inspect raw Telegram updates:
    plugins:
        - class: App\Telegram\Plugin\RequestLoggerPlugin
          arguments:
              $logger: '@monolog.logger.telegram'
    
  • Console Commands: Verify bot status with:
    php bin/console andrew-gos:telegram-bot:webhook-info my_bot
    
  • Strict Typing: Leverage PHPStan for early detection of type mismatches in handlers/checkers.

Extension Points

  1. Custom Factories Extend the TelegramFactoryInterface for non-standard bot setups (e.g., multi-account bots).

  2. Dynamic Handlers Register handlers dynamically via Symfony’s container events:

    $container->register('dynamic.handler', DynamicHandler::class);
    
  3. Plugin Middleware Combine plugins and middlewares for layered processing:

    plugins:
        - App\Plugin\AuthPlugin
    handlers:
        - middlewares:
            - App\Middleware\RateLimitMiddleware
          handler: App\Handler\CoreHandler
    
  4. Event Subscribers Listen to TelegramUpdateEvent for cross-bot logic:

    use Symfony\Component\EventDispatcher\EventSubscriberInterface;
    
    class TelegramEventSubscriber implements EventSubscriberInterface {
        public static function getSubscribedEvents() {
            return [TelegramUpdateEvent::class => 'onUpdate'];
        }
        public function onUpdate(TelegramUpdateEvent $event) { ... }
    }
    

Configuration Quirks

  • Environment Variables: Always use %env() for tokens to avoid hardcoding:
    arguments:
        $token: '%env(TELEGRAM_BOT_TOKEN)%'
    
  • YAML Anchors: Reuse configurations with anchors (e.g., shared plugins):
    andrew_gos_telegram_bot:
        plugins:
            &logger_plugin
            class: App\Plugin\RequestLoggerPlugin
            arguments:
                $logger: '@monolog.logger.telegram'
        bots:
            bot1:
                plugins: [*logger_plugin]
            bot2:
                plugins: [*logger_plugin]
    
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui