symfony/telegram-notifier
Symfony Telegram Notifier provides a Telegram integration for the Symfony Notifier component, letting you send notifications and messages to Telegram chats via bots. Easy to configure in Symfony apps and compatible with the broader notifier channel system.
Install the package:
composer require symfony/telegram-notifier
Configure the DSN in .env:
TELEGRAM_DSN=telegram://TOKEN@default?channel=CHAT_ID
TOKEN with your Telegram Bot Token.CHAT_ID with your target chat ID (e.g., @username or a numeric group ID).Register the transport in config/packages/notifier.yaml:
notifier:
chat:
telegram: '%env(TELEGRAM_DSN)%'
First use case: Send a simple message in a controller or command:
use Symfony\Component\Notifier\NotifierInterface;
use Symfony\Component\Notifier\Message\ChatMessage;
public function sendNotification(NotifierInterface $notifier): void
{
$message = new ChatMessage('Hello from Laravel!');
$notifier->send($message);
}
.env for security.NotifierInterface (autowired by Symfony) to send messages.Use Case: Alerts, logs, or status updates.
$message = new ChatMessage('Deployment failed on staging!');
$message->options((new TelegramOptions())->parseMode('MarkdownV2'));
$notifier->send($message);
Use Case: Attachments, images, or documents.
$options = (new TelegramOptions())
->photo('https://example.com/image.jpg')
->caption('Monthly Report')
->parseMode('HTML');
$message = new ChatMessage('Check the report below:');
$message->options($options);
$notifier->send($message);
Use Case: Polls, surveys, or workflows.
$markup = (new InlineKeyboardMarkup())
->inlineKeyboard([
(new InlineKeyboardButton('Approve'))->callbackData('approve'),
(new InlineKeyboardButton('Reject'))->callbackData('reject'),
]);
$options = (new TelegramOptions())->replyMarkup($markup);
$message = new ChatMessage('Review this PR?');
$message->options($options);
$notifier->send($message);
Use Case: Organize messages in threads (Symfony 7.3+).
$options = (new TelegramOptions())->messageThreadId(-100123456789); // Thread ID
$message = new ChatMessage('Threaded reply');
$message->options($options);
$notifier->send($message);
Use Case: Local files (e.g., logs, reports).
$options = (new TelegramOptions())
->uploadDocument(storage_path('logs/laravel.log'))
->caption('Server Logs');
$message = new ChatMessage('Check the logs:');
$message->options($options);
$notifier->send($message);
Use Case: Route messages to multiple chats.
$chats = ['@admin', '-100123456789']; // Group/channel IDs
foreach ($chats as $chatId) {
$message = new ChatMessage('Urgent: Server down!');
$message->options((new TelegramOptions())->chatId($chatId));
$notifier->send($message);
}
Use Case: Retry failed sends or log errors.
try {
$notifier->send($message);
} catch (TransportException $e) {
Log::error('Telegram send failed: ' . $e->getMessage());
// Retry logic or fallback (e.g., email)
}
Symfony Messenger: Integrate with Symfony’s Messenger component for async processing:
# config/packages/messenger.yaml
framework:
messenger:
transports:
telegram: '%env(TELEGRAM_DSN)%'
routing:
'App\Message\TelegramAlert': telegram
$bus->dispatch(new TelegramAlert('Alert message'));
Laravel Events:
Trigger notifications on events (e.g., job.failed):
Event::listen(JobFailed::class, function (JobFailed $event) {
$message = new ChatMessage("Job failed: {$event->job}");
$notifier->send($message);
});
Scheduled Tasks: Use Laravel’s scheduler to send periodic updates:
$schedule->call(function () {
$notifier->send(new ChatMessage('Daily digest'));
})->daily();
Local Development:
Use sslmode=disable for local testing (see README).
DSN Format:
telegram://TOKEN@default?chat=CHAT_ID (incorrect parameter name).channel or chat (both work, but channel is explicit for groups).telegram://TOKEN@default?channel=-100123456789.File Size Limits:
Markdown Escaping:
*, _, [) in messages may break formatting.parseMode('HTML') or escape characters manually.Rate Limits:
symfony/messenger).Callback Queries:
answerCallbackQuery can leave buttons unresponsive.Local Testing:
sslmode=disable) exposes traffic to MITM attacks.Enable Debug Mode: Configure the DSN to log requests:
TELEGRAM_DSN=telegram://TOKEN@default?channel=CHAT_ID&debug=1
Check logs for raw API responses.
Inspect Raw API Calls: Use a Telegram API proxy to debug locally.
Validate Chat IDs:
getUpdates to verify IDs./start to your bot and check the response.Handle Exceptions:
Catch Symfony\Component\Notifier\Exception\TransportException for failed sends:
try {
$notifier->send($message);
} catch (TransportException $e) {
// Log or notify admins
}
Custom Transport:
Extend TelegramTransport to add features (e.g., custom API endpoints):
class CustomTelegramTransport extends TelegramTransport
{
protected function getUri(): UriInterface
{
return new Uri('https://custom-api.example.com/bot' . $this->token);
}
}
Message Factories: Create reusable message builders:
class TelegramAlertFactory
{
public static function create(string $title, string $message): ChatMessage
{
$options = (new TelegramOptions())
->parseMode('MarkdownV2')
->disableWebPagePreview(true);
$chatMessage = new ChatMessage($message);
$chatMessage->options($options);
return $chatMessage->subject($title);
}
}
Middleware: Use Symfony Messenger middleware to modify messages:
$bus->addMiddleware(new class implements MiddlewareInterface {
public function handle(Envelope $envelope, HandleMiddleware $next): Envelope
{
$message = $envelope->getMessage();
if ($message instanceof ChatMessage) {
$message->options((new TelegramOptions())->addReplyMarkup(...));
}
return $next->handle($envelope);
How can I help you explore Laravel packages today?