LaravelのNotificationをつかってSlackのメッセージを飛ばす

技術系

目次

はじめに

先日LaravelからSlackメッセージが送れるようになって、「やった!これで楽しくなる!」って思っていたのですが、 @naname さんから「Laravelって最近は標準でSlack対応してますよww」という情報を頂きまして、そっちを使ってみました。

Laravel5.4からSlackのIncoming Webhookでメッセージを飛ばす
Laravelの新しいバージョン(5.4か5.3)から、NotificationでSlackのメッセージを飛ばせるようになりました。下記の記事にその方法をまとめました。LaravelからSlackのメッセージを飛ばしてみました。こちらの記事...

GuzzleのインストールとNotificationの作成

Slackのメッセージを飛ばすためにはGuzzuleライブラリが必要です。これを入れておきます。

$ composer install guzzlehttp/guzzle
今時のPHP HTTPクライアントのGuzzleを使ってみた - Qiita
はじめに LaravelでHTTPリクエストを投げたかったのでGuzzleを使ってみました。 以前ですとPEARのHTTP_Request2を使っていましたが、あまり最近使われていないようなので新しいパッケージを使ってみました。 HTTP_...

次いでLaravelでSlackのメッセージを飛ばす準備を行います。
LaravelではSlackに限らず、メールやSMSなどに対応した「Notification」という仕組みがあります。
メール、SMS、Slackなどのドライバ部分に相当するところはなんでもよくて、「〇〇といったことを通知したい」という場合に「〇〇Notification」として作成しておき、実際の実装部分でその手段を実装する、といった感じです。
このNotificationを作成します。

$  php artisan make:notification SlackNotification

app/Notifications/SlackNotification.phpというファイルが作成されました。

このファイルのvia()をslackに書き換え、toSack()というメソッドを実装します。

    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        return ['slack'];
    }

    /**
     * Slackのメッセージを飛ばす。
     *
     * @param $notifiable
     *
     * @return SlackMessage
     */
    public function toSlack( $notifiable ) {
        return (new SlackMessage)
            // ->success()
            ->from('LaravelBot')                              // ユーザ名
            ->to('#bot')                                      // 送信先チャンネル
            // ->image(':yousan:')                            // 画像アイコンらしい
            ->content('Whoops! Something went wrong.'.time()) // メッセージ
            ;
    }

Webhook URLの設定

incoming-webhookは下記のURLから取得しておきます。

Find your workspace | Slack
Find and sign in to your Slack workspace.

NotificationはUserなどのモデルインスタンスから送信されることを想定しているようで、そちらに設定しておきます。
これはUserごとの通知先メールアドレスがDBに保存されていて、それを呼び出してNotificationを使う、ということが想定されているようです。
固定値を返すrouteNotificationForSlack()メソッドを実装しておきます。

    public function routeNotificationForSlack()
    {
        return 'https://hooks.slack.com/services/T0XXXXX/BXXXX/ZAXXXXXXXXXXXXXXXXXXXX';
    }

テスト呼び出し

実際に呼び出します。
今回はコマンドとして呼んでみます。

$ php artisan make:command PostSlackMessage

コマンドを作成します。
app/Console/Commands/PostSlackMessage.phpというファイルができているので、そちらを編集します。

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'slack:post';


    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $user = new \App\User;
        $user->notify(new \App\Notifications\SlackNotification());
        $this->line('Message sent');
    }

コマンドを登録します。
app/Console/Kernel.phpにPostSlackMessageを登録します。

    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        Commands\PostSlackMessage::class,
    ];

呼び出します。

$ php artisan slack:post

通知が来ました!

感想

というわけでやってみましたが、かなり簡単でした。
今回はWebhookURLをUserクラスに紐付けしていましたが、コレクション等の場合にはFacadeを使うと良いようですね。

Using The Notification Facade
Alternatively, you may send notifications via the Notification facade. This is useful primarily when you need to send a notification to multiple notifiable entities such as a collection of users. To send notifications using the facade, pass all of the notifiable entities and the notification instance to the send method:

Notifications | Laravel 5.4 - The clean stack for Artisans and agents
Laravel is a PHP web application framework with expressive, elegant syntax. We've already laid the foundation — freeing ...

またLINEのNotificationもあるようなので、そちらも是非試してみたいです。
https://packagist.org/packages/hinaloe/laravel-line-notify

参考サイト

https://laravel.com/docs/5.4/notifications#slack-notifications
https://readouble.com/laravel/5.3/ja/artisan.html

コンソールへのメッセージ出力

php artisan make:command PostSlackMessage

コメント

タイトルとURLをコピーしました