Download the PHP package samuelterra22/laravel-telegram-notifications without Composer
On this page you can find all versions of the php package samuelterra22/laravel-telegram-notifications. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download samuelterra22/laravel-telegram-notifications
More information about samuelterra22/laravel-telegram-notifications
Files in samuelterra22/laravel-telegram-notifications
Package laravel-telegram-notifications
Short Description Laravel package for sending notifications, messages and logs via Telegram Bot API
License MIT
Homepage https://github.com/samuelterra22/laravel-telegram-notifications
Informations about the package laravel-telegram-notifications
Laravel Telegram Notifications
A complete Laravel package for integrating the Telegram Bot API with Laravel applications. Send messages, notifications, log errors, use interactive keyboards, support multiple bots and forum topics.
Table of Contents
- Features
- Requirements
- Installation
- Configuration
- Quick Start
- Usage
- Sending Messages via Facade
- Laravel Notifications Channel
- Message Types
- Text Formatting Methods
- Interactive Keyboards
- Fluent Message Builder
- Broadcasting
- Edit, Delete, Forward & Copy Messages
- Chat Actions
- Chat Management
- Bot Management & Commands
- Webhook Management & Middleware
- File Operations
- Callbacks & Inline Queries
- Moderation
- Advanced Options
- Message Effects
- Reactions
- MarkdownV2 Escaping
- Blade View Rendering
- Media Group Builder
- Payments & Invoices
- Gifts
- Stories
- Checklists
- Logging (Monolog Handler)
- Artisan Commands
- Webhook Handler
- Queued Broadcasting
- Error Handling
- Multi-Bot Support
- Enums Reference
- Typed Responses
- Testing
- API Quick Reference
- Roadmap
- Development
- Changelog
- Contributing
- License
Features
- 13 message builders: text, photo, document, video, audio, voice, animation, location, venue, contact, poll, sticker, dice
- Facade convenience methods: send photos, videos, stickers, video notes, media groups, and more directly via
Telegram:: - Laravel Notifications channel: use
toTelegram()in your notification classes - Monolog log handler: send error logs directly to Telegram with emoji, stack traces, and app context
- Multi-bot support: configure and switch between multiple bots at runtime
- Forum/Topics support: send messages to specific forum topics via
message_thread_id - Interactive keyboards: inline keyboards, reply keyboards, force reply, and keyboard removal with fluent builders
- 10 inline button types: URL, callback, web app, login URL, switch inline query, copy text, pay, and more
- Fluent API:
Telegram::message($chatId)->html('text')->silent()->send() - Broadcast support: send messages to multiple chats with rate limiting and failure callbacks
- Typed response objects:
TelegramResponsewithmessageId(),date(),chat(),text()accessors - Auto message splitting: messages exceeding 4096 characters are split automatically
- Message effects: animated visual effects (confetti, fire) via
effect()on all message builders (Bot API 7.4+) - Expandable blockquotes: collapsible text sections via
expandableQuote() - Blade view rendering: use Blade templates for message content via
view() - MarkdownV2 auto-escaping:
MarkdownV2::escape()helper andescapedMarkdown()builder method - TelegramMediaGroup builder: fluent builder for sending media albums via notification channel
- Reactions:
setMessageReaction()for emoji and custom emoji reactions - Payments & invoices:
sendInvoice(),createInvoiceLink(), Telegram Stars support - Gifts:
sendGift(),getAvailableGifts() - Stories:
postStory(),editStory(),deleteStory() - Checklists:
TelegramChecklistfluent builder for structured task lists - Configurable retry with backoff: exponential backoff with jitter for rate limit handling
- Queued broadcasting: dispatch broadcasts as Laravel queue jobs via
queue() - Webhook handler: abstract
WebhookHandlerclass for routing incoming updates telegram:sendcommand: send messages from the command line- Rate limit handling: built-in retry-after handling with configurable exponential backoff
- Webhook verification middleware: validate incoming webhook requests via secret token
- Chat action shortcuts:
typing(),uploadingPhoto(),recordingVideo(), and more $optionsparameter on all methods: pass any Telegram Bot API parameter without falling back to rawcall()- Rich error objects:
TelegramApiExceptionwith status code, API method, retry-after, and rate limit detection - Fully testable: all HTTP calls via Laravel's
Http::facade, easily mocked withHttp::fake() - Zero external dependencies: uses Laravel's built-in HTTP client
- 99.9% test coverage: 785 tests with 1439 assertions
Requirements
- PHP 8.2+
- Laravel 11 or 12
Installation
Publish the config file:
Configuration
Add to your .env:
All available environment variables:
| Variable | Description | Default |
|---|---|---|
TELEGRAM_BOT_TOKEN |
Bot token from @BotFather | (required) |
TELEGRAM_BOT_USERNAME |
Bot username (without @) for integration links | null |
TELEGRAM_CHAT_ID |
Default chat ID for the bot | null |
TELEGRAM_TOPIC_ID |
Default forum topic ID | null |
TELEGRAM_BOT |
Name of the default bot | default |
TELEGRAM_API_BASE_URL |
Telegram API base URL (useful for local Bot API server) | https://api.telegram.org |
TELEGRAM_TIMEOUT |
HTTP timeout in seconds | 10 |
TELEGRAM_LOG_ENABLED |
Enable Telegram log handler | false |
TELEGRAM_LOG_BOT |
Bot to use for logging | default |
TELEGRAM_LOG_CHAT_ID |
Chat ID for log messages | null |
TELEGRAM_LOG_TOPIC_ID |
Topic ID for log messages | null |
TELEGRAM_WEBHOOK_SECRET |
Secret token for webhook verification | null |
TELEGRAM_RETRY_MAX_ATTEMPTS |
Max retry attempts on rate limit | 3 |
TELEGRAM_RETRY_BASE_DELAY_MS |
Base delay in milliseconds | 1000 |
TELEGRAM_RETRY_USE_JITTER |
Add random jitter to delays | true |
The config file config/telegram-notifications.php supports multiple bots:
Quick Start
Usage
Sending Messages via Facade
Laravel Notifications Channel
Create a notification class with a toTelegram() method:
Send notifications:
Add the routing method to your notifiable model:
You can return any message type from toTelegram() (not just TelegramMessage):
Message Types
All message builders share these methods via the HasSharedParams trait:
| Method | Description |
|---|---|
to(string $chatId) |
Set the target chat ID |
topic(string $topicId) |
Set the forum topic/thread ID |
bot(string $bot) |
Set which bot to use |
All builders also support silent() and protected() to disable notifications and protect content from forwarding/saving.
Text Message
Photo
Document
Video
Audio
Voice
Animation (GIF)
Sticker
Location
You can also set coordinates individually:
Venue
Contact
Poll
Dice
Facade-Only Types
These types don't have dedicated builder classes but are available via the Facade:
Text Formatting Methods
TelegramMessage provides fluent methods for HTML formatting:
| Method | Output | Example |
|---|---|---|
content(string $text) |
Raw text | Hello world |
line(string $text) |
Appends text + newline | Line 1\nLine 2 |
bold(string $text) |
<b>text</b> |
text |
italic(string $text) |
<i>text</i> |
text |
underline(string $text) |
<u>text</u> |
text |
strikethrough(string $text) |
<s>text</s> |
|
code(string $text) |
<code>text</code> |
text |
pre(string $text, ?string $lang) |
<pre><code class="lang">text</code></pre> |
Code block |
link(string $text, string $url) |
<a href="url">text</a> |
text |
spoiler(string $text) |
<tg-spoiler>text</tg-spoiler> |
Hidden text |
quote(string $text) |
<blockquote>text</blockquote> |
Blockquote |
expandableQuote(string $text) |
<blockquote expandable>text</blockquote> |
Collapsible quote |
Change parse mode:
Messages exceeding 4096 characters are automatically split into multiple messages using splitContent().
Interactive Keyboards
Inline Keyboard
Inline keyboards appear below the message:
All inline button types:
| Method | Description | Parameters |
|---|---|---|
url(text, url, columns) |
Opens a URL | string $text, string $url, int $columns = 2 |
callback(text, data, columns) |
Sends callback query | string $text, string $data, int $columns = 2 |
webApp(text, url, columns) |
Opens a Web App | string $text, string $webAppUrl, int $columns = 2 |
loginUrl(text, loginUrl, columns) |
Authentication button | string $text, array\|string $loginUrl, int $columns = 2 |
switchInlineQuery(text, query, columns) |
Switch to inline in any chat | string $text, string $query = '', int $columns = 2 |
switchInlineQueryCurrentChat(text, query, columns) |
Switch to inline in current chat | string $text, string $query = '', int $columns = 2 |
switchInlineQueryChosenChat(text, options, columns) |
Switch inline with chat picker | string $text, array $options = [], int $columns = 2 |
copyText(text, textToCopy, columns) |
Copies text to clipboard | string $text, string $textToCopy, int $columns = 2 |
pay(text, columns) |
Payment button | string $text, int $columns = 2 |
button(button, columns) |
Add a custom Button instance |
Button $button, int $columns = 2 |
row() |
Start a new button row |
The $columns parameter controls auto-layout: buttons are placed in rows of N columns. Use row() to force a new row.
Custom Button Objects
For full control, use the Button class:
Reply Keyboard
Reply keyboards replace the device keyboard:
| Method | Description |
|---|---|
button(text, columns) |
Simple text button |
requestContact(text, columns) |
Request user's phone number |
requestLocation(text, columns) |
Request user's location |
row() |
Start a new button row |
resize(bool) |
Resize keyboard to fit buttons |
oneTime(bool) |
Hide keyboard after one button press |
placeholder(string) |
Input field placeholder text |
selective(bool) |
Show only to mentioned/replied-to users |
persistent(bool) |
Keep keyboard always visible |
Force Reply & Remove Keyboard
Checking Keyboard State
Fluent Message Builder
Build and send messages with a chainable interface that returns typed TelegramResponse objects:
Available methods on PendingMessage:
| Method | Description |
|---|---|
text(string $text) |
Set message text (default parse mode) |
html(string $text) |
Set text with HTML parse mode |
markdown(string $text) |
Set text with MarkdownV2 parse mode |
silent() |
Disable notification sound |
protected() |
Protect content from forwarding/saving |
disablePreview() |
Disable web page link previews |
keyboard(ReplyMarkupInterface $markup) |
Attach any keyboard/reply markup |
replyTo(int\|string $messageId) |
Reply to a specific message |
topic(string $topicId) |
Send to a forum topic |
sendWhen(bool $condition) |
Only send if condition is true |
send() |
Execute and return TelegramResponse |
Conditional Sending
Broadcasting
Send the same message to multiple chats with rate limiting and error handling:
You can also add recipients dynamically:
Available methods on PendingBroadcast:
| Method | Description |
|---|---|
to(string ...$chatIds) |
Add chat IDs to the broadcast list |
text(string $text) |
Set message text |
html(string $text) |
Set text with HTML parse mode |
markdown(string $text) |
Set text with MarkdownV2 parse mode |
silent() |
Disable notification sound |
protected() |
Protect content |
keyboard(ReplyMarkupInterface $markup) |
Attach keyboard |
rateLimit(int $milliseconds) |
Delay between sends (default: 0) |
onFailure(callable $callback) |
Handle per-chat failures: fn(string $chatId, Throwable $e) |
send() |
Execute broadcast, returns array of TelegramResponse |
Edit, Delete, Forward & Copy Messages
Chat Actions
Show what the bot is "doing" to the user:
Chat Management
Bot Management & Commands
Webhook Management & Middleware
Setting Up Webhooks
Verifying Incoming Webhooks
Protect your webhook endpoint with the built-in middleware:
The telegram.webhook middleware checks the X-Telegram-Bot-Api-Secret-Token header against your configured secret. If no secret is configured, all requests pass through.
File Operations
Uploading Local Files
Use the low-level TelegramBotApi::upload() method for sending local files:
Callbacks & Inline Queries
Moderation
Advanced Options
All Facade methods accept an optional $options array as the last parameter. This lets you pass any Telegram Bot API parameter without falling back to raw call():
Raw API Calls
For any Telegram Bot API method not wrapped by the package:
Message Effects
All message builders support the effect() method for animated visual effects (Bot API 7.4+):
Reactions
MarkdownV2 Escaping
Blade View Rendering
Use Blade templates for message content:
Example Blade template (resources/views/telegram/order-shipped.blade.php):
Media Group Builder
Payments & Invoices
Paid Media
Gifts
Stories
Checklists
Suggested Posts
Profile Management
Streaming Message Drafts
Logging (Monolog Handler)
Send application logs directly to Telegram. The handler uses callSilent() internally, so it never crashes your application even if the Telegram API is unreachable.
Setup
Add the Telegram channel to config/logging.php:
Configure in .env:
Usage
Exception Handler Integration
Report all exceptions to Telegram in bootstrap/app.php:
Log Message Format
Log messages are formatted with:
- Level emoji (e.g. CRITICAL, ERROR, WARNING)
- Application name and environment
- Authenticated user info (ID and email, when available)
- Message text
- Exception class, file, and line number (when applicable)
- Truncated stack trace (max 2000 chars)
- Total message capped at 4096 characters (Telegram limit)
If HTML formatting fails, the handler automatically falls back to plain text.
Artisan Commands
telegram:get-me
Display bot information:
Output shows: ID, Name, Username, Is Bot, Can Join Groups, Can Read Messages, Supports Inline.
telegram:set-webhook
Manage webhook configuration:
telegram:send
Send a message from the command line:
Webhook Handler
The package provides an abstract WebhookHandler base class for processing incoming Telegram updates. Create a concrete handler by extending it:
Register it in your routes:
The handler automatically routes updates:
/command args->onCommandCommand($message, $args)(dynamic method dispatch)/command@BotName args-> strips the@BotNameportion- Plain messages ->
onMessage($message) - Callback queries ->
onCallbackQuery($callbackQuery) - Inline queries ->
onInlineQuery($inlineQuery) - Pre-checkout queries ->
onPreCheckoutQuery($query) - Shipping queries ->
onShippingQuery($query) - Message reactions ->
onMessageReaction($reaction) - Unknown commands ->
onUnknownCommand($command, $message, $args) - Unrecognized updates ->
onUnhandledUpdate($update)
Queued Broadcasting
Dispatch broadcasts as Laravel queue jobs for background processing:
The SendTelegramBroadcast job handles individual failures gracefully -- if sending to one chat fails, it continues to the rest.
Error Handling
API errors throw TelegramApiException with rich context:
Rate Limiting
The package handles HTTP 429 (Too Many Requests) with configurable exponential backoff:
- When a
429response is received, the client retries with exponential backoff - If the response includes
retry_after, that value is used as the delay - Otherwise, delay doubles each attempt: base_delay * 2^(attempt-1)
- Optional jitter adds randomness to prevent thundering herd
- After
max_attemptsretries,TelegramApiExceptionis thrown
Configure via config/telegram-notifications.php or environment variables:
Silent Calls
For non-critical paths where you don't want exceptions:
The logging handler (TelegramHandler) always uses callSilent() to ensure log delivery failures never crash your application.
Multi-Bot Support
Configuration
Switching Bots
Bot Usernames & Integration Links
Each bot can have its own username for generating t.me integration links:
Bots are lazy-loaded: the TelegramBotApi instance for each bot is only created when first accessed via bot().
Enums Reference
ParseMode
ChatAction
Typed Responses
The fluent builder returns TelegramResponse objects with typed accessors:
| Method | Return Type | Description |
|---|---|---|
ok() |
bool |
Whether the API request succeeded |
messageId() |
?int |
The sent message ID |
date() |
?Carbon |
Message timestamp as Carbon instance |
chat() |
?array |
Chat data (id, type, title, etc.) |
text() |
?string |
Message text content |
result() |
array |
Full API result object |
toArray() |
array |
Raw response data |
Testing
The package uses Laravel's Http::fake() for all API calls, making it trivial to test:
Testing Notifications
Testing with Sequences
Asserting No Calls Were Made
API Quick Reference
Telegram Facade Methods
Messaging
| Method | Parameters | Returns |
|---|---|---|
sendMessage |
string $chatId, string $text, ?string $parseMode = 'HTML', ?string $topicId = null, array $options = [] |
array |
sendPhoto |
string $chatId, string $photo, ?string $caption = null, ?string $parseMode = 'HTML', array $options = [] |
array |
sendDocument |
string $chatId, string $document, ?string $caption = null, ?string $parseMode = 'HTML', array $options = [] |
array |
sendVideo |
string $chatId, string $video, ?string $caption = null, ?string $parseMode = 'HTML', array $options = [] |
array |
sendAudio |
string $chatId, string $audio, ?string $caption = null, ?string $parseMode = 'HTML', array $options = [] |
array |
sendVoice |
string $chatId, string $voice, ?string $caption = null, ?string $parseMode = 'HTML', array $options = [] |
array |
sendAnimation |
string $chatId, string $animation, ?string $caption = null, ?string $parseMode = 'HTML', array $options = [] |
array |
sendSticker |
string $chatId, string $sticker, array $options = [] |
array |
sendVideoNote |
string $chatId, string $videoNote, array $options = [] |
array |
sendMediaGroup |
string $chatId, array $media, array $options = [] |
array |
sendLocation |
string $chatId, float $latitude, float $longitude, array $options = [] |
array |
sendVenue |
string $chatId, float $lat, float $lng, string $title, string $address, array $options = [] |
array |
sendContact |
string $chatId, string $phone, string $firstName, ?string $lastName = null, array $options = [] |
array |
sendPoll |
string $chatId, string $question, array $options, array $extra = [] |
array |
sendDice |
string $chatId, ?string $emoji = null, array $options = [] |
array |
Message Operations
| Method | Parameters | Returns |
|---|---|---|
editMessageText |
string $chatId, int\|string $messageId, string $text, ?string $parseMode = 'HTML', array $options = [] |
array |
editMessageCaption |
string $chatId, int\|string $messageId, string $caption, ?string $parseMode = 'HTML', array $options = [] |
array |
editMessageReplyMarkup |
string $chatId, int\|string $messageId, array $replyMarkup, array $options = [] |
array |
editMessageMedia |
string $chatId, int\|string $messageId, array $media, array $options = [] |
array |
deleteMessage |
string $chatId, int\|string $messageId, array $options = [] |
array |
deleteMessages |
string $chatId, array $messageIds, array $options = [] |
array |
forwardMessage |
string $chatId, string $fromChatId, int\|string $messageId, array $options = [] |
array |
copyMessage |
string $chatId, string $fromChatId, int\|string $messageId, array $options = [] |
array |
Chat Actions & Management
| Method | Parameters | Returns |
|---|---|---|
sendChatAction |
string $chatId, ChatAction $action, array $options = [] |
array |
typing |
string $chatId |
array |
uploadingPhoto |
string $chatId |
array |
uploadingDocument |
string $chatId |
array |
recordingVideo |
string $chatId |
array |
recordingVoice |
string $chatId |
array |
getChat |
string $chatId, array $options = [] |
array |
getChatMember |
string $chatId, int\|string $userId, array $options = [] |
array |
getChatMemberCount |
string $chatId, array $options = [] |
array |
pinChatMessage |
string $chatId, int\|string $messageId, bool $disableNotification = false, array $options = [] |
array |
unpinChatMessage |
string $chatId, ?int $messageId = null, array $options = [] |
array |
unpinAllChatMessages |
string $chatId, array $options = [] |
array |
Bot & Webhook
| Method | Parameters | Returns |
|---|---|---|
getMe |
array |
|
setMyCommands |
array $commands, array $options = [] |
array |
getMyCommands |
array $options = [] |
array |
deleteMyCommands |
array $options = [] |
array |
getFile |
string $fileId, array $options = [] |
array |
setWebhook |
string $url, ?string $secretToken = null, array $options = [] |
array |
deleteWebhook |
bool $dropPendingUpdates = false, array $options = [] |
array |
getWebhookInfo |
array |
Callbacks, Queries & Moderation
| Method | Parameters | Returns |
|---|---|---|
answerCallbackQuery |
string $id, ?string $text = null, bool $showAlert = false, array $options = [] |
array |
answerInlineQuery |
string $id, array $results, array $options = [] |
array |
setMessageReaction |
string $chatId, int\|string $messageId, array $reaction, bool $isBig = false, array $options = [] |
array |
banChatMember |
string $chatId, int\|string $userId, array $options = [] |
array |
unbanChatMember |
string $chatId, int\|string $userId, array $options = [] |
array |
Payments & Commerce
| Method | Parameters | Returns |
|---|---|---|
sendInvoice |
string $chatId, string $title, string $description, string $payload, string $currency, array $prices, ?string $providerToken = null, array $options = [] |
array |
createInvoiceLink |
string $title, string $description, string $payload, string $currency, array $prices, ?string $providerToken = null, array $options = [] |
array |
answerPreCheckoutQuery |
string $preCheckoutQueryId, bool $ok, ?string $errorMessage = null, array $options = [] |
array |
answerShippingQuery |
string $shippingQueryId, bool $ok, ?array $shippingOptions = null, ?string $errorMessage = null, array $options = [] |
array |
refundStarPayment |
int\|string $userId, string $telegramPaymentChargeId, array $options = [] |
array |
getStarTransactions |
?int $offset = null, ?int $limit = null, array $options = [] |
array |
sendPaidMedia |
string $chatId, int $starCount, array $media, ?string $caption = null, ?string $parseMode = 'HTML', array $options = [] |
array |
sendGift |
int\|string $userId, string $giftId, ?string $text = null, ?string $textParseMode = null, array $options = [] |
array |
getAvailableGifts |
array $options = [] |
array |
Stories
| Method | Parameters | Returns |
|---|---|---|
postStory |
string $chatId, array $content, ?int $activePeriod = null, ?string $caption = null, ?string $parseMode = 'HTML', array $options = [] |
array |
editStory |
string $chatId, int\|string $storyId, array $content, ?string $caption = null, ?string $parseMode = 'HTML', array $options = [] |
array |
deleteStory |
string $chatId, int\|string $storyId, array $options = [] |
array |
deleteStories |
string $chatId, array $storyIds, array $options = [] |
array |
Checklists & Other
| Method | Parameters | Returns |
|---|---|---|
sendChecklist |
string $chatId, string $title, array $checklist, array $options = [] |
array |
sendMessageDraft |
string $chatId, string $text, ?string $parseMode = 'HTML', ?string $businessConnectionId = null, array $options = [] |
array |
approveSuggestedPost |
string $chatId, int\|string $messageId, array $options = [] |
array |
declineSuggestedPost |
string $chatId, int\|string $messageId, array $options = [] |
array |
setMyProfilePhoto |
string $photo, bool $isPersonal = false, array $options = [] |
array |
removeMyProfilePhoto |
bool $isPersonal = false, array $options = [] |
array |
Fluent Builders
| Method | Parameters | Returns |
|---|---|---|
message |
string $chatId |
PendingMessage |
broadcast |
array $chatIds = [] |
PendingBroadcast |
bot |
?string $name = null |
TelegramBotApi |
TelegramBotApi Methods
| Method | Description |
|---|---|
call(string $method, array $params = []) |
Make API call, throws TelegramApiException on error |
callSilent(string $method, array $params = []) |
Make API call, returns bool (never throws) |
upload(string $method, array $params, string $fileField, string $filePath) |
Upload local file via multipart |
getToken() |
Get the bot token |
getBaseUrl() |
Get the API base URL |
getTimeout() |
Get the HTTP timeout |
Roadmap
All features from the original roadmap have been implemented. Future ideas:
- TelegramVideoNote builder - Fluent builder for round video messages
- Conversation/state management - Multi-step interactive flows with state serialization
- Database-backed bot/chat models - Eloquent models for persistent bot and chat management
- Batch queue integration -
Bus::batch()support for broadcast progress tracking - Mini App support - Enhanced Web App button and data validation helpers
Development
Docker-based development (PHP 8.4 CLI Alpine):
Without Docker:
Changelog
Please see CHANGELOG for more information on what has changed recently.
Contributing
Contributions are welcome! Please ensure tests pass and code follows the project style (Laravel Pint).
This project uses conventional commits for automatic versioning:
fix: description— patch releasefeat: description— minor releasefeat!: description— major release
License
The MIT License (MIT). Please see License File for more information.
All versions of laravel-telegram-notifications with dependencies
illuminate/contracts Version ^11.0||^12.0
illuminate/http Version ^11.0||^12.0
illuminate/notifications Version ^11.0||^12.0
illuminate/support Version ^11.0||^12.0
monolog/monolog Version ^3.0
spatie/laravel-package-tools Version ^1.16