nwilging/laravel-slack-bot

为 Laravel 提供强大的 Slack 消息集成

2.1.3 2023-05-27 17:18 UTC

This package is auto-updated.

Last update: 2024-08-31 00:46:56 UTC


README

Tests Coverage Latest Stable Version License Total Downloads

为 Laravel 提供强大的 Slack 消息集成

关于

虽然 Slack 入站 Webhooks 功能强大,但直接 API 交互更加强大——或者说类似那样。

此包利用 Slack 机器人令牌 与 Slack API 交互。这允许集成执行诸如搜索频道和向任何工作空间中的频道发送消息(包括纯文本和富文本)等操作。

*任何公共频道,或者 Slack App 机器人是成员的私有频道

安装

先决条件

  1. Laravel v8+
  2. PHP 7.4+

使用 Composer 安装

composer require nwilging/laravel-slack-bot

使用 laravel/slack-notification-channel 进行使用

如果你的应用程序使用默认的第一方 Laravel 包,laravel/slack-notification-channel,则此包将与第一方包冲突。默认情况下,此包配置为使用 via() 方法中的频道 slack

如果您希望同时使用此包和 laravel/slack-notification-channel,只需将以下内容添加到您的 .env

SLACK_API_DRIVER_NAME=slackBot

您可以将 slackBot 替换为您想要的任何驱动器名称。驱动器将以该名称实例化,并且您可以将它提供给您的 via() 方法。这将允许您同时使用此包和 laravel/slack-notification-channel

示例

<?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Notification;
use Nwilging\LaravelSlackBot\Contracts\Notifications\SlackApiNotificationContract;

class SlackNotification extends Notification implements SlackApiNotificationContract
{
    use Queueable;

    public function via($notifiable)
    {
        return ['slackBot']
    }

    public function toSlackArray($notifiable): array
    {
        return [
            'contentType' => 'text',
            'message' => 'test plain text message',
            'channelId' => 'C012345',
            'options' => [], // Message Options
        ];
    }
}

配置

使用 此指南 创建您的 Slack 应用。大多数集成将使用以下范围。如果需要,您可以添加额外的 OAuth 范围。

  • channels:read
  • chat:write
  • chat:write.customize
  • groups:read
  • groups:write
  • im:read
  • mpim:read

要配置您的 .env,只需添加以下变量

SLACK_API_BOT_TOKEN=xoxb-your-bot-token

基本用法

消息示例

SlackApiNotificationContract

您的通知 必须 实现 Nwilging\LaravelSlackBot\Contracts\Notifications\SlackApiNotificationContract 接口。

基本用法

此包可以与 Laravel 通知自动使用。将 slack 添加到您的通知的 via() 数组中,并返回数组的 toSlack() 方法

<?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Notification;
use Nwilging\LaravelSlackBot\Contracts\Notifications\SlackApiNotificationContract;

class SlackNotification extends Notification implements SlackApiNotificationContract
{
    use Queueable;

    public function via($notifiable)
    {
        return ['slack']; // Or, `via['slackBot']` if you have configured this in .env
    }

    public function toSlackArray($notifiable): array
    {
        return [
            'contentType' => 'text',
            'message' => 'test plain text message',
            'channelId' => 'C012345',
            'options' => [], // Message Options
        ];
    }
}

这里的 channelId 是您想要发送到的频道的 ID 或名称。

有关 SlackApiService 的使用信息,请参阅更多信息,该服务可以通过频道名称提供频道数据(包括 ID)。

laravel/slack-notification-channel 一起使用

<?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Notification;
use Nwilging\LaravelSlackBot\Contracts\Notifications\SlackApiNotificationContract;

class SlackNotification extends Notification implements SlackApiNotificationContract
{
    use Queueable;

    public function via($notifiable)
    {
        return [
            'slack', // Using laravel/slack-notification-channel driver
            'slackBot', // Using nwilging/laravel-slack-bot driver
        ];
    }
    
    /**
     * The method to build a slack message for laravel/slack-notification-channel
     */
    public function toSlack($notifiable)
    {
        // 
    }

    /**
     * The method to build a slack message for nwilging/laravel-slack-bot
     */
    public function toSlackArray($notifiable): array
    {
        return [
            'contentType' => 'text',
            'message' => 'test plain text message',
            'channelId' => 'C012345',
            'options' => [], // Message Options
        ];
    }
}

高级用法

此包还提供 SlackApiService 和一些辅助类,例如布局构建器、布局块、元素和组合对象。除发送纯文本消息外,最常用的用法是使用布局构建器和相关组件发送富文本消息。您还可以进一步利用 SlackApiService

Slack API 服务

契约: Nwilging\LaravelSlackBot\Contracts\SlackApiServiceContract

