stechstudio/slack-laravel-api

编写自己的 Slack App 集成使用的 Slack SDK。

v4.0.0 2021-06-16 21:33 UTC

README

通过 Laravel 风格的路由和中间件身份验证,轻松处理 Slack 网钩请求。如果您曾经实现过 Slack 的 webhook,您可能会想试试这个。

版本和兼容性

  • PHP 版本: >=8.0
  • Laravel: ^7.0|^8.0

安装

Composer

composer require stechstudio/slack-laravel-api

配置

.env

在 Slack 发送的每个 HTTP 请求中,他们会在 HTTP 头部添加一个 X-Slack-Signature。签名是通过使用标准的 HMAC-SHA256 密钥散列将签名密钥与我们要发送的请求体结合而创建的。

这个签名密钥被中间件用来验证请求

SLACK_SIGNING_SECRET="slacksecretestringhere"

发布 Slack 路由

artisan vendor:publish --provider=slack-routes

用法

发布 Slack 路由后,您可以在 base('routes/slack.php') 中查找 API 路由和一些 Slack 路由的工作示例。

Web 路由

/*
|--------------------------------------------------------------------------
| Slack Webhook Routes
|--------------------------------------------------------------------------
|
| Here is where you can register Slack routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "slack" middleware group. Enjoy building your API!
|
*/

Route::middleware('slack')->match(['get', 'post'], '/slack/api', 'STS\Slack\Http\Controllers\Slack@webhook');

默认情况下,您的应用程序将在 slack/api URI 上有 GET|POST|HEAD 方法,这些方法将一切传递给 STS\Slack\Http\Controllers\Slack@webhook,通过 slack 中间件。

您可以修改 URI,甚至添加其他端点的路由。

Slack 命令路由

use STS\Slack\Facades\SlackRoute;
use STS\Slack\SlashCommands\Echoes;

/*
|--------------------------------------------------------------------------
| Slack Command Routes
|--------------------------------------------------------------------------
|
| Here is where you can register Slack commands for your application.
|
*/
SlackRoute::handles('/hello', function (SlashCommand $slashCommand) {
    return 'Hello World';
});

SlackRoute::handles('/echo', Echoes::class);

这些是工作示例,如果您设置 Slack 割令使用配置的 URI,只需键入 /hello/echo yoodle 即可触发相应的响应。

SlackRoute::handles() 期望您提供一个与 Slack 中的割令匹配的命令,以及一个处理命令的可调用对象。

这最好在 Echo 命令示例中展示。

<?php declare(strict_types=1);

namespace STS\Slack\SlashCommands;

use Illuminate\Support\Facades\Log;
use STS\Slack\Contracts\Messaging\Message as SlackMessage;
use STS\Slack\Contracts\SlashCommands\ControllerI;
use STS\Slack\Messaging\LayoutBlocks\Context;
use STS\Slack\Messaging\LayoutBlocks\Section;
use STS\Slack\Messaging\Message;
use STS\Slack\Models\SlashCommand;
use function json_encode;

class Echoes implements ControllerI
{

    public function handle(SlashCommand $slashCommand): SlackMessage
    {
        return $slashCommand->createMessage('*Echo:*  ' . $slashCommand->getText())
            ->addImage(
                'https://cdn.cp.adobe.io/content/2/dcx/9ed8e319-b714-4c8d-b9d5-7a6d419e50b3/rendition/preview.jpg/version/0/format/jpg/dimension/width/size/1200',
                'Echo Hacker'
            )
            ->addSection('*Slack Parameters* ', function(Section $section) use($slashCommand) {
                $section
                    ->addText("*Team ID*: {$slashCommand->getTeamId()}")
                    ->addText("*Team Domain*: {$slashCommand->getTeamDomain()}")
                    ->addText("*Channel ID*: {$slashCommand->getChannelId()}")
                    ->addText("*Channel Name*: {$slashCommand->getChannelName()}")
                    ->addText("*User ID*: {$slashCommand->getUserId()}")
                    ->addText("*User Name*: {$slashCommand->getUserName()}")
                    ->addText("*Command*: {$slashCommand->getCommand()}");
            })
            ->addSection("*Your Text*\n{$slashCommand->getText()}")
            ->addDivider()
            ->addContext(function(Context $context) {
                $context
                    ->addImage(
                        'https://avatars.slack-edge.com/2019-02-19/556373803382_e2c54afedc2a4fb73ccd_512.png',
                        'The Commander Logo'
                    )
                    ->addText('slack-laravel-api echo handler');
            })
            ->tap(function(Message $message) {
                Log::warning(json_encode($message->toSlackObjectArray()));
            });
    }
}

首先要注意的是,您的命令必须实现 STS\Slack\Contracts\SlashCommands\ControllerI 才是有效的。这确保了我们有一个 handle(),它接受一个 SlashCommand 并返回一个 SlackMessage。

如您所见,SlashCommand 提供了对 Slack 发送给您的一切的访问。最常用的两个是

  • $slashCommand->getCommand()
  • $slashCommand->getText()

假设用户在 Slack 中键入 /echo yoodle ay e who 以触发此操作。那么 getCommand() 将返回 /echo,而 getText() 返回 yoodle ay e who。我们通常然后解析文本以获取子命令。

SlackMessage 类是对 Slack API 指定的 Building Block 消息布局格式 的强大包装。您可以使用这个类做任何您可以用 blocks 做的事情。

结论

就这样,处理您的命令并返回一个 Slack 格式的消息,Laravel 中间件为您验证每个 Slack 调用,并有一些有用的类使处理这些事情变得更容易。