阅读(2326) (6)

Laravel 8 Slack 附件

2021-07-06 09:24:50 更新

你还可以添加 “附件” 到 Slack 消息。相对简单文本消息,附件可以提供更加丰富的格式选项。在这个例子中,我们会发送一个在应用程序中出现的异常错误通知,包含查看更多异常细节的链接:

/**
 * Get the Slack representation of the notification.
 *
 * @param  mixed  $notifiable
 * @return SlackMessage
 */
public function toSlack($notifiable)
{
    $url = url('/exceptions/'.$this->exception->id);

    return (new SlackMessage)
                ->error()
                ->content('Whoops! Something went wrong.')
                ->attachment(function ($attachment) use ($url) {
                    $attachment->title('Exception: File Not Found', $url)
                               ->content('File [background.jpg] was not found.');
                });
} 

上面的示例会生成一个如下所示的 Slack 消息:

basic-slack-attachment.png

附件还允许你指定要呈献给用户的数组数据。为了提高可读性,给定的数组会以表格形式展示:

/**
 * 获取 Slack 形式的通知。
 *
 * @param  mixed  $notifiable
 * @return SlackMessage
 */
public function toSlack($notifiable)
{
    $url = url('/invoices/'.$this->invoice->id);

    return (new SlackMessage)
                ->success()
                ->content('One of your invoices has been paid!')
                ->attachment(function ($attachment) use ($url) {
                    $attachment->title('Invoice 1322', $url)
                               ->fields([
                                    'Title' => 'Server Expenses',
                                    'Amount' => '$1,234',
                                    'Via' => 'American Express',
                                    'Was Overdue' => ':-1:',
                                ]);
                });
} 

上面的示例会生成一个如下所示的 Slack 消息:

slack-fields-attachment.png