Usage | laravel-slack-alerts-rust | Spatie       

 SPATIE  

laravel-slack-alerts-rust
=========================

spatie.be/open-source

  [Docs](https://spatie.be/docs)  [Laravel-slack-alerts-rust](https://spatie.be/docs/laravel-slack-alerts-rust/v1)  Usage

 Version   v1      

 Other versions for crawler [v1](https://spatie.be/docs/laravel-slack-alerts-rust/v1) 

  Usage    
- [ Introduction ](https://spatie.be/docs/laravel-slack-alerts-rust/v1/introduction)
- [ Support us ](https://spatie.be/docs/laravel-slack-alerts-rust/v1/support-us)
- [ Installation and setup ](https://spatie.be/docs/laravel-slack-alerts-rust/v1/installation-and-setup)
- [ Usage ](https://spatie.be/docs/laravel-slack-alerts-rust/v1/usage)
- [ Testing ](https://spatie.be/docs/laravel-slack-alerts-rust/v1/testing)
- [ Changelog ](https://spatie.be/docs/laravel-slack-alerts-rust/v1/changelog)
- [ Releasing ](https://spatie.be/docs/laravel-slack-alerts-rust/v1/releasing)

 Usage
=====

###  On this page 

1. [ Sending blocks ](#content-sending-blocks)
2. [ Using multiple webhooks ](#content-using-multiple-webhooks)
3. [ Queuing ](#content-queuing)
4. [ Formatting ](#content-formatting)

To send a message to Slack, simply call `message()` on the injected `SlackAlert` service and pass it any message you want.

```
let alert = app.resolve::<spatie_slack_alerts::SlackAlert>().await;
alert.message("You have a new subscriber to the newsletter!").await?;
```

Handlers and jobs can request `Inject<SlackAlert>` directly. The service contains final application configuration. Builder methods consume and return `Self`; `(*alert).clone()` gives you an independent builder without changing the injected service.

Sending blocks
--------------------------------------------------------------------------------------------------

Slack supports rich formatting using its [Block Kit](https://api.slack.com/block-kit) API. Send a set of blocks using `blocks()`:

```
use serde_json::json;

alert.blocks(vec![json!({
    "type": "section",
    "text": {
        "type": "mrkdwn",
        "text": "You have a new subscriber to the newsletter!"
    }
})]).await?;
```

Using multiple webhooks
-----------------------------------------------------------------------------------------------------------------------------

You can also use alternative webhooks by adding extra ones to the configuration:

```
Application::configure()
    .with_providers(|providers| { providers.add(service_provider()); })
    .with_config(|config, _| {
        let slack = config.section_mut::<Config>();
        slack.webhook_urls.insert("default".into(), "https://example.com/default".into());
        slack.webhook_urls.insert("marketing".into(), "https://example.com/marketing".into());
    });
```

The webhook to use can be chosen using `to()`:

```
(*alert).clone().to("marketing")
    .message("You have a new subscriber to the newsletter!").await?;
```

### Using a custom webhook

The `to()` function also supports custom webhook URLs:

```
(*alert).clone().to("https://custom-url.com/webhook")
    .message("Some message.").await?;
```

### Sending a message to an alternative channel

For legacy incoming webhooks, you can send a message to another channel using `to_channel()`:

```
alert.to_channel("subscription_alerts").message("Some message.").await?;
```

Modern Slack app webhooks ignore channel, username and icon overrides. They always use the channel and identity configured on the app. Use separate named webhooks for per-channel routing. See [Slack's documentation](https://docs.slack.dev/messaging/sending-messages-using-incoming-webhooks/).

Queuing
-----------------------------------------------------------------------------

By default, messages are sent by dispatching a job to the `default` queue. Configure Laravel's queue connection and run its worker as usual. The package does not create the application's queue tables.

### Configuring the queue

In your `.env` file, add:

```
SLACK_ALERT_QUEUE=queue_name
```

### Changing the queue at runtime

You can queue the job to a different queue than the one defined in config using `on_queue()`:

```
alert.on_queue("some-queue").message("Some message.").await?;
```

### Customizing the job

The default job makes up to three attempts and stops after three errors. To set different retries, timeouts, middleware, or delivery behavior, create your own Laravel job and replace `Config::job`. The callback receives the complete delivery data and the selected queue/synchronous options:

```
use laravel::{Application, queue::{Queueable, job}};
use spatie_slack_alerts::{Config, SendToSlackChannelJob, service_provider};

#[derive(Debug, Queueable)]
struct CustomSlackJob {
    alert: SendToSlackChannelJob,
}

#[job(tries = 5, timeout = std::time::Duration::from_secs(10))]
impl CustomSlackJob {
    async fn handle(self) -> laravel::Result<()> {
        self.alert.handle().await
    }
}

let app = Application::configure()
    .with_providers(|providers| { providers.add(service_provider()); })
    .with_config(|config, _| {
        config.section_mut::<Config>().job = |alert, options| {
            Box::pin(options.dispatch(CustomSlackJob { alert }))
        };
    })
    .create();
```

Your job can call `alert.handle().await`, inspect `alert.payload()`, modify its public fields, or replace delivery entirely. `DispatchOptions::dispatch()` works with any Laravel job and respects the queue and sync selection. Normal Laravel job injection is available for application services. Applications can also replace the `SlackAlert` binding in `with_services` or use `app.swap` in tests.

Formatting
--------------------------------------------------------------------------------------

### Markdown

You can format messages with [Slack's markup](https://slack.com/help/articles/202288908-Format-your-messages). Text is sent unchanged, including empty strings and `"0"`.

```
alert.message("A message *with some bold statements* and _some italicized text_.").await?;
alert.message("<https://spatie.be|This is a link to our homepage>").await?;
```

### Emoji

You can use the same emoji codes as in Slack. Custom emoji are also supported:

```
alert.message(":smile: :custom-code:").await?;
```

### Mentioning

Use [mentions](https://api.slack.com/reference/surfaces/formatting#mentioning-users) to notify users and groups:

```
alert.message("A message that notifies <@U123456> and everyone who is <!here>").await?;
```

### Icon change

For legacy incoming webhooks, change the icon next to the display name:

```
alert.clone().with_icon_url("https://example.com/tiny-icon.jpg").message("Some message.").await?;
alert.with_icon_emoji(":heart:").message("Some message.").await?;
```

### Display name change

For legacy incoming webhooks, change the display name:

```
alert.with_username("More Descriptive Name").message("Some message.").await?;
```

### Synchronous dispatch

By default, alerts are sent using jobs. Use `sync(true)` to send an alert immediately before continuing execution. `sync(false)` restores normal queued dispatch:

```
(*alert).clone().sync(true).message("Some message.").await?;
```

Disabled alerts and missing webhooks are a no-op. Invalid configured URLs and queue failures return `Error`. During synchronous dispatch, transport failures and non-2xx Slack responses also return errors. With an asynchronous queue connection, the worker handles delivery failures and retries them. Treat webhook URLs in stored job payloads as secrets and restrict access to queue storage and failed jobs.

### Usage in tests

Use Laravel's native queue fake to inspect messages, blocks, routing and counts, or the HTTP fake to check delivery without contacting Slack. See [testing](testing).

 A good
match?
-------------

### What we do best

- All things Laravel
- Custom frontend components
- Building APIs
- AI-powered features
- Simplifying things
- Clean solutions
- Integrating services

### Not our cup of tea

- WordPress themes
- Cutting corners
- Free mockups to win a job
- "Just execute the briefing"

 In short: we'd like to be a **substantial part** of your project.

 [ Get in touch via email ](mailto:info@spatie.be?subject=A%20good%20match%21&body=Tell%20us%20as%20much%20as%20you%20can%20about%0A-%20your%20online%20project%0A-%20your%20planning%0A-%20your%20budget%0A-%20%E2%80%A6%0A%0AAnything%20that%20helps%20us%20to%20start%20straightforward%21)
