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

baks-dev/telegram

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:
    composer require baks-dev/telegram
    
  2. Publish Config (if needed):
    php artisan vendor:publish --provider="BaksDev\Telegram\TelegramServiceProvider" --tag="telegram-config"
    
    • Locate config at config/telegram.php (default: BOT_TOKEN and WEBHOOK_URL).
  3. First Use Case:
    use BaksDev\Telegram\Telegram;
    
    $telegram = app(Telegram::class);
    $response = $telegram->sendMessage([
        'chat_id' => -100123456789,
        'text' => 'Hello from Laravel!',
    ]);
    

Key Files to Review

  • config/telegram.php: Bot token, webhook settings, and API defaults.
  • app/Providers/TelegramServiceProvider.php: Service binding and boot logic.
  • src/Telegram.php: Core API client methods.

Implementation Patterns

Core Workflows

1. Sending Messages

  • Basic Text Message:
    $telegram->sendMessage([
        'chat_id' => $userChatId,
        'text' => 'Your order #123 is processing.',
        'parse_mode' => 'HTML', // Optional
    ]);
    
  • Rich Media:
    $telegram->sendPhoto([
        'chat_id' => $chatId,
        'photo' => 'https://example.com/image.jpg',
        'caption' => 'Check this out!',
    ]);
    

2. Handling Webhooks

  • Register Webhook (in a service provider or route):
    $telegram->setWebhook([
        'url' => route('telegram.webhook'),
        'max_connections' => 40,
    ]);
    
  • Update Handler (Laravel route):
    Route::post('/telegram/webhook', function (Request $request) {
        $update = $request->json()->all();
        $telegram = app(Telegram::class);
        $telegram->handleUpdate($update); // Built-in handler
        // OR custom logic:
        // if ($update['message']['text'] === '/start') { ... }
    });
    

3. Bot Commands

  • Set MyCommand:
    $telegram->setMyCommands([
        ['command' => 'start', 'description' => 'Start the bot'],
        ['command' => 'help', 'description' => 'Get help'],
    ]);
    

4. Inline Keyboards

  • Dynamic Buttons:
    $keyboard = [
        ['text' => 'Option 1', 'callback_data' => 'opt1'],
        ['text' => 'Option 2', 'callback_data' => 'opt2'],
    ];
    $telegram->sendMessage([
        'chat_id' => $chatId,
        'text' => 'Choose:',
        'reply_markup' => json_encode(['inline_keyboard' => $keyboard]),
    ]);
    

5. Async Polling (Fallback)

  • Poll Updates (if webhooks fail):
    $telegram->getUpdates(['offset' => -1, 'limit' => 10]);
    

Integration Tips

Laravel Service Container

  • Bind Custom Client:
    $this->app->bind(Telegram::class, function ($app) {
        return new Telegram(config('telegram.bot_token'), [
            'timeout' => 10,
            'proxy' => env('TELEGRAM_PROXY'),
        ]);
    });
    

Middleware for Auth

  • Validate Telegram Updates:
    public function handle(Request $request, Closure $next) {
        $update = $request->json()->all();
        if (!$this->validateTelegramUpdate($update)) {
            abort(403);
        }
        return $next($request);
    }
    

Event Dispatching

  • Trigger Events on Updates:
    event(new TelegramUpdateReceived($update));
    
    • Listen in EventServiceProvider:
      protected $listen = [
          TelegramUpdateReceived::class => [
              HandleTelegramStartCommand::class,
          ],
      ];
      

Gotchas and Tips

Pitfalls

  1. Webhook SSL Requirements

    • Telegram requires HTTPS for webhooks. Use ngrok locally or configure your server:
      $telegram->setWebhook(['url' => 'https://yourdomain.com/webhook']);
      
    • Debugging: Test with curl:
      curl -X POST https://api.telegram.org/bot<TOKEN>/setWebhook?url=https://yourdomain.com/webhook
      
  2. Rate Limits

    • Telegram enforces 30 requests/second per bot. Cache responses or use exponential backoff:
      try {
          $telegram->sendMessage(...);
      } catch (RateLimitException $e) {
          sleep($e->getRetryAfter());
          retry();
      }
      
  3. Chat ID Handling

    • Group Chats: Use -100 prefix (e.g., -100123456789).
    • Private Chats: Ensure chat_id is positive (e.g., 123456789).
    • Debug: Log chat_id to verify:
      \Log::debug('Chat ID:', [$update['message']['chat']['id']]);
      
  4. File Uploads

    • Large files (>10MB) require multipart/form-data. Use sendDocument or sendPhoto with local paths:
      $telegram->sendDocument([
          'chat_id' => $chatId,
          'document' => fopen('path/to/file.pdf', 'r'),
      ]);
      
  5. Locale/Encoding

    • Emoji/Unicode: Ensure your database and config support UTF-8.
    • Parse Mode: Use parse_mode => 'HTML' for rich text (e.g., <b>bold</b>).

Debugging Tips

  1. Enable API Debugging

    • Log raw responses:
      $telegram->setDebug(true); // In config or constructor
      
    • Check Laravel logs for telegram.* entries.
  2. Update Validation

    • Verify update structure:
      if (!isset($update['update_id'])) {
          throw new \InvalidArgumentException('Invalid Telegram update format');
      }
      
  3. Token Security

    • Never hardcode tokens. Use Laravel .env:
      TELEGRAM_BOT_TOKEN=your_token_here
      
    • Restrict token permissions in BotFather.
  4. Testing

    • Use @test accounts to avoid spamming real users.
    • Mock the client in tests:
      $mock = Mockery::mock(Telegram::class);
      $mock->shouldReceive('sendMessage')->once()->andReturn(['ok' => true]);
      $this->app->instance(Telegram::class, $mock);
      

Extension Points

  1. Custom API Methods

    • Extend the client by adding methods to Telegram.php:
      public function pinChatMessage($chatId, $messageId) {
          return $this->request('pinChatMessage', [
              'chat_id' => $chatId,
              'message_id' => $messageId,
          ]);
      }
      
  2. Middleware for Updates

    • Filter updates before handling:
      $telegram->onUpdate(function ($update) {
          if ($update['message']['text'] === '/admin') {
              return false; // Skip
          }
          return true; // Proceed
      });
      
  3. Database Integration

    • Store chat data in a model:
      $chat = Chat::firstOrCreate(['telegram_id' => $update['message']['chat']['id']]);
      $chat->update(['last_active' => now()]);
      
  4. Queue Delayed Tasks

    • Defer non-critical messages:
      TelegramJob::dispatch($telegram, $chatId, 'Delayed message')
          ->delay(now()->addMinutes(5));
      
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.
apiboxsym/user-bundle
apiboxsym/health-check-bundle
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