egormanakin/telegram-bot-bundle
Installation:
composer require boshurik/telegram-bot-bundle
Ensure TELEGRAM_BOT_TOKEN is set in your environment (e.g., .env).
Register the Bundle:
Add new BoShurik\TelegramBotBundle\BoShurikTelegramBotBundle to app/AppKernel.php (or config/bundles.php for Symfony 4+).
Configure Routing:
Add the webhook route in config/routes.yaml:
BoShurikTelegramBotBundle:
resource: "@BoShurikTelegramBotBundle/Resources/config/routing.yml"
prefix: /_telegram/<your-secret-key>
Basic Configuration:
Define the bot token and optional proxy in config/packages/boshurik_telegram_bot.yaml:
boshurik_telegram_bot:
api:
token: "%env(TELEGRAM_BOT_TOKEN)%"
proxy: "socks5://127.0.0.1:8888" # Optional
First Use Case:
Use the BotApi to send a test message:
use TelegramBot\Api\BotApi;
$api = $this->container->get(BotApi::class);
$api->sendMessage([
'chat_id' => '123456789',
'text' => 'Hello from Laravel!',
]);
Polling Updates (Development/Testing): Use the CLI command to fetch updates locally:
bin/console telegram:updates
Ideal for testing without configuring webhooks.
Webhook Setup (Production):
https://yourdomain.com/_telegram/secret-key):
bin/console telegram:webhook:set https://yourdomain.com/_telegram/secret-key [path/to/cert.pem]
/_telegram/secret-key to your Laravel app.Handling Updates:
UpdateHandler service to process incoming updates:
// src/Service/TelegramUpdateHandler.php
namespace App\Service;
use BoShurik\TelegramBotBundle\Event\UpdateEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class TelegramUpdateHandler implements EventSubscriberInterface
{
public static function getSubscribedEvents()
{
return [
'telegram.update' => 'onUpdate',
];
}
public function onUpdate(UpdateEvent $event)
{
$update = $event->getUpdate();
if (isset($update['message']['text'])) {
$text = $update['message']['text'];
$chatId = $update['message']['chat']['id'];
$api = $this->container->get(BotApi::class);
$api->sendMessage([
'chat_id' => $chatId,
'text' => "You said: {$text}",
]);
}
}
}
config/services.yaml:
services:
App\Service\TelegramUpdateHandler:
tags: ['telegram.update_handler']
Sending Rich Content:
Leverage the underlying telegram-bot/api library for advanced features:
$api->sendPhoto([
'chat_id' => '123456789',
'photo' => 'https://example.com/image.jpg',
'caption' => 'Check this out!',
]);
$api->sendDocument([
'chat_id' => '123456789',
'document' => 'https://example.com/file.pdf',
]);
Command-Line Interaction:
Use the BotApi in console commands for admin tasks:
// src/Command/SendBroadcastCommand.php
namespace App\Command;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use TelegramBot\Api\BotApi;
class SendBroadcastCommand extends Command
{
protected static $defaultName = 'telegram:broadcast';
protected function execute(InputInterface $input, OutputInterface $output)
{
$api = $this->getContainer()->get(BotApi::class);
$api->sendMessage([
'chat_id' => '@your_channel_username',
'text' => 'Broadcast message!',
'parse_mode' => 'Markdown',
]);
$output->writeln('Message broadcasted!');
}
}
Webhook SSL Requirements:
Secret Key Exposure:
/_telegram/<your-secret-key>) should not be guessable. Use a strong, random string (e.g., 32-character UUID).Update Handling Race Conditions:
// In your UpdateHandler
$updateId = $update['update_id'];
if (!$this->updateRepository->exists($updateId)) {
$this->updateRepository->save($updateId);
// Process update...
}
Rate Limits:
TelegramBot\Api\Exceptions\TelegramException gracefully:
try {
$api->sendMessage([...]);
} catch (TelegramException $e) {
$this->logger->error('Telegram API error: ' . $e->getMessage());
// Implement retry logic or queue the message
}
Proxy Configuration:
socks5://), ensure it’s stable. Proxy failures will break all API calls.curl --proxy socks5://127.0.0.1:8888 https://api.telegram.org/bot<token>/getMe
Log Updates:
Enable debug mode in config/packages/boshurik_telegram_bot.yaml:
boshurik_telegram_bot:
debug: true
This logs raw updates to var/log/dev.log.
Webhook Verification:
telegram:webhook:set with verbose output:
bin/console telegram:webhook:set https://yourdomain.com/_telegram/secret-key --verbose
Update Validation:
public function onUpdate(UpdateEvent $event)
{
$update = $event->getUpdate();
if (!isset($update['update_id']) || !is_numeric($update['update_id'])) {
throw new \RuntimeException('Invalid update payload');
}
// Process update...
}
Environment-Specific Config:
dev and prod (e.g., config/packages/boshurik_telegram_bot{dev,prod}.yaml):
# config/packages/boshurik_telegram_botdev.yaml
boshurik_telegram_bot:
api:
token: "%env(TELEGRAM_BOT_TOKEN_DEV)%"
debug: true
// src/EventListener/CustomUpdateListener.php
use BoShurik\TelegramBotBundle\Event\UpdateEvent;
class CustomUpdateListener
{
public function onUpdate(UpdateEvent $event)
{
if (isset($event->getUpdate()['custom_game'])) {
// Handle custom game logic
}
}
}
Register the listener in services.yaml:
services:
App\EventListener\CustomUpdateListener:
How can I help you explore Laravel packages today?