From f08f2866c480f11d26b1bd59defcafd4d9607977 Mon Sep 17 00:00:00 2001 From: Irfaq Syed Date: Thu, 17 Oct 2024 01:47:29 +0530 Subject: [PATCH] Update README --- README.md | 191 ++++++++++++++++++++++++++++++++++++++---------------- 1 file changed, 135 insertions(+), 56 deletions(-) diff --git a/README.md b/README.md index 63c3f36..ac339b4 100644 --- a/README.md +++ b/README.md @@ -27,15 +27,16 @@ This package makes it easy to send Telegram notification using [Telegram Bot API - [Attach a GIF File](#attach-a-gif-file) - [Routing a Message](#routing-a-message) - [Handling Response](#handling-response) + - [Exception Handling](#exception-handling) - [On-Demand Notifications](#on-demand-notifications) - [Sending to Multiple Recipients](#sending-to-multiple-recipients) - [Available Methods](#available-methods) - - [Shared Methods](#shared-methods) - - [Telegram Message methods](#telegram-message-methods) - - [Telegram Location methods](#telegram-location-methods) - - [Telegram File methods](#telegram-file-methods) - - [Telegram Contact methods](#telegram-contact-methods) - - [Telegram Poll methods](#telegram-poll-methods) + - [Common Methods](#common-methods) + - [Telegram Message Methods](#telegram-message-methods) + - [Telegram Location Methods](#telegram-location-methods) + - [Telegram File Methods](#telegram-file-methods) + - [Telegram Contact Methods](#telegram-contact-methods) + - [Telegram Poll Methods](#telegram-poll-methods) - [Alternatives](#alternatives) - [Changelog](#changelog) - [Testing](#testing) @@ -183,7 +184,9 @@ class InvoicePaid extends Notification Here's a screenshot preview of the above notification on Telegram Messenger: ![Laravel Telegram Notification Example](https://user-images.githubusercontent.com/1915268/66616627-39be6180-ebef-11e9-92cc-f2da81da047a.jpg) + ### Send with Keyboard + ```php public function toTelegram($notifiable) { @@ -192,8 +195,8 @@ public function toTelegram($notifiable) ->content('Choose an option:') ->keyboard('Button 1') ->keyboard('Button 2'); - // ->keyboard('send your number', request_contact: true) - // ->keyboard('send your location', request_location: true); + // ->keyboard('Send your number', requestContact: true) + // ->keyboard('Send your location', requestLocation: true); } ``` @@ -207,9 +210,9 @@ Preview: public function toTelegram($notifiable) { return TelegramPoll::create() - ->to($notifiable) - ->question("Aren't Laravel Notification Channels awesome?") - ->choices(['Yes', 'YEs', 'YES']); + ->to($chatId) + ->question('What is your favorite programming language?') + ->choices(['PHP', 'Python', 'JavaScript', 'Java', 'C#']); } ``` @@ -351,10 +354,69 @@ public function routeNotificationForTelegram() ### Handling Response -You can make use of the [notification events](https://laravel.com/docs/10.x/notifications#notification-events) to handle the response from Telegram. On success, your event listener will receive a [Message](https://core.telegram.org/bots/api#message) object with various fields as appropriate to the notification type. +You can make use of the [notification events](https://laravel.com/docs/11.x/notifications#notification-events) to handle the response from Telegram. On success, your event listener will receive a [Message](https://core.telegram.org/bots/api#message) object with various fields as appropriate to the notification type. For a complete list of response fields, please refer the Telegram Bot API's [Message object](https://core.telegram.org/bots/api#message) docs. +### Exception Handling + +In case of failures, the package provides two ways to handle exceptions. + +#### Using NotificationFailed Event + +You can listen to the `Illuminate\Notifications\Events\NotificationFailed` event, which provides a `$data` array containing `to`, `request`, and `exception` keys. + +Listener example: +```php +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 individual notifications using the `onError` method in your notification: + +```php +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 need to send a notification to someone who is not stored as a "user" of your application. Using the `Notification::route` method, you may specify ad-hoc notification routing information before sending the notification. For more details, you can check out the [on-demand notifications][link-on-demand-notifications] docs. @@ -386,61 +448,78 @@ Notification::send($recipients, new InvoicePaid()); ## Available Methods -### Shared Methods +For more information on supported parameters, check out these [docs](https://core.telegram.org/bots/api#sendmessage). -> These methods are optional and shared across all the API methods. +### Common Methods -- `to(int|string $chatId)`: Recipient's chat id. -- `token(string $token)`: Bot token if you wish to override the default token for a specific notification. -- `button(string $text, string $url, int $columns = 2)`: Adds an inline "Call to Action" button. You can add as many as you want, and they'll be placed 2 in a row by default. -- `buttonWithCallback(string $text, string $callback_data, int $columns = 2)`: Adds an inline button with the given callback data. You can add as many as you want, and they'll be placed 2 in a row by default. -- `buttonWithWebApp(string $text, string $url, int $columns = 2)`: Adds an inline button that opens a web application when clicked. This button can be used to direct users to a specific web app. -- `disableNotification(bool $disableNotification = true)`: Send the message silently. Users will receive a notification with no sound. -- `options(array $options)`: Allows you to add additional params or override the payload. -- `sendWhen(bool $condition)`: Sets a condition for sending the notification. If the condition is true, the notification will be sent; otherwise, it will not. -- `onError(Closure $callback)`: Sets a callback function to handle exceptions. Callback receives an array with `to`, `request`, `exception` keys. -- `getPayloadValue(string $key)`: Get payload value for given key. +> These methods are optional and common across all the API methods. -### Telegram Message 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 (or `normal()` to unset). Default is `ParseMode::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)` - Add inline CTA button. +- `buttonWithCallback(string $text, string $callbackData, int $columns = 2)` - Add inline button with callback. +- `buttonWithWebApp(string $text, string $url, int $columns = 2)` - Add inline web app button. +- `disableNotification(bool $disableNotification = true)` - Send silently (notification without sound). +- `options(array $options)` - Add/override payload parameters. +- `sendWhen(bool $condition)` - Set condition for sending. If the condition is true, the notification will be sent; otherwise, it will not. +- `onError(Closure $callback)` - Set error handler (receives a data array with `to`, `request`, `exception` keys). +- `getPayloadValue(string $key)` - Get specific payload value. -For more information on supported parameters, check out these [docs](https://core.telegram.org/bots/api#sendmessage). +### Telegram Message Methods + +Telegram message notifications are used to send text messages to the user. Supports [Telegram formatting options](https://core.telegram.org/bots/api#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 escaped content line (for Markdown). +- `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 the `content()` method. +- `chunk(int $limit = 4096)` - Split long messages (rate limited to 1/second). + +> **Note:** Chunked messages will be rate limited to one message per second to comply with rate limitation requirements from Telegram. + +### 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. + +### Telegram File Methods + +Telegram file messages are used to share various types of files with the user. -- `content(string $content, int $limit = null)`: Notification message, supports markdown. For more information on supported markdown styles, check out these [docs](https://core.telegram.org/bots/api#formatting-options). -- `line(string $content)`: Adds a message in a new line. -- `lineIf(bool $boolean, string $line)`: Adds a message in a new line if the given condition is true. -- `escapedLine(string $content)`: Adds a message in a new line while escaping special characters (For Markdown). -- `view(string $view, array $data = [], array $mergeData = [])`: (optional) Blade template name with Telegram supported HTML or Markdown syntax content if you wish to use a view file instead of the `content()` method. -- `chunk(int $limit = 4096)`: (optional) Message chars chunk size to send in parts (For long messages). Note: Chunked messages will be rate limited to one message per second to comply with rate limitation requirements from Telegram. +- `content(string $content)` - Set file caption. Supports markdown. +- `view(string $view, array $data = [], array $mergeData = [])` - Use Blade template for caption. +- `file(string|resource|StreamInterface $file, string $type, string $filename = null)` - Attach file by path/URL. Types: `photo`, `audio`, `document`, `video`, `animation`, `voice`, `video_note`. Use helper methods below for convenience. Filename is optional, ex: `sample.pdf`. -### Telegram Location methods +#### Helper Methods: -- `latitude(float|string $latitude)`: Latitude of the location. -- `longitude(float|string $longitude)`: Longitude of the location. +- `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). -### Telegram File methods +### Telegram Contact Methods -- `content(string $content)`: (optional) File caption, supports markdown. For more information on supported markdown styles, check out these [docs](https://core.telegram.org/bots/api#formatting-options). -- `view(string $view, array $data = [], array $mergeData = [])`: (optional) Blade template name with Telegram supported HTML or Markdown syntax content if you wish to use a view file instead of the `content()` method. -- `file(string|resource|StreamInterface $file, string $type, string $filename = null)`: Local file path or remote URL, `$type` of the file (Ex:`photo`, `audio`, `document`, `video`, `animation`, `voice`, `video_note`) and optionally filename with extension. Ex: `sample.pdf`. You can use helper methods instead of using this to make it easier to work with file attachment. -- `photo(string $file)`: Helper method to attach a photo. -- `audio(string $file)`: Helper method to attach an audio file (MP3 file). -- `document(string $file, string $filename = null)`: Helper method to attach a document or any file as document. -- `video(string $file)`: Helper method to attach a video file. -- `animation(string $file)`: Helper method to attach an animated gif file. -- `voice(string $file)`: Helper method to attach a voice note (`.ogg` file with OPUS encoded). -- `videoNote(string $file)`: Helper method to attach a video note file (Upto 1 min long, rounded square video). +Telegram contact messages are used to share contact information with the user. -### Telegram Contact methods +- `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). -- `phoneNumber(string $phoneNumber)`: Contact phone number. -- `firstName(string $firstName)`: Contact first name. -- `lastName(string $lastName)`: (optional) Contact last name. -- `vCard(string $vCard)`: (optional) Contact vcard. +### Telegram Poll Methods -### 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)`: Poll question. -- `choices(array $choices)`: Poll choices. +- `question(string $question)` - Set poll question. +- `choices(array $choices)` - Set poll choices. ## Alternatives @@ -485,7 +564,7 @@ The MIT License (MIT). Please see [License File](LICENSE.md) for more informatio [link-packagist]: https://packagist.org/packages/laravel-notification-channels/telegram [link-author]: https://github.com/irazasyed [link-contributors]: ../../contributors -[link-notification-facade]: https://laravel.com/docs/10.x/notifications#using-the-notification-facade -[link-on-demand-notifications]: https://laravel.com/docs/10.x/notifications#on-demand-notifications +[link-notification-facade]: https://laravel.com/docs/11.x/notifications#using-the-notification-facade +[link-on-demand-notifications]: https://laravel.com/docs/11.x/notifications#on-demand-notifications [link-telegram-docs-update]: https://core.telegram.org/bots/api#update [link-telegram-docs-getupdates]: https://core.telegram.org/bots/api#getupdates