> ## Documentation Index
> Fetch the complete documentation index at: https://docs.blink.so/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# How Slackbots Work

> Build and deploy a Slackbot with automated setup and webhook tunneling

<Card horizontal icon="microscope">
  You don't need to read this guide to create a Slackbot. The Blink CLI does it
  all for you. This page explains the internals for those who want deeper
  insight.
</Card>

## Overview

Building a Slackbot typically involves navigating complex OAuth flows, managing webhook configurations, handling request verification, and maintaining separate development and production environments. Blink abstracts away these pain points, handling the heavy lifting automatically.

**Most of this work happens in the background with Blink.** You can start building your bot immediately without worrying about webhook signatures, URL verification challenges, or tunnel configuration.

However, if you want to understand what's happening behind the scenes or need to troubleshoot something, this guide explains how Blink agents run in Slack, from development through production deployment.

## How Blink Communicates with Slack

Before diving into setup, it's helpful to understand how Blink agents communicate with Slack.

### Webhook Architecture

Slack sends events (messages, mentions, reactions) to your agent via HTTP POST requests called **webhooks**. Here's the flow:

```
User sends message in Slack
    ↓
Slack creates webhook POST request
    ↓
POST https://{your-webhook-uuid}.blink.host
    ↓
Blink receives and routes request
    ↓
Your agent processes the event
    ↓
Agent responds via Slack API
```

### Request Verification

Every webhook request from Slack includes a cryptographic signature to verify authenticity:

* **Signature Header**: `x-slack-signature` contains an HMAC-SHA256 hash
* **Timestamp Header**: `x-slack-request-timestamp` prevents replay attacks
* **Signing Secret**: Your app's secret key used to verify signatures

Blink's Slack SDK automatically handles verification - you don't need to implement it yourself.

### The Webhook Tunnel

During development, Blink provides a **devhook** - a reverse tunnel that routes webhooks from Slack to your local machine:

```
Development:
Slack → https://{uuid}.blink.host → Your localhost:3000

Production:
Slack → https://{uuid}.blink.host → Your Blink server
```

The same URL works for both environments, making the transition from development to production easy.

<Info>
  During your first `blink deploy` you will be given the option to automatically
  migrate your devhook to the production webhook. Most users choose this option
  as managing separate development and production Slack apps is usually
  unnecessary.
</Info>

## Setting Up Your Slack App

The `blink init` command automates the entire Slack app creation process.

### Step 1: Run the Setup Command

From your agent project directory:

```bash theme={null}
blink init
```

After choosing `Slackbot`, the CLI will prompt you for your Slack app name:

```
What should your Slack app be called?
my-awesome-bot
```

This name appears in Slack when users interact with your bot, and can be changed later.

### Step 2: Behind the Scenes - Devhook Creation

The CLI automatically:

1. **Generates a unique tunnel ID** (UUID)
2. **Saves it to** `.blink/devhook.txt`
3. **Creates your webhook URL**: `https://{uuid}.blink.host`

This URL forwards webhooks to your local machine during development.

<Note>
  The `.blink/devhook.txt` file is automatically added to `.gitignore`. Don't
  commit this to version control.
</Note>

### Step 3: Slack App Manifest Generation

Blink creates a complete Slack app manifest with preconfigured:

**OAuth Scopes:**

* `app_mentions:read` - Detect @mentions
* `chat:write` - Send messages
* `channels:history` - Read channel messages
* `im:history`, `im:read`, `im:write` - Handle DMs
* `users:read` - Get user information
* `reactions:write`, `reactions:read` - Add/read emoji reactions
* `files:read` - Access uploaded files
* `assistant:write` - Use Slack AI features (optional)

**Event Subscriptions:**

* `app_mention` - When bot is @mentioned
* `message.channels` - Channel messages
* `message.im` - Direct messages
* `reaction_added`, `reaction_removed` - Emoji reactions

**Webhook Configuration:**

* All events route to your devhook URL
* Includes interactivity for buttons and modals

### Step 4: Create the Slack App

The CLI opens your browser to:

```
https://api.slack.com/apps?new_app=1&manifest_json={...}
```

In the Slack UI:

<Steps>
  <Step title="Choose workspace">
    Select which workspace to install the app
  </Step>

  <Step title="Review manifest">
    Slack shows the preconfigured app settings. This is where you can alter app
    descriptions and names.
  </Step>

  <Step title="Create app">Click "Create" - Slack provisions your app</Step>

  <Step title="Install to workspace">
    Click "Install to Workspace" and authorize permissions
  </Step>
