Discord 的 Laravel 通知驱动。

v1.6.0 2024-04-01 01:31 UTC

README

Latest Version on Packagist Software License Build Status StyleCI Quality Score Code Coverage Total Downloads

此包使用 Laravel 通过 Discord bot API 简化发送通知。

内容

安装

您可以通过 composer 安装此包

composer require laravel-notification-channels/discord

接下来,您必须加载服务提供者

// config/app.php
'providers' => [
    // ...
    NotificationChannels\Discord\DiscordServiceProvider::class,
],

设置您的 Discord 机器人

  1. 创建一个 Discord 应用。

  2. 在您的 Discord 应用中点击 创建一个 Bot 用户 按钮。

  3. 将您的机器人 API 令牌粘贴到 services.php 配置文件中的 App Bot User

    // config/services.php
    'discord' => [
        'token' => 'YOUR_API_TOKEN',
    ],
  4. 将机器人添加到您的服务器,并通过运行 artisan 命令来识别它

    php artisan discord:setup

用法

在您希望通过 Discord 通知的每个模型中,您必须添加一个可用于通过 routeNotificationForDiscord 方法访问的 channel ID 属性

class Guild extends Eloquent
{
    use Notifiable;

    public function routeNotificationForDiscord()
    {
        return $this->discord_channel;
    }
}

注意:Discord 将直接消息视为常规通道。如果您希望允许用户从您的机器人接收直接消息,您需要为该用户创建一个私人频道。

一个示例工作流程可能如下所示

  1. 您的 users 表中有两个 Discord 列: discord_user_iddiscord_private_channel_id
  2. 当用户更新其 Discord 用户 ID(《discord_user_id》)时,生成并保存一个私人频道 ID(《discord_private_channel_id》)
  3. User 模型的 routeNotificationForDiscord 方法中返回用户的 discord_private_channel_id

您可以使用 NotificationChannels\Discord\Discord 类中的 getPrivateChannel 方法生成直接消息频道

use NotificationChannels\Discord\Discord;

class UserDiscordSettingsController
{
    public function store(Request $request)
    {
        $userId = $request->input('discord_user_id');
        $channelId = app(Discord::class)->getPrivateChannel($userId);

        Auth::user()->update([
            'discord_user_id' => $userId,
            'discord_private_channel_id' => $channelId,
        ]);
    }
}

请注意,getPrivateChannel 方法仅接受 Discord 的雪花 ID。Discord 没有提供 API 路由来通过名称和标签查找用户的 ID,复制和粘贴用户 ID 的过程可能对某些用户来说很复杂。因此,建议您添加一个选项,让用户可以通过使用 Discord 登录或将其链接到现有账户来将其 Discord 账户与其应用程序内的账户连接起来。

现在,您可以在 via 方法中告诉 Laravel 将通知发送到 Discord 频道

// ...
use NotificationChannels\Discord\DiscordChannel;
use NotificationChannels\Discord\DiscordMessage;

class GameChallengeNotification extends Notification
{
    public $challenger;

    public $game;

    public function __construct(Guild $challenger, Game $game)
    {
        $this->challenger = $challenger;
        $this->game = $game;
    }

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

    public function toDiscord($notifiable)
    {
        return DiscordMessage::create("You have been challenged to a game of *{$this->game->name}* by **{$this->challenger->name}**!");
    }
}

可用的消息方法

变更日志

请参阅 CHANGELOG 了解最近更改的详细信息。

测试

$ composer test

安全

如果您发现任何安全相关的问题,请通过电子邮件 cs475x@icloud.com 而不是使用问题跟踪器来联系。

贡献

请参阅 CONTRIBUTING 了解详细信息。

致谢

许可证

麻省理工学院许可证(MIT)。请参阅许可证获取更多信息。