mderakhshi / telegram
Laravel的Telegram通知频道
Requires
- php: ^8.1
- ext-json: *
- guzzlehttp/guzzle: ^7.2
- illuminate/contracts: ^10.0
- illuminate/notifications: ^10.0
- illuminate/support: ^10.0
Requires (Dev)
- mockery/mockery: ^1.4.4
- nunomaduro/larastan: ^2.4
- orchestra/testbench: ^8.0
- pestphp/pest: ^1.22
- pestphp/pest-plugin-laravel: ^1.4
- phpstan/extension-installer: ^1.2
- phpstan/phpstan-deprecation-rules: ^1.1
- phpstan/phpstan-phpunit: ^1.3
- phpunit/phpunit: ^9.5.10
This package is auto-updated.
Last update: 2024-09-21 08:33:22 UTC
README
本包通过使用Laravel和Telegram Bot API轻松发送Telegram通知。
内容
安装
您可以通过composer安装此包。
composer require laravel-notification-channels/telegram
设置您的Telegram机器人
与@BotFather交流并生成Bot API令牌。
然后,配置您的Telegram Bot API令牌。
# config/services.php 'telegram-bot-api' => [ 'token' => env('TELEGRAM_BOT_TOKEN', 'YOUR BOT TOKEN HERE') ],
获取聊天ID
为了向我们发送通知到您的Telegram机器人用户/频道或群组,我们需要知道它们的聊天ID。
这可以通过使用Telegram Bot API的getUpdates
方法获取您的机器人的updates
来实现,具体请参阅Telegram Bot API 文档。
update是一个包含基于更新类型的相关字段的对象,一些update对象示例有message
、callback_query
和poll
。有关字段列表的完整信息,请参阅Telegram Bot API文档。
为了使事情变得简单,该库提供了一个方便的方法,可以用来从其中解析相关聊天ID的更新。
请注意,用户必须首先与您的机器人互动,您才能获取他们的聊天ID,然后您可以将其存储在数据库中以供未来的交互或通知。
以下是一个获取更新的示例
use NotificationChannels\Telegram\TelegramUpdates; // Response is an array of updates. $updates = TelegramUpdates::create() // (Optional). Get's the latest update. NOTE: All previous updates will be forgotten using this method. // ->latest() // (Optional). Limit to 2 updates (By default, updates starting with the earliest unconfirmed update are returned). ->limit(2) // (Optional). Add more params to the request. ->options([ 'timeout' => 0, ]) ->get(); if($updates['ok']) { // Chat ID $chatId = $updates['result'][0]['message']['chat']['id']; }
注意:如果设置了出站webhook,则此方法将不起作用。
有关options
的完整参数列表,请参阅Telegram Bot API文档。
Lumen中使用
如果您在Lumen项目中使用此通知通道,您必须将以下代码添加到您的bootstrap/app.php
文件中。
# bootstrap/app.php // Make sure to create a "config/services.php" file and add the config from the above step. $app->configure('services'); # Register the notification service providers. $app->register(Illuminate\Notifications\NotificationServiceProvider::class); $app->register(NotificationChannels\Telegram\TelegramServiceProvider::class);
代理或桥接支持
如果您的国家无法访问Telegram Bot API,您可能无法发送通知。您可以按照以下说明设置代理在此处,或者通过设置上述base_uri
配置使用桥接URI使用Web桥。
您可以在.env
文件中设置HTTPS_PROXY
。
使用方法
现在您可以在Notification类中的via()
方法中使用该通道。
文本通知
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/' . $this->invoice->id); return TelegramMessage::create() // Optional recipient user id. ->to($notifiable->telegram_user_id) // Markdown supported. ->content("Hello there!") ->line("Your invoice has been *PAID*") ->line("Thank you!") // (Optional) Blade template for the content. // ->view('notification', ['url' => $url]) // (Optional) Inline Buttons ->button('View Invoice', $url) ->button('Download Invoice', $url) // (Optional) Inline Button with callback. You can handle callback in your bot instance ->buttonWithCallback('Confirm', 'confirm_invoice ' . $this->invoice->id); } }
以下是上述通知在Telegram消息应用中的截图预览
发送投票
public function toTelegram($notifiable) { return TelegramPoll::create() ->to($notifiable) ->question("Aren't Laravel Notification Channels awesome?") ->choices(['Yes', 'YEs', 'YES']); }
预览
附加联系人
public function toTelegram($notifiable) { return TelegramContact::create() ->to($notifiable->telegram_user_id) // Optional ->firstName('John') ->lastName('Doe') // Optional ->phoneNumber('00000000'); }
预览
附加音频
public function toTelegram($notifiable) { return TelegramFile::create() ->to($notifiable->telegram_user_id) // Optional ->content('Audio') // Optional Caption ->audio('/path/to/audio.mp3'); }
预览
附加图片
public function toTelegram($notifiable) { return TelegramFile::create() ->to($notifiable->telegram_user_id) // Optional ->content('Awesome *bold* text and [inline URL](http://www.example.com/)') ->file('/storage/archive/6029014.jpg', 'photo'); // local photo // OR using a helper method with or without a remote file. // ->photo('https://file-examples-com.github.io/uploads/2017/10/file_example_JPG_1MB.jpg'); }
预览
附加文档
public function toTelegram($notifiable) { return TelegramFile::create() ->to($notifiable->telegram_user_id) // Optional ->content('Did you know we can set a custom filename too?') ->document('https://file-examples-com.github.io/uploads/2017/10/file-sample_150kB.pdf', 'sample.pdf'); }
预览
附加位置
public function toTelegram($notifiable) { return TelegramLocation::create() ->latitude('40.6892494') ->longitude('-74.0466891'); }
预览
附加视频
public function toTelegram($notifiable) { return TelegramFile::create() ->content('Sample *video* notification!') ->video('https://file-examples-com.github.io/uploads/2017/04/file_example_MP4_480_1_5MG.mp4'); }
预览
附加GIF文件
public function toTelegram($notifiable) { return TelegramFile::create() ->content('Woot! We can send animated gif notifications too!') ->animation('https://sample-videos.com/gif/2.gif'); // Or local file // ->animation('/path/to/some/animated.gif'); }
预览
路由消息
您可以通过提供收件人的聊天ID给to($chatId)
方法来发送通知,就像前面的示例中所示,或者在你的通知模型中添加一个routeNotificationForTelegram()
方法。
/** * Route notifications for the Telegram channel. * * @return int */ public function routeNotificationForTelegram() { return $this->telegram_user_id; }
处理响应
您可以使用通知事件来处理来自Telegram的响应。在成功的情况下,您的监听器将收到一个包含各种字段的消息对象,这些字段根据通知类型适当设置。
有关响应字段的完整列表,请参阅Telegram Bot API的消息对象文档。
按需通知
有时您可能需要向不是您的应用程序“用户”的人发送通知。使用
Notification::route
方法,在发送通知之前,您可以指定临时的通知路由信息。有关更多详细信息,您可以查看按需通知文档。
use Illuminate\Support\Facades\Notification; Notification::route('telegram', 'TELEGRAM_CHAT_ID') ->notify(new InvoicePaid($invoice));
发送给多个收件人
使用通知外观,您可以一次向多个收件人发送通知。
如果您向多个用户发送大量通知,Telegram Bot API将不允许每秒发送超过30条消息。为了获得最佳效果,请考虑将通知分散在8-12小时的大间隔内。
请注意,您的机器人无法向同一群组发送每分钟超过20条消息。
如果您超过限制,您将开始收到
429
错误。有关更多详细信息,请参阅Telegram Bots的常见问题解答。
use Illuminate\Support\Facades\Notification; // Recipients can be an array of chat IDs or collection of notifiable entities. Notification::send($recipients, new InvoicePaid());
可用方法
共享方法
这些方法都是可选的,并且在整个API方法中共享。
to(int|string $chatId)
:收件人的聊天ID。token(string $token)
:如果需要覆盖特定通知的默认令牌,请提供机器人令牌。button(string $text, string $url, int $columns = 2)
:添加一个内联“操作”按钮。您可以添加任意多个,默认情况下它们将两行一排放置。buttonWithCallback(string $text, string $callback_data, int $columns = 2)
:添加一个带有指定回调数据的内联按钮。您可以添加任意多个,默认情况下它们将两行一排放置。disableNotification(bool $disableNotification = true)
:静默发送消息。用户将收到没有声音的通知。options(array $options)
:允许您添加额外的参数或覆盖负载。getPayloadValue(string $key)
:获取给定键的负载值。
Telegram消息方法
有关支持的参数的更多信息,请查看这些文档。
content(string $content, int $limit = null)
:通知消息,支持Markdown。有关支持的Markdown样式的更多信息,请查看这些文档。line(string $content)
:在新的行中添加一条消息。escapedLine(string $content)
:在新的行中添加一条消息,同时转义特殊字符(适用于Markdown)。view(string $view, array $data = [], array $mergeData = [])
:(可选)如果您希望使用视图文件而不是content()
方法,请提供带有Telegram支持的HTML或Markdown语法内容的Blade模板名称。chunk(int $limit = 4096)
:(可选)发送时以部分发送的消息字符块大小(适用于长消息)。注意:分块消息将被限制为每秒一条,以符合Telegram的速率限制要求。
Telegram位置方法
latitude(float|string $latitude)
:位置的纬度。longitude(float|string $longitude)
:位置的经度。
Telegram文件方法
content(string $content)
: (可选)文件标题,支持Markdown。有关支持的Markdown样式更多信息,请参阅这些文档。view(string $view, array $data = [], array $mergeData = [])
:(可选)如果您希望使用视图文件而不是content()
方法,请提供带有Telegram支持的HTML或Markdown语法内容的Blade模板名称。file(string|resource|StreamInterface $file, string $type, string $filename = null)
: 本地文件路径或远程URL,文件的类型(例如:photo
、audio
、document
、video
、animation
、voice
、video_note
)和可选的带扩展名的文件名。例如:sample.pdf
。您可以使用辅助方法而不是使用此方法,以简化文件附件的处理。photo(string $file)
: 附加照片的辅助方法。audio(string $file)
: 附加音频文件(MP3文件)的辅助方法。document(string $file, string $filename = null)
: 附加文档或任何文件作为文档的辅助方法。video(string $file)
: 附加视频文件的辅助方法。animation(string $file)
: 附加动画GIF文件的辅助方法。voice(string $file)
: 附加语音笔记(OPUS编码的.ogg
文件)的辅助方法。videoNote(string $file)
: 附加视频笔记文件(最长1分钟,方形视频)的辅助方法。
Telegram联系人方法
phoneNumber(string $phoneNumber)
: 联系电话号码。firstName(string $firstName)
: 联系人的名字。lastName(string $lastName)
: (可选)联系人的姓氏。vCard(string $vCard)
: (可选)联系人vCard。
Telegram投票方法
question(string $question)
: 投票问题。choices(array $choices)
: 投票选项。
替代方案
对于高级用法,请考虑使用telegram-bot-sdk。
变更日志
有关最近更改的信息,请参阅CHANGELOG。
测试
$ composer test
安全
如果您发现任何安全问题,请通过电子邮件syed@lukonet.com联系,而不是使用问题跟踪器。
贡献
有关详细信息,请参阅CONTRIBUTING。
致谢
许可
MIT许可(MIT)。有关更多信息,请参阅许可文件。