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 Begin

  1. Install the Package

    composer require andrew-gos/telegram-bot
    

    Ensure your project uses PHP 8.2+ and has ext-curl enabled.

  2. Create a Bot Instance

    use AndrewGos\TelegramBot\Bot;
    use AndrewGos\TelegramBot\Client\TelegramClient;
    
    $client = new TelegramClient('YOUR_BOT_TOKEN');
    $bot = new Bot($client);
    
  3. Handle Updates (Basic Command)

    use AndrewGos\TelegramBot\Handler\CommandHandler;
    use AndrewGos\TelegramBot\Update\CommandUpdate;
    
    $bot->getHandlerGroup()
        ->addHandler(new CommandHandler('/start', function (CommandUpdate $update) {
            $update->getMessage()->reply('Hello!');
        }));
    
  4. Run the Bot

    $bot->run();
    

    For production, use a webhook or long-polling (see BASIC.md).


First Use Case: Command-Based Bot

  • Scenario: A bot that responds to /start, /help, and custom commands.
  • Implementation:
    $bot->getHandlerGroup()
        ->addHandler(new CommandHandler('/start', fn($update) => $update->reply('Welcome!')))
        ->addHandler(new CommandHandler('/help', fn($update) => $update->reply('Type /start to begin.')));
    
  • Key Files to Reference:

Implementation Patterns

Core Workflow: Update Processing

  1. Register Handlers Use HandlerGroup to organize handlers by priority or type:

    $group = $bot->getHandlerGroup();
    $group->addHandler(new CommandHandler('/echo', fn($update) => $update->reply($update->getMessage()->getText())));
    $group->addHandler(new TextHandler('ping', fn($update) => $update->reply('pong!')));
    
  2. Middleware Pipeline Intercept or modify updates before/after handlers:

    $bot->getMiddleware()->add(new LoggingMiddleware());
    $bot->getMiddleware()->add(new RateLimitMiddleware(10)); // Example custom middleware
    
    • Common Middleware Use Cases:
      • Logging (Psr\Log\LoggerInterface integration).
      • Rate limiting (e.g., Symfony\RateLimiter).
      • Authentication (e.g., restrict commands to admins).
  3. Framework Integration

    • Laravel Example: Bind the bot as a service in AppServiceProvider:
      $this->app->singleton(Bot::class, fn($app) => new Bot(
          new TelegramClient(config('telegram.bot_token'))
      ));
      
      Use dependency injection in controllers:
      public function handleUpdate(Bot $bot) {
          $bot->run(); // Process updates via webhook/long-polling
      }
      
  4. Plugins for Reusability Encapsulate logic (e.g., database integration, analytics) as plugins:

    class DatabasePlugin implements PluginInterface {
        public function __invoke(Bot $bot): void {
            $bot->getMiddleware()->add(new DatabaseLoggingMiddleware());
        }
    }
    $bot->addPlugin(new DatabasePlugin());
    

Integration Tips

  • Webhook Setup: Configure Telegram’s webhook URL in your Laravel routes:

    Route::post('/telegram-webhook', function (Request $request, Bot $bot) {
        $bot->processUpdate($request->getContent());
    });
    

    Use TelegramClient::setWebhook() for dynamic updates.

  • Async Processing: Offload heavy tasks (e.g., sending media) to queues:

    $bot->getMiddleware()->add(new QueueMiddleware(new LaravelQueue()));
    
  • Testing: Mock TelegramClient and Update objects:

    $mockClient = $this->createMock(TelegramClient::class);
    $bot = new Bot($mockClient);
    $bot->getHandlerGroup()->addHandler(new CommandHandler('/test', fn($update) => $update->reply('test')));
    

Gotchas and Tips

Pitfalls

  1. Strict Typing Quirks

    • Issue: Forgetting to type-hint Update objects (e.g., CommandUpdate vs. MessageUpdate) causes runtime errors.
    • Fix: Use instanceof checks or generic Update handlers with Update::getType():
      $bot->getHandlerGroup()->addHandler(new Handler(
          fn($update) => $update instanceof CommandUpdate && $update->getCommand() === '/start',
          fn($update) => $update->reply('Start!')
      ));
      
  2. Webhook Delays

    • Issue: Telegram may retry failed webhook requests. Unhandled exceptions crash the bot.
    • Fix: Wrap run() in a try-catch and log errors:
      try {
          $bot->run();
      } catch (Exception $e) {
          Log::error('Telegram bot error: ' . $e->getMessage());
      }
      
  3. Middleware Order Matters

    • Issue: Middleware runs in registration order. A LoggingMiddleware after a RateLimitMiddleware won’t log rate-limited requests.
    • Fix: Register middleware in reverse order of execution:
      $bot->getMiddleware()->add(new RateLimitMiddleware());
      $bot->getMiddleware()->add(new LoggingMiddleware());
      
  4. Long-Polling Timeouts

    • Issue: Long-polling (getUpdates) may time out if the bot is idle.
    • Fix: Use webhooks for production or set a low timeout in TelegramClient:
      $client = new TelegramClient('TOKEN', 30); // 30-second timeout
      

Debugging Tips

  1. Enable Verbose Logging Inject a Psr\Log\LoggerInterface into TelegramClient:

    $client = new TelegramClient('TOKEN', null, null, new MonologLogger());
    
  2. Inspect Raw Updates Dump raw JSON from Telegram to debug:

    $bot->getMiddleware()->add(new HandlerMiddleware(
        fn($update) => Log::debug('Raw update:', $update->jsonSerialize())
    ));
    
  3. Test Locally with getUpdates Use long-polling for development:

    $client->setWebhook(false); // Disable webhook
    $updates = $client->getUpdates(); // Manually fetch updates
    

Extension Points

  1. Custom Update Types Extend Update for domain-specific logic:

    class CustomUpdate extends Update {
        public function getCustomData(): array {
            return $this->data['custom_field'] ?? [];
        }
    }
    
  2. Dynamic Handlers Register handlers at runtime (e.g., from a database):

    $commands = Command::all();
    foreach ($commands as $cmd) {
        $bot->getHandlerGroup()->addHandler(new CommandHandler(
            $cmd->slug,
            fn($update) => $update->reply($cmd->response)
        ));
    }
    
  3. PSR-15 Middleware Implement Psr\Http\Server\MiddlewareInterface for HTTP-based middleware:

    class AuthMiddleware implements MiddlewareInterface {
        public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface {
            if (!$request->getQueryParams()['auth']) {
                return new Response('Unauthorized', 403);
            }
            return $handler->handle($request);
        }
    }
    
  4. Event Dispatching Use Psr\EventDispatcher\EventDispatcherInterface to trigger events:

    $bot->getEventDispatcher()->dispatch(new UpdateReceivedEvent($update));
    

Config Quirks

  • Default Timeout: TelegramClient uses a 60-second timeout for getUpdates. Adjust via constructor:
    $client = new TelegramClient('TOKEN', 5); // 5-second timeout
    
  • Webhook Certificates: If using HTTPS, ensure your server’s certificate is valid. Telegram rejects invalid certs.
  • Rate Limits: Telegram enforces rate limits. Handle 429 Too Many Requests in middleware:
    $bot->getMiddleware()->add(new RetryMiddleware());
    
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.
nasirkhan/laravel-sharekit
directorytree/privacy-filter-classifier
directorytree/privacy-filter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity
testo/bridge-symfony