</Steps>

### Step 5: Provide Credentials

Return to your terminal. The CLI prompts for three pieces of information:

#### App ID

From the **Basic Information** page in Slack:

```
After creating the app, paste the App ID:
A01234567AB
```

#### Signing Secret

From the same **Basic Information** page:

```
Paste your Signing Secret:
•••••••••••••••••••••••••
```

The signing secret verifies that webhook requests actually come from Slack.

#### Bot Token

From the **OAuth & Permissions** page (after installing):

```
Paste your Bot Token:
•••••••••••••••••••••••••••••••
```

The CLI validates the token against Slack's API before accepting it.

### Step 6: Webhook Verification

The CLI starts a webhook listener and waits for connectivity:

```
✓ Webhook listener started
✓ Webhook challenge received

Try sending a DM to the bot - it's "my-awesome-bot" in the search bar.
```

**Behind the scenes:**

1. **Listener connects** to Blink's devhook service via WebSocket
2. **URL verification challenge** - Slack sends a test request, CLI responds automatically
3. **Signature verification** - All incoming requests are verified
4. **Test DM** - You send a message, confirming end-to-end connectivity

If signature verification fails, the CLI prompts you to re-enter the signing secret.

### Step 7: Success

Once the test DM arrives:

```
✓ DM received!
✓ Credentials saved to .env.local

Congrats, your app is now installed and ready to use!
Run `blink dev` to use your agent.
```

Your `.env.local` now contains:

```env theme={null}
SLACK_BOT_TOKEN=xoxb-your-token-here
SLACK_SIGNING_SECRET=your-signing-secret-here
```

## Developing Your Slackbot

### Starting the Development Server

```bash theme={null}
blink dev
```

This command:

* Loads environment variables from `.env.local`
* Starts HTTP server on `localhost:3000`
* Establishes devhook tunnel connection
* Enables hot-reload for code changes

You'll see:

```
blink■ dev

⚙ Send webhooks from anywhere: https://abc123.blink.host
🔄 Hot reload enabled
✓ Agent running on http://localhost:3000
```

### Testing Your Bot

1. **Open Slack** and find your bot in the search bar
2. **Send a DM** or @mention it in a channel
3. **View logs** in your terminal showing request handling
4. **Make code changes directly or via Edit Mode** - they hot-reload automatically

<Note>
  Remember, to chat with your undeployed local agent via Slack, your terminal
  must be in `blink dev` and toggled to [Run
  Mode](/get-started/building-with-blink).
</Note>

### Slack Message Formatting

Slack uses different formatting than standard Markdown:

| Standard Markdown   | Slack Format           |
| ------------------- | ---------------------- |
| `**bold**`          | `*bold*`               |
| `*italic*`          | `_italic_`             |
| `~~strikethrough~~` | `~strikethrough~`      |
| `[text](url)`       | `<url\|text>`          |
| `@username`         | `<@U123456>` (user ID) |

The Slack SDK handles conversions automatically, but be aware when formatting messages.

## Deploying to Production

Once your bot works locally, deploy it to your Blink server. After deploying, you can chat with your Slackbot without needing to be in `blink dev`.

To deploy:

```bash theme={null}
blink deploy
```

### Environment Variable Migration

On first deployment, Blink prompts to copy environment variables:

```
Environment Variables
  Missing 2 vars in .env.production:
    SLACK_BOT_TOKEN, SLACK_SIGNING_SECRET

Copy missing vars from .env.local to .env.production? (Y/n)
```

Choose **Yes** to:

* Copy credentials to `.env.production` file
* Deploy them as encrypted secrets to the server

<Info>Your .env files are automatically added to .gitignore.</Info>

### Webhook Tunnel Migration

This is the key step that keeps your Slack integration working:

```
Webhook Tunnel
  Current: https://abc123.blink.host → local dev
  After: https://abc123.blink.host → production
  Migrating will keep your webhooks working in production

Migrate tunnel to production? (Y/n)
```

**What tunnel migration does:**

1. **Preserves your webhook URL** - No changes needed in your Slack manifest
2. **Updates routing** - Your Blink server now handles requests instead of localhost
3. **Resets local devhook** - Generates new UUID for future dev work

**If you choose Yes:**

