LoginSignup
1
0

More than 1 year has passed since last update.

【Laravel】Block Kitを使ったSlack通知機能

Posted at

環境

Laravel v9.5.1 (PHP v8.1.3)

Block Kitを使った通知機能

Notificationを使ってSlack通知機能を実装した記事はたくさん見かけたが、Notificationに加え、リッチなメッセージを作成できるBlock Kitを使った通知機能は見なかったので仕組みを理解し実装するのに時間がかかってしまった。

実装

大体はドキュメント通りに実装し、toSlack()の中にデフォルトで書いてあるnew SlackMessage->to()は使わずに下記のように変更。

<?php

namespace App\Notifications;

...
class Slack extends Notification
{
  use Queueable;

  private string $message;

  public function __construct(string $message)
  {
    $this->message = $message;
  }

  public function via(): array
  {
    return ['slack'];
  }

  public function toSlack(): string
  {
    $client = new Client();
    $response = $client->request(
      "POST",
      'https://slack.com/api/chat.postMessage',
      [
        'form_params' => [
          'token'   => config('slack.token'),
          'channel' => config('slack.channel'),
          'attachments'  => json_encode($this->attachments()),
        ],
      ]);

    return $response->getBody()->getContents();
  }

  private function attachments(): array
  {
    return [
      [
        "color"=> "#f2c744",
        "blocks"=> [
          [
            "type"=> "section",
            "text"=> [
              "type"=> "mrkdwn",
              "text": "This is a mrkdwn section block :ghost: *this is bold*, and ~this is crossed out~, and <https://google.com|this is a link>"
            ]
          ],
          [
            "type"=> "image",
            "image_url"=> "https://i1.wp.com/thetempest.co/wp-content/uploads/2017/08/The-wise-words-of-Michael-Scott-Imgur-2.jpg?w=1024&ssl=1",
            "alt_text"=> "inspiration"
          ]
        ]
      ]
    ];
  }
}

通知を送りたいタイミングに下記を記述。

User::first()->notify(new Slack($message));

実際の通知がこんな感じになる

スクリーンショット 2022-06-28 17 54 18

参考

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0