laravel-notification-channels/telegram
| Install | |
|---|---|
composer require laravel-notification-channels/telegram |
|
| Latest Version: | 7.0.0 |
| PHP: | ^8.3 |
| License: | MIT |
| Last Updated: | Aug 24, 2026 |
| Links: | GitHub · Packagist |
Telegram Notifications Channel for Laravel
This package makes it easy to send Telegram notifications from Laravel via the Telegram Bot API.
Contents
- Installation
- Usage
- Text Notification
- Send with Keyboard
- Send a Dice
- Send a Poll
- Send a Rich Message
- Attach a Contact
- Attach an Audio
- Attach a Photo
- Attach a Document
- Attach a Location
- Attach a Venue
- Attach a Video
- Attach a GIF File
- Attach a Sticker
- Send a Media Group
- Routing a Message
- Handling Response
- Exception Handling
- On-Demand Notifications
- Sending to Multiple Recipients
- Using the Telegram Client Directly
- Available Methods
- Alternatives
- Changelog
- Testing
- Security
- Contributing
- Credits
- License
Installation
You can install the package via composer:
composer require laravel-notification-channels/telegram
Setting up your Telegram Bot
Talk to @BotFather and generate a Bot API token.
Then, configure your Telegram Bot API token:
# config/services.php
'telegram' => [
'token' => env('TELEGRAM_BOT_TOKEN', 'YOUR BOT TOKEN HERE'),
// Optional bridge / self-hosted Bot API server
// 'base_uri' => env('TELEGRAM_API_BASE_URI'),
// Optional Guzzle HTTP client options.
// Defaults: 30s request timeout, 10s connection timeout.
// 'http' => [
// 'timeout' => 30,
// 'connect_timeout' => 10,
// 'proxy' => env('TELEGRAM_HTTP_PROXY'),
// ],
],
[!NOTE] The package also supports the legacy
services.telegram-bot-api.*config keys for backward compatibility, butservices.telegram.*is the preferred configuration format.
Retrieving Chat ID
To send notifications to a Telegram user, channel, or group, you need its chat ID.
You can retrieve it by fetching your bot updates with the getUpdates method described in the Telegram Bot API docs.
An update is an object whose shape depends on the event type, such as message, callback_query, or poll. For the full list of fields, see the Telegram Bot API docs.
To make this easier, the package ships with TelegramUpdates, which lets you fetch updates and inspect the chat IDs you need.
Keep in mind that the user must interact with your bot first before you can obtain their chat ID and store it for future notifications.
Here's an example of fetching an update:
use NotificationChannels\Telegram\TelegramUpdates;
// Response is an array of updates.
$updates = TelegramUpdates::create()
// (Optional) Get the latest update.
// NOTE: All previous updates will be forgotten using this method.
// ->latest()
// (Optional) Limit to 2 updates. By default, updates start with the earliest unconfirmed update.
->limit(2)
// (Optional) Add more request parameters.
->options([
'timeout' => 0,
])
->get();
if ($updates['ok']) {
// Chat ID
$chatId = $updates['result'][0]['message']['chat']['id'];
}
[!NOTE] This method will not work while an outgoing webhook is configured.
For the full list of supported options(), see the Telegram Bot API docs.
Proxy or Bridge Support
You may not be able to send notifications directly if the Telegram Bot API is blocked in your region.
In that case, you can either configure a proxy by following the Guzzle instructions here or
point the package at a bridge or self-hosted Bot API server by setting the base_uri config shown above.
You can also set HTTPS_PROXY in your .env file, or set the proxy key (or any other Guzzle request option, such as timeout) in the services.telegram.http config array shown above.
Usage
You can now return the channel from your notification's via() method.
Text Notification
use NotificationChannels\Telegram\TelegramMessage;
use Illuminate\Notifications\Notification;
class InvoicePaid extends Notification
{
public function via($notifiable)
{
return ['telegram'];
}
public function toTelegram($notifiable)
{
$url = url('/invoice/' . $notifiable->invoice->id);
$user = $notifiable->name;
return TelegramMessage::create()
->to($notifiable->telegram_user_id)
->content('Hello there!')
->line('Your invoice has been *PAID*')
->lineIf($notifiable->amount > 0, "Amount paid: {$notifiable->amount}")
->escapedLine("Thank you, {$user}!")
// ->view('notification', ['url' => $url])
->button('View Invoice', $url)
->button('Download Invoice', $url);
// Other fluent helpers are also available:
// ->businessConnectionId('business-connection-id')
// ->messageThreadId(42)
// ->protectContent()
// ->directMessagesTopicId(1001)
// ->allowPaidBroadcast()
// ->messageEffectId('5104841245755180586')
// ->replyParameters(['message_id' => 123])
// ->suggestedPostParameters(['price' => ['amount' => 10, 'currency' => 'XTR']])
// ->entities([...])
// ->linkPreviewOptions(['is_disabled' => true])
// ->sendWhen($notifiable->amount > 0)
// ->buttonWithWebApp('Open Web App', $url)
// ->buttonWithCallback('Confirm', 'confirm_invoice '.$this->invoice->id)
// ->buttonWithCallback('Delete', 'delete', style: 'danger')
// ->buttonWithCallback('Approve', 'approve', style: 'success')
// ->button('Details', $url, iconCustomEmojiId: '5368324170671202286')
// ->disabledButton('Expired')
// ->forceReply()
// ->receiverUserId($notifiable->telegram_user_id)
// ->callbackQueryId($callbackQueryId)
// ->replaceCallbackQueryMessage()
// ->ephemeralMessageParameters(['receiver_user_id' => $notifiable->telegram_user_id])
}
}
Here's a screenshot preview of the above notification on Telegram Messenger:

