Laravel 에서 slack 채널에 알림을 전송하는 방법을 설명합니다.


Slack 설정

  1. 워크스페이스에 들어갑니다.
  2. web hook 으로 연동할 채널에 들어간 후에 상단의 설정 아이콘을 클릭하고 Add apps 를 클릭합니다.


  3. App  목록에서 Webhook  을 치고 나온 목록에서 Incoming Webhooks  선택합니다.
  4. Web Browser 가 기동되며 웹 훅 설정 화면이 뜨면 add to Slack  을 클릭합니다.
  5. 화면이 바뀌면 여기에서 Post to Channel  에 메시지를 보낼 채널을 선택하고 Add Incoming WebHooks integration  을 클릭합니다.
  6. 생성된 Web hook URL 을 복사해 놓습니다.


Laravel 설정

  1. slack notification driver 를 설치합니다.

    composer require laravel/slack-notification-channel
    CODE
  2. 위에서 생성한 Web Hook URL 을 .env 에 설정해 줍니다.

    SLACK_WEBHOOK_URL=https://hooks.slack.com/services/mywebhook/url
    CODE
  3. config/ 내 설정 파일에 위에서 설정한 env 변수를 읽어올수 있도록 추가합니다. 예로 저는 myservice.php 에 다음과 같은 내용을 추가했습니다.

    config/myservice.php

    <?php
    return [
     'notification' => [
            'slack_webhook_url' => env('SLACK_WEBHOOK_URL'),
        ],
    PHP
  4. 새로운 Notification 클래스를 생성합니다. 저는 scheduling 작업이 완료되면 통지할 용도로 TaskSchedulerRan 란 notification class 를 생성했습니다.

    php artisan make:notification TaskSchedulerRan
    CODE
  5. TaskSchedulerRan.php 의 delivery 채널을 지정하는 via 메서드에 'slack' 을 추가해 주고 toSlack 메서드를 구현해 줍니다. 

    위 예제 클래스는 Queue 를 사용하므로 sync 방식으로 알림을 전송할 경우 implements ShouldQueue 부분을 삭제합니다.

Notifiable Trait 사용


  1. Notification 할 클래스에 Notifiable 트레이트를 포함시킵니다.

    class User extends Authenticatable
    {
        use Notifiable;
    }
    CODE
  2. 클래스에 routeNotificationForChannelType 메서드를 구현합니다. ChannelType 은 알림을 전달할 채널 이름을 적어줍니다. 채널이 mail 일 경우 routeNotificationForEMail 이며 Slack 이므로 routeNotificationForSlack 메서드를 구현합니다.

    public function routeNotificationForSlack($notification)
    {
    	return config('myservice.notification.slack_webhook_url');
    }
    CODE
  3. Notifiable 트레이트를 포함시킨 클래스의 notify 메서드를 Notification class 를 매개 변수로 전달해서 호출합니다.

    $user->notify(new TaskSchedulerRan('my task', Carbon::now()));
    CODE
  4. 제대로 전송되었는지 확인합니다.

On-Demand Notifications 사용

  1. 정상적으로 메시지가 가는지 확인해 봅니다. 예로 다음은 On demand notifications 를 사용하여 슬랙 메시지를 전송하는 예제입니다.

    $now = \Carbon\Carbon::now();
    
    Notification::route('slack', config('myservice.notification.slack_webhook_url'))
                 ->notify(
                          new TaskSchedulerRan('my task',\Carbon\Carbon::now())
                   );
    PHP


Ref