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

Api Laravel Package

telegram-bot/api

Native PHP wrapper for the Telegram Bot API with no extra requirements. Supports all API methods and response types, including sending messages, documents, reply/inline keyboards, and media groups. Install via Composer and start building bots quickly.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require telegram-bot/api
    

    Add to composer.json if using Laravel:

    "require": {
        "telegram-bot/api": "^3.0"
    }
    
  2. Basic Bot Initialization:

    use TelegramBot\Api\BotApi;
    
    $bot = new BotApi(config('services.telegram.bot_token'));
    
  3. First Use Case: Send a message in a Laravel controller:

    public function sendWelcomeMessage(Request $request)
    {
        $chatId = $request->input('chat_id');
        $bot->sendMessage($chatId, 'Welcome to our service!');
    }
    

Where to Look First


Implementation Patterns

Core Workflows

1. Command-Based Interactions

// In a Laravel service provider or controller
$bot->command('start', function ($message) use ($bot) {
    $chatId = $message->getChat()->getId();
    $bot->sendMessage($chatId, "Hello! Use /help for options.");
});

2. Event-Driven Responses

// Handle all text messages
$bot->on(function ($update) use ($bot) {
    $message = $update->getMessage();
    if ($message) {
        $bot->sendMessage(
            $message->getChat()->getId(),
            "You said: " . $message->getText()
        );
    }
}, function () {
    return true; // Always run
});

3. Media Handling

// Handle document uploads
$bot->on(function ($update) use ($bot) {
    $document = $update->getMessage()->getDocument();
    if ($document) {
        $file = $bot->getFile($document->getFileId());
        $bot->sendMessage(
            $update->getMessage()->getChat()->getId(),
            "Received file: " . $file->getFilePath()
        );
    }
});

4. Keyboard Integration

// Inline keyboard for buttons
$keyboard = new \TelegramBot\Api\Types\Inline\InlineKeyboardMarkup([
    [
        ['text' => 'Option 1', 'callback_data' => 'opt1'],
        ['text' => 'Option 2', 'callback_data' => 'opt2'],
    ]
]);

$bot->sendMessage($chatId, "Choose:", null, false, null, $keyboard);

// Handle callback queries
$bot->onCallbackQuery(function ($callbackQuery) use ($bot) {
    $data = $callbackQuery->getData();
    $bot->answerCallbackQuery($callbackQuery->getId(), "You selected: $data");
});

5. Laravel Service Container Integration

// In AppServiceProvider@boot()
$this->app->singleton('telegram.bot', function ($app) {
    return new \TelegramBot\Api\BotApi(config('services.telegram.bot_token'));
});

// Usage in controllers
public function __construct(private BotApi $bot) {}

Advanced Patterns

1. Webhook Setup (Laravel)

// routes/web.php
Route::post('/telegram/webhook', function (Request $request) {
    $update = \TelegramBot\Api\Types\Update::fromArray($request->all());
    $bot = app('telegram.bot');

    // Process update (e.g., dispatch Laravel events)
    event(new TelegramUpdateReceived($update));

    return response()->json(['status': 'ok']);
});

2. Rate Limiting & Retries

use TelegramBot\Api\Exception\HttpException;

try {
    $bot->sendMessage($chatId, $text);
} catch (HttpException $e) {
    if ($e->getCode() === 429) { // Rate limited
        sleep($e->getRetryAfter());
        $bot->sendMessage($chatId, $text);
    }
}

3. Custom HTTP Client (Symfony)

use Symfony\Component\HttpClient\HttpClient;
use TelegramBot\Api\Http\SymfonyHttpClient;

$client = HttpClient::create();
$bot = new \TelegramBot\Api\BotApi(
    config('services.telegram.bot_token'),
    null,
    new SymfonyHttpClient($client)
);

4. Local Bot API Server

// For testing without hitting Telegram's servers
$bot = new \TelegramBot\Api\Client(
    'token',
    null,
    null,
    'http://localhost:8081'
);

Gotchas and Tips

Common Pitfalls

  1. Chat ID Types:

    • Telegram uses strings for private chats (e.g., "12345678").
    • Use integers for groups/supergroups (e.g., -100123456789).
    • Gotcha: Mixing types causes Bad Request errors.
  2. Webhook SSL:

    • Telegram requires HTTPS for webhooks. Use Laravel Valet/Forge with a valid certificate or ngrok for local testing.
  3. Rate Limits:

    • Telegram enforces rate limits. Handle 429 Too Many Requests with retries.
  4. File Handling:

    • Files sent via sendDocument must be CURLFile objects or URLs.
    • Gotcha: Local files must be accessible by the PHP process (check open_basedir restrictions).
  5. Deprecated Methods:

    • Avoid thumb* methods (use thumbnail* instead).
    • Prefer banChatMember over deprecated kickChatMember.

Debugging Tips

  1. Enable Logging:

    $bot = new \TelegramBot\Api\BotApi('token', null, null, null, [
        'logger' => function ($level, $message) {
            \Log::channel('telegram')->$level($message);
        }
    ]);
    
  2. Inspect Updates:

    $bot->on(function ($update) {
        \Log::debug('Raw update:', $update->toArray());
    });
    
  3. Validate Webhook URL:

    • Test with Telegram BotFather:
      /setwebhook https://yourdomain.com/telegram/webhook?secret=SECRET
      

Extension Points

  1. Custom Update Handlers:

    // Dispatch Laravel events
    $bot->on(function ($update) {
        event(new TelegramUpdateReceived($update));
    });
    
  2. Middleware for Requests:

    $bot = new \TelegramBot\Api\BotApi('token', null, null, null, [
        'http' => [
            'headers' => [
                'User-Agent' => 'LaravelBot/1.0',
            ],
        ],
    ]);
    
  3. Proxy Support:

    $bot = new \TelegramBot\Api\BotApi('token', null, null, null, [
        'proxy' => 'http://proxy.example.com:8080',
    ]);
    
  4. Third-Party HTTP Clients:

    • Use SymfonyHttpClient or GuzzleHttpClient for advanced features (e.g., async requests).

Laravel-Specific Quirks

  1. Configuration: Add to config/services.php:

    'telegram' => [
        'bot_token' => env('TELEGRAM_BOT_TOKEN'),
        'webhook_secret' => env('TELEGRAM_WEBHOOK_SECRET'),
    ],
    
  2. Environment Variables:

    TELEGRAM_BOT_TOKEN=your_token_here
    TELEGRAM_WEBHOOK_URL=https://yourdomain.com/telegram/webhook
    
  3. Artisan Commands:

    // Example: Send a test message via CLI
    $bot = app('telegram.bot');
    $bot->sendMessage(env('TEST_CHAT_ID'), 'Bot is running!');
    
  4. Testing:

    • Use TelegramBot\Api\Client with a local server for unit tests.
    • Mock BotApi in PHPUnit:
      $mockBot = Mockery::mock(\TelegramBot\Api\BotApi::class);
      $mockBot->shouldReceive('sendMessage')->once();
      
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.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor