tomatophp/discord-notifications

Laravel 通知驱动程序,用于 Discord。

v1.0.0 2024-03-12 18:50 UTC

This package is auto-updated.

Last update: 2024-09-12 20:00:57 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 应用程序中的 创建一个机器人用户 按钮。

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

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

    php artisan discord:setup

用法

在您希望通过 Discord 接收通知的每个模型中,您必须添加一个可由 routeNotificationForDiscord 方法访问的频道 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 没有提供用于通过名称和标签查找用户 ID 的 API 路由,复制和粘贴用户 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}**!");
    }
}

可用的消息方法

更新日志

有关最近更改的更多信息,请参阅 更新日志

测试

$ composer test

安全性

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

贡献

请参阅CONTRIBUTING以获取详细信息。

致谢

许可证

MIT许可(MIT)。请参阅LICENSE以获取更多信息。