方法

  • listConversations - 返回频道和组的分页列表
    • int $limit = 100 - 页面限制(默认 100)
    • ?string $cursor = null - 页面游标,用于获取新页面
    • bool $excludeArchived = false - 标志以排除存档频道和组
    • ?string $teamId = null - 要列出对话的团队 ID(如果令牌属于全局应用,则为必需项)
    • bool $includePrivate = true - 标志以包含私有频道和群组(将仅显示应用是成员的频道)
  • getChannelByName - 使用给定名称检索频道数据
    • string $name - 要检索的频道名称
  • sendTextMessage - 发送纯文本消息
    • string $channelId - 要发送到的频道 ID
    • string $message - 要发送的消息文本(可能包含 Markdown)
    • array $options = [] - 消息选项
  • sendBlocksMessage - 使用 布局块 发送消息
    • string $channelId - 要发送到的频道 ID
    • array $blocks - Block 数组
    • array $options = [] - 消息选项

消息选项

应将消息选项作为具有以下架构的数组传递

{
    username?: string,
    icon?: {
      emoji?: string,
      url?: string,
    },
    unfurl?: {
      'media': bool,
      'links': bool,
    },
    thread?: {
      ts?: string,
      send_to_channel?: bool,
    },
    link_names?: bool,
    metadata?: array,
    parse?: string,
    markdown?: bool,
}

这些选项实际上是 来自 chat.postMessage 的可选参数

存在一个 SlackOptionsBuilder 支持类,使得构建此数组更加易于表达

use Nwilging\LaravelSlackBot\Support\SlackOptionsBuilder;

$builder = new SlackOptionsBuilder();

$builder
    ->username('My Bot') // Set a custom username
    ->iconUrl('https://...') // URL to icon (overrides iconEmoji)
    ->iconEmoji(':white_check_mark:') // Sets icon to an emoji
    ->unfurlMedia()
    ->unfurlLinks()
    ->threadTs('ThreadTS')
    ->threadReplySendToChannel() // Whether or not to send reply to channel when replying to a thread
    ->linkNames()
    ->parse('...')
    ->markdown() // Enable markdown (or disable by passing `false`)
    ->metadata([]);

// Pass this to `SlackApiService`
$apiServiceCompliantOptionsArray = $builder->toArray();

布局块

布局块实现通常遵循 Slack 的布局块 设计。

布局构建器

存在一个位于 Nwilging\LaravelSlackBot\Support\LayoutBuilder\Builder 的布局 Builder,实现了接口 Nwilging\LaravelSlackBot\Contracts\Support\LayoutBuilder\BuilderContract

构建器旨在提供易于表达的方法来构建基本且健壮的消息。这在 toSlack() 方法中构建您的通知时非常有用。

use Nwilging\LaravelSlackBot\Support\LayoutBuilder\Builder;
use Nwilging\LaravelSlackBot\Support\LayoutBlocks\Blocks;
use Nwilging\LaravelSlackBot\Support\LayoutBlocks\Elements;

$layouBuilder = new Builder();

// Create a button element with text
$buttonElement = new Elements\ButtonElement(
    $layoutBuilder->withPlainText('Button Text'), // Helper method to create a TextObject
    'action-id'
);

// Add the button element to an actions block
$actionsBlock = new Blocks\ActionsBlock([$buttonElement]);

$layoutBuilder
    ->header('Header Text')
    ->divider()
    ->addBlock($actionsBlock);

// Pass this to `sendBlocksMessage`
$apiServiceCompliantBlocksArray = $layoutBuilder->getBlocks();

处理斜杠命令

Slack 斜杠命令 可以通过此包和您在应用程序中配置的命令处理器进行处理。

Nwilging\LaravelSlackBot\Services\SlackCommandHandlerService 有一个 handle 方法,它接受一个 Request 对象。此服务将使用请求头和您提供的签名密钥验证传入的消息,然后尝试使用注册的命令处理器处理命令请求。

创建命令处理器

命令处理器应实现接口 Nwilging\LaravelSlackBot\Contracts\SlackCommandHandlerContract。一个示例处理器

<?php
declare(strict_types=1);

namespace App;

use Nwilging\LaravelSlackBot\Support\SlackCommandRequest;
use Symfony\Component\HttpFoundation\Response;

class TestCommandHandler implements SlackCommandHandlerContract
{
    public function handle(SlackCommandRequest $commandRequest): Response
    {
        return response('OK');
    }
}

注册命令处理器

命令处理器应在服务提供程序中注册,以便在应用程序启动时可用。您可以在任何已注册在您的应用程序中的服务提供程序中这样做。在您的服务提供程序的 register 方法中放置命令处理器注册。

<?php

namespace App\Providers;

use App\TestCommandHandler;
use Illuminate\Support\ServiceProvider;
use Nwilging\LaravelSlackBot\Contracts\Services\SlackCommandHandlerFactoryServiceContract;

class AppServiceProvider extends ServiceProvider
{
    public function register()
    {
        /** @var SlackCommandHandlerFactoryServiceContract $slackCommandFactory */
        $slackCommandFactory = $this->app->make(SlackCommandHandlerFactoryServiceContract::class);
        $slackCommandFactory->register(TestCommandHandler::class, 'command-name');
    }
}