Contents
Slack準備
Slackの通知先の場所(チャネル)を#myappとします。
原理
Slack側にWebhookというURLを発行してもらい、そこに対してメッセージを送るイメージです。
WebhookURL取得
以下のアドレスにアクセスします。
https://slack.com/services/new/incoming-webhook
すると、「チャンネルへの投稿」にて#myappを選択します。
「インテグレーションを追加する」ボタンを押下すると、WebhookURLと簡単?な説明がでてきます。このWebhookURLコピーしておき、プログラムから使用します。
PHPのHTTPクライアントライブラリ
Guzzleをインストール
プロジェクトの直下デパッケージを追加します。
composer require guzzlehttp/guzzle
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
C:\var\www\ecblue\myslack>composer require guzzlehttp/guzzle Using version ^6.3 for guzzlehttp/guzzle ./composer.json has been updated Loading composer repositories with package information Updating dependencies (including require-dev) Package operations: 5 installs, 0 updates, 0 removals - Installing guzzlehttp/promises (v1.3.1): Downloading (100%) - Installing ralouphie/getallheaders (3.0.3): Downloading (100%) - Installing psr/http-message (1.0.1): Downloading (100%) - Installing guzzlehttp/psr7 (1.6.1): Downloading (100%) - Installing guzzlehttp/guzzle (6.3.3): Downloading (100%) guzzlehttp/psr7 suggests installing zendframework/zend-httphandlerrunner (Emit PSR-7 responses) Writing lock file Generating optimized autoload files > Illuminate\Foundation\ComposerScripts::postAutoloadDump > @php artisan package:discover --ansi Discovered Package: beyondcode/laravel-dump-server Discovered Package: fideloper/proxy Discovered Package: laravel/tinker Discovered Package: nesbot/carbon Discovered Package: nunomaduro/collision Package manifest generated successfully. |
上記の処理はLaravel5.7まで必要でした。
ドライバーのエラーが出て5.8よりComposerでSlackの通知チャンネルをインストールする必要がる事を知ったので、上記のインストールが必要なのか不明です。すみません。
Laravel5.8から
composer require laravel/slack-notification-channel
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
C:\var\www\ecblue\myslack>composer require laravel/slack-notification-channel Using version ^2.0 for laravel/slack-notification-channel ./composer.json has been updated Loading composer repositories with package information Updating dependencies (including require-dev) Package operations: 1 install, 0 updates, 0 removals - Installing laravel/slack-notification-channel (v2.0.0): Downloading (100%) Writing lock file Generating optimized autoload files > Illuminate\Foundation\ComposerScripts::postAutoloadDump > @php artisan package:discover --ansi Discovered Package: beyondcode/laravel-dump-server Discovered Package: fideloper/proxy Discovered Package: laravel/nexmo-notification-channel Discovered Package: laravel/slack-notification-channel Discovered Package: laravel/tinker Discovered Package: nesbot/carbon Discovered Package: nunomaduro/collision Package manifest generated successfully. |
プログラム
メッセージが#myappへ送れる事を確認します。
通知クラス
php artisan make:notification SlackPosted
このコマンドで通知クラスが作成されます。
C:\var\www\ecblue\sqlsrv\app\Notifications\SlackPosted.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
<?php namespace App\Notifications; use Illuminate\Bus\Queueable; use Illuminate\Notifications\Notification; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Notifications\Messages\MailMessage; class SlackPosted extends Notification { use Queueable; /** * Create a new notification instance. * * @return void */ public function __construct() { // } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { return ['mail']; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\MailMessage */ public function toMail($notifiable) { return (new MailMessage) ->line('The introduction to the notification.') ->action('Notification Action', url('/')) ->line('Thank you for using our application!'); } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ public function toArray($notifiable) { return [ // ]; } } |
これを書き換えます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 |
<?php namespace App\Notifications; use Illuminate\Bus\Queueable; use Illuminate\Notifications\Notification; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Notifications\Messages\MailMessage; use Illuminate\Notifications\Messages\SlackMessage;//これを追加 class SlackPosted extends Notification { use Queueable; /** * Create a new notification instance. * * @return void */ public function __construct() { // } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { return ['slack']; //ここを書換 } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\MailMessage */ public function toMail($notifiable) { return (new MailMessage) ->line('The introduction to the notification.') ->action('Notification Action', url('/')) ->line('Thank you for using our application!'); } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ public function toArray($notifiable) { return [ // ]; } //以下、追加 public function toSlack($notifiable) { //https://qiita.com/kei4eva4/items/6827a9b14a71c3ba1ee5 //https://qiita.com/amymd/items/2616368bf3969ecb1aaf $url = 'https://qiita.com'; return (new SlackMessage) ->from('HogeName')//投稿者名 ->image('https://cdn.qiita.com/assets/favicons/public/apple-touch-icon-f9a6afad761ec2306e10db2736187c8b.png') ->success() ->attachment(function ($attachment) use ($url) { $attachment->title('Qiita', $url)//タイトルとリンクURL ->fields([//以下ユーザの任意で設定可能 'タイトル' => 'Laravel->Slack通知', 'タグ' => '入門', 'ユーザー' => '@Lara',//ユーザのアドレス '投稿日時' => \Carbon\Carbon::now()->toDateTimeString(), 'hoge' => 'xxx' ])->color('#ffa')//黄色の縦線 ->content('ログ・・・');//内容 }); } } |
通知先クラス
C:\var\www\ecblue\sqlsrv\appに
Hoge.phpを作成します。
通知先を返すメソッドを追加します。
routeNotificationForXXXのXXXの部分に書かれた情報を元にドライバ情報を読み込んでくるとの事なので、このrouteNotificationForSlackとします。
つまり、routeNotificationForSlackがWebHookURLを返す関数となります。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<?php namespace App; use Illuminate\Notifications\Notifiable; class Hoge { use Notifiable; public function routeNotificationForSlack() { return 'https://hooks.slack.com/services/--- 取得したWebHook情報 ---'; } //送信した後の画面遷移 public function move() { //リダイレクト header( "Location: http://ecblue.dip.jp/myslack/public" ) ; exit ; } } |
通知先を記述します。
ルーティング
1 2 3 4 5 |
Route::get('/slack', function () { $user = new App\Hoge; $user->notify(new \App\Notifications\SlackPosted); $user->move();//リダイレクト(ページ移動) }); |
解説
通知は2つの方法で送信されます。これは、Notifiable
トレイトのnotify
メソッドによる方法です。
通知クラスにtoSlack
メソッドを定義する必要があります。
このメソッドは$notifiable
エンティティを受け取り、Illuminate\Notifications\Messages\SlackMessage
インスタンスを返す必要があります。っと公式解説にあります。
プログラムを見ると、いまいち理解できません。
このように書けばメッセージが飛ぶと思いましょう。
送信
結果
さいごに
掲示板(っぽい)のと組み合わせて、投稿があったら、通知する仕組みを今度作ってみたいと思います。メールやLineへも送れるみたいなので、機会があればやってみます。