* ✅ Production immediately works with existing Slack app
* ✅ No webhook URL updates needed
* ⚠️ Local dev needs reconfiguration (see below)

**If you choose No:**

* ⚠️ You must manually update Slack's webhook URL
* ✅ Local dev continues working unchanged

<Note>
  **Recommended**: Choose **Yes** for first deployment, unless you prefer to
  maintain separate Development and Production Slack apps.
</Note>

### After Deployment

```
✓ Deployed. All new chats will use this version.
https://blink.so/my-org/my-bot/deployments/1

Note: To continue developing locally with webhooks, you'll need to
reconfigure external services. Run `blink setup slack-app` to create
a new Slack app for development.
```

Your bot is now live! Test it in your Slack workspace.

## Continuing Local Development After Migration

After migrating the webhook tunnel to production, you have two options for local development:

### Option 1: Create a Separate Dev Slack App (Recommended)

Run `blink setup slack-app` again to:

* Create a new Slack app dedicated to development
* Generate a fresh devhook tunnel
* Keep dev and prod environments isolated

**Best practice**: Name your dev app clearly (e.g., "My Bot \[DEV]") to distinguish it from production.

### Option 2: Update Existing Slack App Webhook

Temporarily update your production Slack app's webhook URL:

1. Run `blink dev` to get your new devhook URL
2. Go to **Slack App Settings** → **Event Subscriptions**
3. Update **Request URL** to the new devhook URL
4. Remember to revert before testing production changes

<Warning>
  Option 2 means production webhooks won't work while you're developing. Use
  Option 1 for safer development.
</Warning>

## Troubleshooting

<AccordionGroup>
  <Accordion title="Webhook Not Receiving Events">
    **Check:**

    1. Run `blink dev` and verify the devhook URL is shown
    2. In Slack app settings, verify **Event Subscriptions** → **Request URL** matches your devhook
    3. Check that the URL shows a green "Verified" checkmark
    4. Look for "Invalid signature" errors in terminal (wrong signing secret)

    **Fix:**

    ```bash theme={null}
    # Regenerate credentials
    blink setup slack-app
    ```
  </Accordion>

  <Accordion title="Invalid Signing Secret Error">
    The signing secret doesn't match. This happens if:

    * You copied the wrong secret from Slack
    * You regenerated the secret in Slack but didn't update `.env.local`

    **Fix:**

    1. Go to Slack app **Basic Information** page
    2. Copy the current **Signing Secret**
    3. Update `.env.local`:
       ```env theme={null}
       SLACK_SIGNING_SECRET=your-correct-secret-here
       ```
    4. Restart `blink dev`
  </Accordion>

  <Accordion title="Bot Not Responding to DMs">
    **Check:**

    1. Bot user is online (should show as "Active")
    2. Your agent listens to `message` events (not just `app_mention`)
    3. Event handler checks for `is_im` channel type
    4. No errors in terminal logs

    **Example fix:**

    ```typescript theme={null}
    app.event("message", async ({ event }) => {
      // Ignore bot messages and threaded replies
      if (event.subtype || event.bot_id || event.thread_ts) return;

      // Check if DM
      const channelInfo = await app.client.conversations.info({
        channel: event.channel,
      });

      if (channelInfo.channel?.is_im) {
        // Handle DM
      }
    });
    ```
  </Accordion>

  {" "}

  <Accordion title="Bot Not Responding to @Mentions">
    **Check:** 1. `app_mentions:read` scope is enabled 2. Event subscription
    includes `app_mention` 3. Handler is registered: `app.event("app_mention",
          ...)`
  </Accordion>

  <Accordion title="Production Webhook Not Working After Deployment">
    **If you migrated the tunnel:**

    * Webhook should work automatically
    * Check deployment succeeded (not "Failed" status)
    * Verify in the server logs that requests are arriving

    **If you didn't migrate:**

    * Update Slack app webhook URL to your production URL
    * Find it in deployment output or the web UI dashboard
  </Accordion>

  <Accordion title="Environment Variables Not Loading">
    **Development:**

    * Check `.env.local` exists and has correct syntax
    * No quotes needed around values: `TOKEN=abc123` (not `TOKEN="abc123"`)
    * Restart `blink dev` after editing

    **Production:**

    * Verify `.env.production` was created before deploying
    * Check the dashboard → Agent → Settings → Environment Variables
    * Redeploy if variables were added after last deployment
  </Accordion>
</AccordionGroup>
