/slackへアクセスするとメッセージを送信する
作成手順
1.送信できる様にライブラリを追加する
2.Notification(通知)クラスの作成とメッセージ部分の作成
3.routeNotificationForSlackメソッドを追加
4.ルーティング
Contents
1.送信できる様にライブラリを追加する
composer require guzzlehttp/guzzle
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
C:\var\www\vblue\blog>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) Nothing to install or update Generating optimized autoload files > Illuminate\Foundation\ComposerScripts::postAutoloadDump > @php artisan package:discover 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. |
2.Notification(通知)クラスの作成とメッセージ部分の作成
php artisan make:notification SlackPosted
1 2 |
C:\var\www\vblue\blog>php artisan make:notification SlackPosted Notification created successfully. |
C:\var\www\vblue\blog\app\NotificationsにSlackPosted.phpが作成される
次の様に変更する。
①via部分変更
1 2 3 4 |
public function via($notifiable) { return ['slack']; } |
②通知メッセージ部分追加
1 2 3 4 5 6 7 8 9 10 |
public function toSlack($notifiable) { return (new SlackMessage) ->success() ->content('問題が発生しました') ->attachment(function ($attachment) { $attachment->title('weeklyランキングが生成されませんでした。') ->content('エラーログ。。。'); }); } |
③頭の方に追加
1 2 3 4 5 |
use Illuminate\Bus\Queueable; use Illuminate\Notifications\Notification; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Notifications\Messages\MailMessage; use Illuminate\Notifications\Messages\SlackMessage;//これを追加 |
3.routeNotificationForSlackメソッドを追加
app/Hoge.phpを作成します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<?php namespace App; use Illuminate\Notifications\Notifiable; class Hoge { use Notifiable; public function routeNotificationForSlack() { return 'https://hooks.slack.com/services/xxxxx';//取得したURL } } |
4.ルーティング
/slackにアクセスした時のふるまいを記述します。
routes/web.php
1 2 3 4 |
Route::get('/slack', function () { $user = new App\Hoge; $user->notify(new \App\Notifications\SlackPosted); }); |
注意事項
日本語文字列がある場合には、特にUTF-8で保存する事!!
参考)
https://qiita.com/amymd/items/2616368bf3969ecb1aaf