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

borsaco/telegram-bot-api-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:
    composer require borsaco/telegram-bot-api-bundle
    
  2. Configure the bundle in config/packages/telegram.yaml with your bot token(s) and optional proxy settings.
  3. Access the bot in a controller:
    use Borsaco\TelegramBotApiBundle\Service\Bot;
    public function index(Bot $bot) {
        // Use $bot to interact with Telegram API
    }
    

First Use Case: Sending a Message

public function sendMessage(Bot $bot, Request $request) {
    $chatId = $request->query->get('chat_id');
    $message = $request->query->get('message');

    $bot->sendMessage([
        'chat_id' => $chatId,
        'text' => $message,
    ]);

    return new Response('Message sent!');
}

Key Starting Points

  • Bot Service: Injected via dependency injection (Bot class).
  • Telegram API Docs: Core Telegram Bot API for method references.
  • Webhook Setup: Configure a route to handle incoming updates (e.g., /telegram/webhook).

Implementation Patterns

Common Workflows

1. Handling Incoming Updates

Use a controller to process Telegram updates (e.g., messages, callbacks):

public function handleUpdate(Bot $bot, Request $request) {
    $update = json_decode($request->getContent(), true);

    if (isset($update['message'])) {
        $message = $update['message'];
        $bot->sendMessage([
            'chat_id' => $message['chat']['id'],
            'text' => 'Thanks for your message!',
        ]);
    }
}

2. Sending Media

Send photos, documents, or stickers:

$bot->sendPhoto([
    'chat_id' => $chatId,
    'photo' => 'https://example.com/image.jpg',
    'caption' => 'Check this out!',
]);

3. Inline Keyboards

Create interactive buttons:

$keyboard = [
    'inline_keyboard' => [
        [
            ['text' => 'Option 1', 'callback_data' => 'opt1'],
            ['text' => 'Option 2', 'callback_data' => 'opt2'],
        ],
    ],
];

$bot->sendMessage([
    'chat_id' => $chatId,
    'text' => 'Choose an option:',
    'reply_markup' => json_encode($keyboard),
]);

4. Handling Callbacks

Process button clicks via webhook:

if (isset($update['callback_query'])) {
    $callback = $update['callback_query'];
    $bot->answerCallbackQuery([
        'callback_query_id' => $callback['id'],
        'text' => 'You clicked: ' . $callback['data'],
    ]);
}

5. Async Requests (Optional)

Enable async mode in telegram.yaml for non-blocking calls:

async_requests: true

Integration Tips

Symfony Messenger Integration

Use Symfony’s Messenger component to queue Telegram API calls:

use Symfony\Component\Messenger\MessageBusInterface;

public function __construct(MessageBusInterface $bus) {
    $this->bus = $bus;
}

public function sendAsync(Bot $bot, $chatId, $message) {
    $this->bus->dispatch(new SendTelegramMessage($bot, $chatId, $message));
}

Command Bus for Bot Actions

Create commands for reusable bot logic:

// src/Command/SendWelcomeMessage.php
class SendWelcomeMessage implements CommandInterface {
    public function __construct(private Bot $bot, private int $chatId) {}

    public function handle(): void {
        $this->bot->sendMessage([
            'chat_id' => $this->chatId,
            'text' => 'Welcome to our bot!',
        ]);
    }
}

Event-Driven Architecture

Dispatch events for bot interactions (e.g., MessageReceivedEvent):

public function handleUpdate(Bot $bot, Request $request) {
    $update = json_decode($request->getContent(), true);
    if (isset($update['message'])) {
        $event = new MessageReceivedEvent($update['message']);
        $this->eventDispatcher->dispatch($event);
    }
}

Gotchas and Tips

Pitfalls

1. Webhook Configuration

  • HTTPS Requirement: Telegram requires HTTPS for webhooks. Use ngrok locally for testing:
    ngrok http 8000
    
  • Verify Token: Always validate the update payload’s token field matches your bot’s token in production.

2. Rate Limits

  • Telegram enforces rate limits. Handle 429 Too Many Requests gracefully:
    try {
        $bot->sendMessage([...]);
    } catch (RateLimitException $e) {
        // Retry logic or notify admin
    }
    

3. Async Mode Quirks

  • If async_requests: true, responses may not be immediate. Use callbacks or polling for critical actions.

4. Maintenance Mode

  • The maintenance flag in telegram.yaml only filters developers if developers_id is set. Test thoroughly:
    development:
        developers_id: [1234567] # Your Telegram user ID
        maintenance: true
    

5. Proxy Issues

  • If using a proxy (e.g., socks5h), ensure it’s correctly formatted and accessible from your server.

Debugging Tips

1. Log Raw Updates

Log incoming updates to debug payloads:

public function handleUpdate(Bot $bot, Request $request) {
    $this->logger->debug('Raw update:', ['update' => $request->getContent()]);
    // Process update...
}

2. Test Locally with curl

Simulate Telegram updates for testing:

curl -X POST http://localhost:8000/telegram/webhook \
  -H "Content-Type: application/json" \
  -d '{"message": {"text": "test", "chat": {"id": 123}}}'

3. Bot Token Validation

  • Double-check your token in telegram.yaml and BotFather. A wrong token causes silent failures.

4. Error Handling

Wrap API calls in try-catch blocks:

try {
    $response = $bot->getMe();
} catch (TelegramApiException $e) {
    $this->logger->error('Telegram API error:', ['error' => $e->getMessage()]);
    throw new \RuntimeException('Bot service unavailable');
}

Extension Points

1. Custom Bot Classes

Extend the Bot service for domain-specific logic:

class CustomBot extends Bot {
    public function sendWelcomeMessage(int $chatId): void {
        $this->sendMessage([
            'chat_id' => $chatId,
            'text' => 'Welcome! Use /help for commands.',
        ]);
    }
}

2. Middleware for Updates

Add middleware to preprocess updates (e.g., logging, filtering):

// src/EventListener/TelegramUpdateListener.php
public function onKernelRequest(GetResponseEvent $event) {
    if ($event->isMasterRequest() && $event->getRequest()->getPathInfo() === '/telegram/webhook') {
        $update = json_decode($event->getRequest()->getContent(), true);
        // Custom logic (e.g., block spam)
    }
}

3. Custom Response Classes

Create DTOs for API responses to avoid magic strings:

class TelegramUser {
    public function __construct(
        public int $id,
        public string $firstName,
        public ?string $lastName,
        public ?string $username
    ) {}
}

// Usage:
$user = new TelegramUser(
    $update['message']['from']['id'],
    $update['message']['from']['first_name'],
    $update['message']['from']['last_name'] ?? null,
    $update['message']['from']['username'] ?? null
);

4. Database Integration

Store chat states or user data in Doctrine:

// After receiving a message:
$user = $update['message']['from'];
$chat = $this->chatRepository->findOrCreate($user['id'], $user['first_name']);

// Update chat state:
$chat->setLastActiveAt(new \DateTime());
$this->chatRepository->save($chat);

5. Testing

Use TelegramBotApiBundle's Bot interface for mocking in tests:

// tests/Service/BotTest.php
public function testSendMessage() {
    $bot = $this->createMock(Bot::class);
    $bot->expects($this->once())
        ->method('sendMessage')
        ->with(['chat_id' => 12
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