Send with Keyboard
public function toTelegram($notifiable)
{
return TelegramMessage::create()
->to($notifiable->telegram_user_id)
->content('Choose an option:')
->keyboard('Button 1')
->keyboard('Button 2');
}
Preview:
You can also request structured input from the keyboard:
TelegramMessage::create()
->content('Please share your phone number or location')
->keyboard('Send your number', requestContact: true)
->keyboard('Send your location', requestLocation: true);
Preview:
Send a Dice
use NotificationChannels\Telegram\TelegramDice;
public function toTelegram($notifiable)
{
return TelegramDice::create()
->to($notifiable->telegram_user_id)
->emoji('🎯');
}
Preview:
Send a Poll
public function toTelegram($notifiable)
{
return TelegramPoll::create()
->to($notifiable->telegram_user_id)
->question('Which is your favorite Laravel Notification Channel?')
->choices(['Telegram', 'Facebook', 'Slack']);
// Other fluent helpers are also available:
// ->description('Voting closes in an hour')
// ->quiz(0)
// ->explanation('Telegram, of course!')
// ->isAnonymous(false)
// ->allowsMultipleAnswers()
// ->allowsRevoting()
// ->shuffleOptions()
// ->allowAddingOptions()
// ->hideResultsUntilCloses()
// ->membersOnly()
// ->countryCodes(['US', 'GB'])
// ->openPeriod(600)
// ->closeDate(now()->addHour()->getTimestamp())
// ->media(['type' => 'photo', 'media' => $url])
}
Preview:
Send a Rich Message
Rich messages (Bot API 10.1) let you send long-form, formatted posts built from blocks or from a single Markdown / HTML document.
The simplest way is to pass Markdown (or HTML) content, referencing any attached media with tg://photo?id=, tg://video?id= or tg://audio?id= links:
use NotificationChannels\Telegram\TelegramRichMessage;
public function toTelegram($notifiable)
{
return TelegramRichMessage::create()
->to($notifiable->telegram_user_id)
->markdown(<<<'MD'
# Invoice #1234 Paid
Thanks for your payment, we've credited your account.
[](tg://photo?id=receipt)
MD)
->media('receipt', ['type' => 'photo', 'media' => 'https://example.com/receipt.jpg'])
->button('View Invoice', url('/invoice/1234'));
// Or render a Blade view as the HTML content instead:
// ->view('invoices.telegram', ['invoice' => $notifiable->invoice])
}
For full control over the layout, build the message out of blocks:
public function toTelegram($notifiable)
{
return TelegramRichMessage::create()
->to($notifiable->telegram_user_id)
->heading('Invoice #1234 Paid')
->paragraph(['Thanks for your payment, ', ['type' => 'bold', 'text' => $notifiable->name], '!'])
->photoBlock(
['type' => 'photo', 'media' => 'https://example.com/receipt.jpg'],
['text' => 'Your receipt', 'credit' => 'Billing']
)
->listBlock(['Plan: Pro', 'Amount: $49.00', 'Next renewal: in 30 days'])
->table(
cells: [
[['blocks' => [['type' => 'paragraph', 'text' => 'Item']]], ['blocks' => [['type' => 'paragraph', 'text' => 'Total']]]],
[['blocks' => [['type' => 'paragraph', 'text' => 'Pro plan']]], ['blocks' => [['type' => 'paragraph', 'text' => '$49.00']]]],
],
bordered: true,
striped: true,
caption: 'Invoice summary'
)
->expandableBlockquote('The full terms of the plan...')
->divider()
->footer('Questions? Just reply to this message.')
->buttons([
['text' => 'Download Invoice', 'url' => url('/invoice/1234/download')],
['text' => 'View Receipt', 'callback_data' => 'receipt 1234', 'style' => 'primary'],
], align: 'center');
}
All the common methods (to(), button(), keyboard(), disableNotification(), replyParameters(), ...) work as usual and are sent alongside the encoded rich_message param.
[!NOTE] Block types without a dedicated builder (such as
collageandslideshow) can be added with theblock()escape hatch. Direct file uploads for rich message media are not supported: reference media by URL orfile_id.
Streaming Drafts
Drafts (sendRichMessageDraft) are temporary messages shown to the user while they're still being written. Sending again with the same draftId() animates the replacement of the previous content, which makes TelegramRichMessageDraft a good fit for streaming an AI generated answer as it's produced:
use NotificationChannels\Telegram\TelegramRichMessageDraft;
$draft = TelegramRichMessageDraft::create()
->to($chatId)
->draftId($chatId) // Any non-zero integer, stable for this stream.
->canStop() // Optional: show a button that stops the generation.
->keepOnStop(); // Optional: keep the partial draft around when it's stopped.
$buffer = '';
foreach ($stream as $chunk) {
$buffer .= $chunk;
// Replaces the content of the draft with the answer so far.
$draft->markdown($buffer)->send();
}
// Turns the draft into a permanent message via `sendRichMessage`.
$draft->markdown($buffer)->finalize();
Every content and block builder of TelegramRichMessage is available on the draft, so you can stream blocks instead of Markdown if you prefer.
[!IMPORTANT] Drafts can only be sent to private chats and the
draft_idmust be a non-zero integer. Batch your updates (roughly onesend()every 0.5-1 seconds) instead of sending one per token, otherwise your bot will quickly hit the API rate limits. A draft that's never finalized simply disappears: onlyfinalize()leaves a permanent message behind. The endpoint acceptschat_id,message_thread_id,draft_id,rich_message,can_stopandkeep_on_stoponly, so buttons and notification flags are applied when the draft is finalized.
Attach a Contact
public function toTelegram($notifiable)
{
return TelegramContact::create()
->to($notifiable->telegram_user_id) // Optional
->firstName('John')
->lastName('Doe') // Optional
->phoneNumber('00000000');
}
Preview:
Attach an Audio
public function toTelegram($notifiable)
{
return TelegramFile::create()
->to($notifiable->telegram_user_id) // Optional
->content('Audio') // Optional caption
->captionEntities([
['offset' => 0, 'length' => 5, 'type' => 'bold'],
])
->audio('/path/to/audio.mp3');
}
Preview:

Attach a Photo
public function toTelegram($notifiable)
{
return TelegramFile::create()
->to($notifiable->telegram_user_id) // Optional
->content('Awesome *bold* text and [inline URL](http://www.example.com/)')
->showCaptionAboveMedia()
->file('/storage/archive/6029014.jpg', 'photo'); // local photo
}
You can also use a helper method with a remote file or Telegram file ID:
TelegramFile::create()
->photo('https://samples-files.com/samples/images/jpg/1280-720-sample.jpg');
If you already know whether you're dealing with a URL or a Telegram file ID, use the explicit methods instead — they validate the input and skip the detection heuristics:
use NotificationChannels\Telegram\Enums\FileType;
TelegramFile::create()
->url('https://samples-files.com/samples/images/jpg/1280-720-sample.jpg', FileType::Photo);
TelegramFile::create()
->fileId('AgACAgQAAxkDAAIBLGV3', FileType::Photo);
Preview:

Attach a Document
public function toTelegram($notifiable)
{
return TelegramFile::create()
->to($notifiable->telegram_user_id) // Optional
->content('Here is your PDF document')
->document('https://samples-files.com/samples/documents/pdf/sample-1-small-size.pdf');
}
Preview:
If you want to control the filename, you need to upload the actual file contents instead of passing the remote URL directly:
$contents = file_get_contents('https://samples-files.com/samples/documents/pdf/sample-1-small-size.pdf');
TelegramFile::create()
->content('Did you know we can set a custom filename too?')
->document($contents, 'sample.pdf');
Preview:
Raw file contents are also supported when you provide a filename:
TelegramFile::create()
->document('Hello Text Document Content', 'hello.txt');
Preview:
Attach a Location
public function toTelegram($notifiable)
{
return TelegramLocation::create()
->to($notifiable->telegram_user_id)
->latitude('40.6892494')
->longitude('-74.0466891');
}
Preview:
You can also send live location
public function toTelegram($notifiable)
{
return TelegramLocation::create()
->to($notifiable->telegram_user_id)
->latitude('40.6892494')
->longitude('-74.0466891')
->horizontalAccuracy(25)
->livePeriod(300)
->heading(180)
->proximityAlertRadius(50);
}
Preview:
Attach a Venue
public function toTelegram($notifiable)
{
return TelegramVenue::create()
->to($notifiable->telegram_user_id)
->latitude('38.8951')
->longitude('-77.0364')
->title('Grand Palace')
->address('Bangkok, Thailand');
}
Preview:
Attach a Video
public function toTelegram($notifiable)
{
return TelegramFile::create()
->to($notifiable->telegram_user_id)
->content('Sample *video* notification!')
->video('https://samples-files.com/samples/video/mp4/sample2-720x480.mp4');
}
Preview:
Attach a GIF File
public function toTelegram($notifiable)
{
return TelegramFile::create()
->to($notifiable->telegram_user_id)
->content('Woot! We can send animated gif notifications too!')
->animation('https://disk.sample.cat/samples/gif/sample-2.gif');
}
Local files work the same way:
TelegramFile::create()
->animation('/path/to/some/animated.gif');
Preview:
Attach a Sticker
public function toTelegram($notifiable)
{
return TelegramFile::create()
->to($notifiable->telegram_user_id)
->sticker(storage_path('telegram/AnimatedSticker.tgs'));
}
Preview:
Send a Media Group
Use TelegramMediaGroup to send multiple items in a single group.
use NotificationChannels\Telegram\TelegramMediaGroup;
public function toTelegram($notifiable)
{
return TelegramMediaGroup::create()
->to($notifiable->telegram_user_id)
->photo('https://example.com/one.jpg', 'First image')
->photo('https://example.com/two.jpg');
}
Uploaded files are also supported:
TelegramMediaGroup::create()
->photo(storage_path('app/telegram/one.jpg'), 'First image')
->video(storage_path('app/telegram/video.mp4'), 'Release demo');
Preview:
Documents are also supported, including dynamically generated content:
TelegramMediaGroup::create()
->document('Monthly report content on-the-fly', 'Monthly report caption', 'monthly.txt')
->document('/path/to/local/file.pdf', 'pdf file caption', 'annual-report.pdf');
Preview:
Supported Input Types
Each media item can be provided as:
- A Telegram file ID
- A remote URL
- A local file path
- A stream or resource
- Raw file contents (requires a filename)
When uploading local files or raw content, the package automatically handles multipart uploads.
Media groups support albums of photo, video, audio, and document items.
[!NOTE] Telegram does not allow mixing certain media types within a single group. Documents cannot be combined with photos or videos. However, photos and videos can be sent together in the same media group.
Routing a Message
You can either send a notification by setting the recipient explicitly with to($chatId) as shown above, or define routeNotificationForTelegram() on your notifiable model:
/**
* Route notifications for the Telegram channel.
*
* @return int
*/
public function routeNotificationForTelegram()
{
return $this->telegram_user_id;
}
Handling Response
You can use notification events to handle Telegram responses. On success, your listener receives a Message object with fields appropriate to the notification type.
For the full list of response fields, refer to the Telegram Bot API Message object docs.
Exception Handling
For failures, the package provides two exception-handling hooks.
Using NotificationFailed Event
You can listen to
Illuminate\Notifications\Events\NotificationFailed, which provides a$dataarray containingto,request, andexceptionkeys.
Listener example:
use Illuminate\Notifications\Events\NotificationFailed;
class HandleNotificationFailure
{
public function handle(NotificationFailed $event)
{
// $event->notification: The notification instance.
// $event->notifiable: The notifiable entity who received the notification.
// $event->channel: The channel name.
// $event->data: The data needed to process this failure.
if ($event->channel !== 'telegram') {
return;
}
// Log the error / notify administrator or disable notification channel for the user, etc.
\Log::error('Telegram notification failed', [
'chat_id' => $event->data['to'],
'error' => $event->data['exception']->getMessage(),
'request' => $event->data['request']
]);
}
}
Using onError Callback
You can handle exceptions for an individual notification by attaching an
onErrorcallback:
public function toTelegram($notifiable)
{
return TelegramMessage::create()
->content('Hello!')
->onError(function ($data) {
\Log::error('Failed to send Telegram notification', [
'chat_id' => $data['to'],
'error' => $data['exception']->getMessage()
]);
});
}
In both methods, the $data array contains the following keys:
to: The recipient's chat ID.request: The payload sent to the Telegram Bot API.exception: The exception object containing error details.
On-Demand Notifications
Sometimes you may want to send a Telegram notification to someone who is not stored as a notifiable model. With
Notification::route, you can provide ad-hoc routing information before dispatching the notification. For more details, see the on-demand notifications docs.
use Illuminate\Support\Facades\Notification;
Notification::route('telegram', 'TELEGRAM_CHAT_ID')
->notify(new InvoicePaid($invoice));
Sending to Multiple Recipients
Using the notification facade, you can send a notification to multiple recipients at once.
[!WARNING] If you're sending bulk notifications to many users, the Telegram Bot API will not allow much more than 30 messages per second. Consider spreading out notifications over large intervals of 8—12 hours for best results.
Also note that your bot will not be able to send more than 20 messages per minute to the same group.
If you go over the limit, you'll start getting
429errors. The package automatically waits for theretry_afterduration reported by Telegram and retries once (skipped whenretry_afterexceeds 60 seconds), but sustained bursts will still fail. For more details, refer Telegram Bots FAQ.
use Illuminate\Support\Facades\Notification;
// Recipients can be an array of chat IDs or collection of notifiable entities.
Notification::send($recipients, new InvoicePaid());
Using the Telegram Client Directly
If you need lower-level Bot API access, you can use the Telegram facade:
use NotificationChannels\Telegram\Facades\Telegram;
Telegram::sendChatAction([
'chat_id' => $chatId,
'action' => 'typing',
]);
Or resolve the Telegram client directly from the container:
use NotificationChannels\Telegram\Telegram;
$telegram = app(Telegram::class);
$telegram->sendChatAction([
'chat_id' => $chatId,
'action' => 'typing',
]);
$telegram->editMessageText([
'chat_id' => $chatId,
'message_id' => $messageId,
'text' => 'Updated message text',
]);
$telegram->deleteMessage([
'chat_id' => $chatId,
'message_id' => $messageId,
]);
$telegram->sendMediaGroup([
'chat_id' => $chatId,
'media' => json_encode([
['type' => 'photo', 'media' => 'https://example.com/one.jpg', 'caption' => 'First'],
['type' => 'photo', 'media' => 'https://example.com/two.jpg'],
], JSON_THROW_ON_ERROR),
]);
$telegram->stopPoll([
'chat_id' => $chatId,
'message_id' => $pollMessageId,
]);
Available direct client helpers currently include:
sendMessage(array $params)sendFile(array $params, string $type, bool $multipart = false)sendMediaGroup(array $params, bool $multipart = false)sendPoll(array $params)sendRichMessage(array $params)sendRichMessageDraft(array $params)sendContact(array $params)sendLocation(array $params)sendVenue(array $params)sendDice(array $params)sendChatAction(array $params)editMessageText(array $params)editMessageCaption(array $params)editMessageMedia(array $params, bool $multipart = false)editMessageReplyMarkup(array $params)stopPoll(array $params)deleteMessage(array $params)deleteMessages(array $params)getUpdates(array $params)
Available Methods
For more information on supported parameters, check out these docs.
Common Methods
These methods are optional and common across all the API methods.
to(int|string $chatId)- Set recipient's chat ID.token(string $token)- Override default bot token.parseMode(enum ParseMode $mode)- Set message parse mode (ornormal()to unset). Default isParseMode::Markdown.keyboard(string $text, int $columns = 2, bool $requestContact = false, bool $requestLocation = false)- Add regular keyboard. You can add as many as you want, and they'll be placed 2 in a row by default.button(string $text, string $url, int $columns = 2, ?string $style = null, ?string $iconCustomEmojiId = null)- Add inline CTA button. Optionalstyle:'danger'(red),'success'(green),'primary'(blue). OptionaliconCustomEmojiId: custom emoji identifier shown as the button icon.buttonWithCallback(string $text, string $callbackData, int $columns = 2, ?string $style = null, ?string $iconCustomEmojiId = null)- Add inline button with callback.buttonWithWebApp(string $text, string $url, int $columns = 2, ?string $style = null, ?string $iconCustomEmojiId = null)- Add inline web app button.disabledButton(string $text, int $columns = 2, ?string $style = null, ?string $iconCustomEmojiId = null)- Add an inline button that is disabled and does nothing.forceReply(bool $force = true)- Show the reply interface to the user, as if they had manually selected the message and tapped 'Reply'. Applies to the inline and regular keyboard markups, whenever it's called.disableNotification(bool $disableNotification = true)- Send silently (notification without sound).businessConnectionId(string $businessConnectionId)- Send on behalf of a connected business account.messageThreadId(int $messageThreadId)- Send to a forum / topic thread.directMessagesTopicId(int $directMessagesTopicId)- Send to a channel direct message topic.protectContent(bool $protect = true)- Protect content from forwarding and saving.allowPaidBroadcast(bool $allow = true)- Allow paid high-throughput broadcasts.messageEffectId(string $messageEffectId)- Add a private-chat message effect.ephemeralMessageParameters(array $parameters)- Set theEphemeralMessageParametersof the message. Repeated calls are merged into the parameters set so far.receiverUserId(int $userId)- Send an ephemeral message that is visible only to the given user (ephemeral_message_parameters.receiver_user_id).callbackQueryId(string $callbackQueryId)- Send an ephemeral message in response to the given callback query.replaceCallbackQueryMessage(bool $replace = true)- Show the ephemeral message in place of the original message. Must stay false for callback queries coming from ephemeral messages.replyParameters(array $replyParameters)- Set structured reply parameters.suggestedPostParameters(array $suggestedPostParameters)- Set suggested post parameters for supported direct message topics.options(array $options)- Add/override payload parameters. Array values are JSON encoded automatically when the request is sent.sendWhen(bool $condition)- Set condition for sending. If the condition is true, the notification will be sent; otherwise, it will not.onError(callable $callback)- Set error handler (receives a data array withto,request,exceptionkeys).getPayloadValue(string $key)- Get specific payload value.
Telegram Message Methods
Telegram message notifications are used to send text messages to the user. Supports Telegram formatting options
content(string $content, int $limit = null)- Set message content with optional length limit. Supports markdown.line(string $content)- Add new line of content.lineIf(bool $condition, string $content)- Conditionally add new line.escapedLine(string $content)- Add a line escaped for the currently set parse mode: the full special character set forMarkdownV2, only_,*,`and[for the default legacyMarkdownmode, and no escaping forHTMLor when no parse mode is set. Set the parse mode before calling this method.view(string $view, array $data = [], array $mergeData = [])- Use Blade template with Telegram supported HTML or Markdown syntax content if you wish to use a view file instead of thecontent()method.entities(array $entities)- Set explicit message entities instead of usingparse_mode.linkPreviewOptions(array $linkPreviewOptions)- Set Telegram link preview options.chunk(int $limit = 4096)- Split long messages into chunks of at most$limitUTF-8 characters (Telegram's limit is 4096). The splitter prefers breaking at the last newline within a chunk, then the last space, and only hard-splits when neither is available.
[!NOTE] A one second pause is added between chunks to comply with Telegram's rate limits.
A chunk boundary can still land inside a Markdown entity (e.g. an unclosed
*bold*), which Telegram rejects. Prefer chunk-sized paragraphs, or disable the parse mode withnormal()for machine-generated content.
Helper Methods:
escapeMarkdown(string $content)- Escape a string to make it safe for theMarkdownV2parse mode.escapeLegacyMarkdown(string $content)- Escape the characters supported by the legacyMarkdownparse mode (_,*,`,[).
Telegram Location Methods
Telegram location messages are used to share a geographical location with the user.
latitude(float|string $latitude)- Set location latitude.longitude(float|string $longitude)- Set location longitude.horizontalAccuracy(float|int|string $horizontalAccuracy)- Set the location accuracy radius in meters.livePeriod(int $livePeriod)- Set the live location period in seconds.heading(int $heading)- Set the movement direction in degrees.proximityAlertRadius(int $proximityAlertRadius)- Set the proximity alert radius in meters.
Telegram Venue Methods
Telegram venue messages are used to share a geographical location information about a venue.
latitude(float|string $latitude)- Set venue latitude.longitude(float|string $longitude)- Set venue longitude.title(string $title)- Set venue name/title.address(string $address)- Set venue address.foursquareId(string $foursquareId)- (Optional) Set Foursquare identifier of the venue.foursquareType(string $foursquareType)- (Optional) Set Foursquare type of the venue, if known.googlePlaceId(string $googlePlaceId)- (Optional) Set Google Places identifier of the venue.googlePlaceType(string $googlePlaceType)- (Optional) Set Google Places type of the venue.
Telegram File Methods
Telegram file messages are used to share various types of files with the user.
content(string $content)- Set file caption. Supports markdown.view(string $view, array $data = [], array $mergeData = [])- Use Blade template for caption.captionEntities(array $captionEntities)- Set explicit caption entities.showCaptionAboveMedia(bool $show = true)- Show caption above supported media types.file(string|resource|StreamInterface $file, FileType|string $type, string $filename = null)- Attach a local path, remote URL, Telegram file ID, stream/resource, or raw file contents. Types:photo,audio,document,video,animation,voice,video_note,sticker,live_photo(useEnums\FileType). Pass a filename when the string represents raw file contents. An unknown type string throwsCouldNotSendNotification::invalidFileType().fileId(string $fileId, FileType|string $type = FileType::Document)- Attach an existing Telegram file by its file ID, bypassing the local-file/URL detection heuristics offile().url(string $url, FileType|string $type = FileType::Document)- Attach a remote file by its URL, bypassing the detection heuristics offile().
Helper Methods:
photo(string $file)- Send photo.audio(string $file)- Send audio (MP3).document(string $file, string $filename = null)- Send document or any file as document.video(string $file)- Send video.animation(string $file)- Send animated GIF.voice(string $file)- Send voice note (OGG/OPUS).videoNote(string $file)- Send video note (≤1min, rounded square video).sticker(string $file)- Send sticker (static PNG/WEBP, animated .TGS, or video .WEBM stickers).livePhoto(string $file)- Send live photo.
Telegram Media Group Methods
Telegram media groups are albums of
photo,video,audio,document, orlive_photoitems sent as a single notification.
photo(string|resource|StreamInterface $media, string $caption = null, string $filename = null)- Add a photo to the group.video(string|resource|StreamInterface $media, string $caption = null, string $filename = null)- Add a video to the group.audio(string|resource|StreamInterface $media, string $caption = null, string $filename = null)- Add an audio file to the group.document(string|resource|StreamInterface $media, string $caption = null, string $filename = null)- Add a document to the group.livePhoto(string|resource|StreamInterface $media, string $caption = null, string $filename = null)- Add a live photo to the group.hasAttachments()- Determine if the group contains uploaded files and requires multipart transport.
Each media item may be a Telegram file ID, a URL, a local path, a stream/resource, or raw file contents when paired with a filename.
Telegram Contact Methods
Telegram contact messages are used to share contact information with the user.
phoneNumber(string $phone)- Set contact phone.firstName(string $name)- Set contact first name.lastName(string $name)- Set contact last name (optional).vCard(string $vcard)- Set contact vCard (optional).
Telegram Dice Methods
Telegram dice messages are interactive emoji dice / darts / slots / bowling style messages.
emoji(string $emoji)- Set the dice emoji (🎲,🎯,🎳,🏀,⚽,🎰, etc.).
Telegram Poll Methods
Telegram polls are a type of interactive message that allows users to vote on a question. Polls can be used to gather feedback, make decisions, or even run contests.
question(string $question)- Set poll question.choices(array $choices)- Set poll choices. Each choice may be a string or anInputPollOptionarray such as['text' => 'Yes', 'media' => [...]].description(string $description)- Set poll description.descriptionParseMode(enum ParseMode|string $mode)- Set the parse mode of the description.descriptionEntities(array $entities)- Set explicit description entities instead of using a parse mode.type(string $type)- Set poll type (regularorquiz).quiz(int|array $correctOptionIds)- Turn the poll into a quiz and set the zero based index(es) of the correct choice(s).explanation(string $explanation)- Set the text shown when a user chooses an incorrect quiz answer.explanationParseMode(enum ParseMode|string $mode)- Set the parse mode of the explanation.explanationEntities(array $entities)- Set explicit explanation entities instead of using a parse mode.isAnonymous(bool $anonymous = true)- Make the poll anonymous.allowsMultipleAnswers(bool $allow = true)- Allow multiple answers.allowsRevoting(bool $allow = true)- Allow users to change their vote.shuffleOptions(bool $shuffle = true)- Shuffle the choices for each user.allowAddingOptions(bool $allow = true)- Allow users to add their own choices.hideResultsUntilCloses(bool $hide = true)- Hide the results until the poll is closed.membersOnly(bool $membersOnly = true)- Restrict voting to the members of the chat.countryCodes(array $codes)- Restrict voting to users from the given two letter country codes.openPeriod(int $seconds)- Set how long the poll stays open after creation.closeDate(int $timestamp)- Set the Unix timestamp at which the poll closes automatically.media(array $media)- Set theInputPollMediashown with the question.explanationMedia(array $media)- Set theInputPollMediashown with the quiz explanation.
Telegram Rich Message Methods
Telegram rich messages are long-form posts built from an
InputRichMessage. You can either provide Markdown / HTML content or compose the message out of blocks (or both). EveryRichTextparameter accepts a plain string or a rich text array, which is passed through to the API untouched.
Content Methods:
markdown(string $markdown)- Set the Markdown content of the message. Also settable via the constructor /create().html(string $html)- Set the HTML content of the message.view(string $view, array $data = [], array $mergeData = [])- Render a Blade template as the HTML content.media(string $id, array $media)- Attach anInputRichMessageMediaitem that can be referenced from the content withtg://photo?id=,tg://video?id=,tg://document?id=ortg://audio?id=links. The$idmust be 1-64 characters long and contain only letters, digits, underscores and hyphens, otherwise aCouldNotSendNotificationexception is thrown.rtl(bool $rtl = true)- Render the message right-to-left (is_rtl).skipEntityDetection(bool $skip = true)- Skip automatic detection of entities such as links and mentions.getRichMessage()- Get theInputRichMessagearray built so far.
Block Methods:
Each of these appends an
InputRichBlockto the message, in the order they are called.
paragraph(string|array $text)- Add a paragraph.heading(string|array $text, int $size = 1)- Add a heading of the given size.preformatted(string|array $text, ?string $language = null)- Add a preformatted (pre) block with optional syntax highlighting language.footer(string|array $text)- Add a footer.divider()- Add a horizontal divider.math(string $expression)- Add a mathematical expression.anchor(string $name)- Add a named anchor that can be linked to.blockquote(array|string $blocks, string|array|null $credit = null)- Add a blockquote. A string is wrapped into a single paragraph block.expandableBlockquote(string|array $text, string|array|null $credit = null)- Add a blockquote that can be expanded and collapsed back.pullquote(string|array $text, string|array|null $credit = null)- Add a pullquote.details(string|array $summary, array $blocks, bool $isOpen = false)- Add a collapsible details block.table(array $cells, bool $bordered = false, bool $striped = false, string|array|null $caption = null, bool $compact = false)- Add a table from rows ofRichBlockTableCellarrays.$compactrenders the cells with smaller indents.buttons(array $buttons, ?string $align = null)- Add a row of 1-8RichMessageButtonarrays, optionally alignedleft,centerorright.listBlock(array $items)- Add a list. Each item may be a string (wrapped into a single paragraph block) or anInputRichBlockListItemarray (blocks,has_checkbox,is_checked,value,type).thinking(string|array $text)- Add a thinking block.map(float $latitude, float $longitude, int $zoom, int $width, int $height)- Add a map block.photoBlock(array $photo, ?array $caption = null)- Add a photo block from anInputMediaPhotoarray with an optionalRichBlockCaption.videoBlock(array $video, ?array $caption = null)- Add a video block.audioBlock(array $audio, ?array $caption = null)- Add an audio block.animationBlock(array $animation, ?array $caption = null)- Add an animation block.voiceNoteBlock(array $voiceNote, ?array $caption = null)- Add a voice note block.documentBlock(array $document, ?array $caption = null)- Add a general file block from anInputMediaDocumentarray.block(array $block)- Escape hatch to append any rawInputRichBlockarray, such ascollageorslideshow.
Draft Methods:
TelegramRichMessageDraftextendsTelegramRichMessage, so every content and block method above is available on a draft as well. See Streaming Drafts.
draftId(int $draftId)- Set the identifier of the draft. Must be a non-zero integer, otherwise aCouldNotSendNotificationexception is thrown. Sending repeatedly with the same identifier animates the replacement of the previously sent content.canStop(bool $canStop = true)- Show the user a button to stop further drafts. The bot receives astopped_message_generationupdate when it's pressed.keepOnStop(bool $keepOnStop = true)- Keep the draft in the chat when the stop button is pressed. It still disappears after a short time, so send the partial content as a new message to preserve it.send()- Send (or replace) the draft viasendRichMessageDraft. Throws aCouldNotSendNotificationexception when nodraftId()was given.finalize()- Send the current content as a permanent message viasendRichMessage, dropping the draft-only params (draft_id,can_stopandkeep_on_stop). The draft state is left untouched.
Alternatives
For advanced usage, please consider using telegram-bot-sdk instead.
Changelog
Please see CHANGELOG for details about recent changes.
Testing
# Run the test suite
$ composer test
# Run static analysis
$ composer analyse
# Fix code style
$ composer format
# Run mutation testing (requires Xdebug or PCOV)
$ composer test-mutation
Security
If you discover any security related issues, please email syed@lukonet.com instead of using the issue tracker.
Contributing
Please see CONTRIBUTING for details.
Credits
License
The MIT License (MIT). Please see License File for more information.
Related Packages
toastr.js for Laravel 5.2 easy notification like growl for example