mwakaambrose/laravel-slack-alert

1.5 2022-11-08 07:07 UTC

This package is auto-updated.

Last update: 2024-09-08 10:47:19 UTC


README

本包可快速将警报发送到Slack。您可以用它来通知自己在应用中发生的任何重要事件。

use MwakaAmbrose\SlackAlert\Facades\SlackAlert;

SlackAlert::string("You have a new subscriber to the {$newsletter->name} newsletter!");

在底层,使用工作进程与Slack进行通信。这样,即使Slack服务不可用,您的应用也不会失败。

安装

您可以通过composer安装此包

composer require mwakaambrose/laravel-slack-alert

您可以为包含有效Slack webhook URL的SLACK_ALERT_WEBHOOK环境变量设置。您可以在Slack API文档中了解如何获取webhook URL(链接)

或者,您可以使用以下命令发布配置文件

php artisan vendor:publish --tag="slack-alert-config"

这是发布配置文件的内容

return [
    /*
     * The webhook URLs that we'll use to send a message to Slack.
     */
    'webhook_urls' => [
        'default' => env('SLACK_ALERT_WEBHOOK'),
    ],
];

用法

要向Slack发送消息,只需调用SlackAlert::string()并传递任何您想要的消息。

SlackAlert::string("You have a new subscriber to the {$newsletter->name} newsletter!");

使用多个webhooks

您还可以在配置文件中指定额外的webhooks以使用替代webhook。

// in config/slack-alert.php

'webhook_urls' => [
    'default' => 'https://hooks.slack.com/services/XXXXXX',
    'marketing' => 'https://hooks.slack.com/services/YYYYYY',
],

可以使用to函数选择要使用的webhook。

use MwakaAmbrose\SlackAlert\Facades\SlackAlert;

SlackAlert::to('marketing')->string("You have a new subscriber to the {$newsletter->name} newsletter!");

使用自定义webhooks

to函数还支持自定义webhook URL。

use MwakaAmbrose\SlackAlert\Facades\SlackAlert;

SlackAlert::to('https://custom-url.com')->message("You have a new subscriber to the {$newsletter->name} newsletter!");

格式化

Markdown

您可以使用Slack的标记来格式化消息。有关更多信息,请参阅Slack API文档

use MwakaAmbrose\SlackAlert\Facades\SlackAlert;

SlackAlert::string("A message *with some bold statements* and _some italicized text_.");

在Slack中,链接的格式与经典Markdown结构不同。

SlackAlert::string("<https://theonehq.com|This is a link to our homepage>");

表情符号

您可以使用与Slack相同的emoji代码。这意味着也支持自定义emoji。

use MwakaAmbrose\SlackAlert\Facades\SlackAlert;

SlackAlert::string(":smile: :custom-code:");

提及

您可以使用提及来通知用户和组。有关更多信息,请参阅Slack API文档

use MwakaAmbrose\SlackAlert\Facades\SlackAlert;

SlackAlert::string("A message that notifies <@username> and everyone else who is <!here>")

发送异常

您可以通过调用异常函数并传递任何可抛出实例来向Slack发送异常。您将在Slack上收到消息、文件、行号和应用程序环境。

SlackAlert::to("failed_vsla_wallet")->exception(new \Exception("This is a test exception"));

更高级的用法

您可以传递一个返回SlackPhp\Blockkit\Surfaces\Message实例的回调函数,以在Slack中构建自己的强大消息块。有关更多信息,请参阅该包的主页

SlackAlert::to('failed_vsla_wallet')->send(function(){
    $msg = Message::new();
    // Then you can add blocks using the surface's available methods.
    $msg->text('Don\'t you just love Slack?');
    $msg->divider();
    $msg->newImage()
        ->title('Team Chat')
        ->url('https://imgs.xkcd.com/comics/team_chat.png')
        ->altText('Comic about the stubbornness of some people switching chat clients');

    return $msg;
});

测试

composer test

鸣谢

许可协议

MIT许可(MIT)。有关更多信息,请参阅许可文件