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

irazasyed/telegram-bot-sdk

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup in Laravel

  1. Installation

    composer require irazasyed/telegram-bot-sdk
    
  2. Configure Bot Token Add your bot token to .env:

    TELEGRAM_BOT_TOKEN=your_bot_token_here
    
  3. Basic Webhook Setup In routes/web.php:

    use Telegram\Bot\Api;
    use Telegram\Bot\Laravel\Telegram;
    
    Telegram::route(function (Api $telegram) {
        $telegram->commands(['start', 'help'], function ($message) {
            $telegram->sendMessage([
                'chat_id' => $message->getChat()->getId(),
                'text' => 'Welcome to my bot!'
            ]);
        });
    });
    
  4. Verify Webhook Run:

    php artisan telegram:webhook-setup
    

First Use Case: Handling /start Command

Telegram::route(function (Api $telegram) {
    $telegram->onCommand('start', function ($message) {
        $telegram->replyToChatId($message->getChat()->getId(), 'Hello!');
    });
});

Implementation Patterns

Command-Based Workflows

Pattern: Use onCommand() for structured interactions.

Telegram::route(function (Api $telegram) {
    $telegram->commands(['start', 'help'], function ($message) {
        $telegram->sendMessage([
            'chat_id' => $message->getChat()->getId(),
            'text' => 'Available commands: /start, /help'
        ]);
    });
});

Middleware for Authentication

Pattern: Validate users via middleware.

Telegram::route(function (Api $telegram) {
    $telegram->middleware(function ($update) {
        $chat = $update->getMessage()->getChat();
        if ($chat->getType() !== 'private') {
            return false; // Ignore non-private chats
        }
        return true;
    });

    $telegram->onCommand('secret', function ($message) {
        $telegram->sendMessage([
            'chat_id' => $message->getChat()->getId(),
            'text' => 'Access granted!'
        ]);
    });
});

Integration with Laravel Services

Pattern: Inject Laravel services into bot logic.

Telegram::route(function (Api $telegram) {
    $telegram->onText(/\/user (\d+)/, function ($message, $userId) {
        $user = app(\App\Models\User::class)->find($userId);
        $telegram->sendMessage([
            'chat_id' => $message->getChat()->getId(),
            'text' => "User: {$user->name}"
        ]);
    });
});

Handling Updates with Queues

Pattern: Offload processing to queues for scalability.

Telegram::route(function (Api $telegram) {
    $telegram->onText(/\/process/, function ($message) {
        dispatch(new ProcessUpdateJob($message));
    });
});

Gotchas and Tips

Webhook Pitfalls

  • HTTPS Requirement: Telegram requires HTTPS for webhooks. Use telegram:webhook-setup with --force-https if testing locally.
  • Verification Token: Always validate the update_id and message_id to avoid replay attacks.
  • Debugging: Enable debug mode in config/telegram-bot-sdk.php:
    'debug' => env('TELEGRAM_DEBUG', false),
    

Rate Limiting

  • Default Limits: Telegram enforces rate limits. Cache frequent API calls or use exponential backoff.
  • Retry Logic: Implement retry logic for failed requests:
    try {
        $telegram->sendMessage($params);
    } catch (\Telegram\Bot\Exceptions\TelegramException $e) {
        if ($e->getCode() === 429) {
            sleep(1); // Retry after 1 second
            $telegram->sendMessage($params);
        }
    }
    

Extension Points

  • Custom Update Handlers: Extend Telegram\Bot\Api to handle custom update types:
    $telegram->on('my_custom_update', function ($update) {
        // Handle custom logic
    });
    
  • Middleware Chaining: Chain middleware for complex validation:
    $telegram->middleware([AuthMiddleware::class, LogMiddleware::class]);
    

Configuration Quirks

  • Bot Token: Ensure the token is never logged or exposed. Use Laravel's .env and config/telegram-bot-sdk.php.
  • Timezone: Set the correct timezone in config/telegram-bot-sdk.php to avoid timestamp issues:
    'timezone' => 'UTC',
    

Debugging Tips

  • Log Updates: Enable logging in config/telegram-bot-sdk.php:
    'log_updates' => true,
    
  • Inspect Raw Data: Access raw updates via $update->rawContent for debugging complex cases.

Performance Tips

  • Batch Processing: Use Telegram\Bot\Api::sendMessage() with disable_notification for bulk messages.
  • Lazy Loading: Load heavy dependencies (e.g., Eloquent models) only when needed inside handlers.
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware