alimousavi/telenotify

Laravel 包,用于通过 Telegram 发送通知。

v1.0.0 2024-06-28 18:18 UTC

This package is auto-updated.

Last update: 2024-09-28 18:48:04 UTC


README

TeleNotify 是一个 Laravel 通知通道,用于通过 Telegram 机器人发送消息。

安装

您可以通过 composer 安装此包

composer require alimousavi/telenotify

可选地,您可以发布配置文件

php artisan vendor:publish --provider="AliMousavi\TeleNotify\TeleNotifyServiceProvider"

这将发布一个名为 telenotify.php 的配置文件,您可以在此处设置您的 Telegram 机器人 API 令牌。

使用方法

步骤 1:添加 Telegram 机器人令牌

将您的 Telegram 机器人令牌添加到您的 .env 文件

TELEGRAM_BOT_API_TOKEN=your-bot-api-token

步骤 2:实现 TeleNotifiable 接口

您的通知模型(例如,User、Employee)应实现 TeleNotifiable 接口并提供一个 getTelegramChatId() 方法

use Alimousavi\TeleNotify\Contracts\TeleNotifiableInterface;

class User implements TeleNotifiableInterface
{
    // ...

    public function getTelegramChatId(): string|int|null
    {
        return $this->telegram_chat_id;
    }
}

注意:使用 TeleNotifiable 特性

如果您的通知模型已经有一个 telegram_chat_id 属性,您可以使用 TeleNotifiable 特性简化实现

use Alimousavi\TeleNotify\Contracts\TeleNotifiableInterface;
use Alimousavi\TeleNotify\Traits\TeleNotifiable;

class User implements TeleNotifiableInterface
{
    use TeleNotifiable;

    // ...
}

使用特性和实现是可选的,但如果您的通知模型包含 telegram_chat_id 属性,则建议使用,以符合 TeleNotifiableInterface 的要求。

步骤 3:在通知中使用 TelegramChannel

在您的通知类中,在 via() 方法中使用 TelegramChannel::class 并实现 toTelegram() 方法

use Illuminate\Notifications\Notification;
use Alimousavi\TeleNotify\Channels\TelegramChannel;
use Alimousavi\TeleNotify\Contracts\TeleNotifiable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Bus\Queueable;

class ExampleNotification extends Notification implements ShouldQueue
{
    use Queueable;

    public function via($notifiable)
    {
        return [TelegramChannel::class];
    }

    public function toTelegram(TeleNotifiable $notifiable)
    {
        return [
            'text' => 'Hello, this is a test message from TeleNotify!',
        ];
    }
}

强烈建议实现 ShouldQueue 并使用 Queueable 特性,以利用 Laravel 的队列功能,优化性能并提高通知系统的响应性。

步骤 4:示例消息

示例 1:简单文本消息

public function toTelegram(TeleNotifiable $notifiable)
{
    return [
        'text' => 'Hello, this is a simple text message!',
    ];
}

示例 2:带有解析模式的消息

public function toTelegram(TeleNotifiable $notifiable)
{
    return [
        'text' => 'Hello, this message uses *Markdown* parse mode.',
        'parse_mode' => 'Markdown',
    ];
}

示例 3:带有禁用通知的消息

public function toTelegram(TeleNotifiable $notifiable)
{
    return [
        'text' => 'Hello, this message will not trigger a notification.',
        'disable_notification' => true,
    ];
}

有关更多自定义选项,请参阅 Telegram Bot API 文档

贡献

欢迎贡献!

许可

此包是开源软件,根据 MIT 许可证 授权。