Dev.to WebDev 🛠 Dev 👁 0 📖 6 min read

Create AI Voice Responses for Slack Bots

Why Voice‑Enabled Slack Bots Matter Most Slack bots stick to plain text, but adding a spoken response can turn a mundane notification into a more engaging, accessible experience. Think of a bot that reads out critical

Why Voice‑Enabled Slack Bots Matter

Most Slack bots stick to plain text, but adding a spoken response can turn a mundane notification into a more engaging, accessible experience. Think of a bot that reads out critical alerts, narrates daily stand‑up summaries, or even mimics a team member’s voice for a bit of fun. With modern text‑to‑speech (TTS) services you can generate high‑quality audio on the fly, and with a few lines of code you can pipe that audio straight into Slack.

In this guide we’ll walk through:

  1. Setting up a basic Slack bot (Python‑first, but the concepts translate to JavaScript or curl).
  2. Calling a state‑of‑the‑art TTS API to turn text into a voice clip.
  3. Uploading the generated audio back to Slack as a file attachment.

The TTS engine we’ll use is ElevenLabs, which offers natural‑sounding voice cloning and a generous free tier. You can sign up via this affiliate link: https://try.elevenlabs.io/kr07zfuqn1bp – it’s a quick way to get an API key and start experimenting.

Prerequisites

What you need Why
Slack workspace To install the bot and test interactions
Slack App with chat:write, files:write, and commands scopes Allows the bot to post messages and upload audio
Python 3.9+ (or Node.js if you prefer) The language we’ll use for the demo
ElevenLabs API key To generate voice responses
Ngrok (or any public tunnel) To expose your local server to Slack’s event request URLs

Install the required Python packages:

pip install slack_sdk flask requests

1. Create a Minimal Slack Bot

  1. Go to api.slack.com/apps → Create New App → From scratch.
  2. Give it a name (e.g., VoiceBot) and select your workspace.
  3. Under OAuth & Permissions, add the following scopes:
    • chat:write
    • files:write
    • commands
  4. Install the app to your workspace – you’ll receive a Bot User OAuth Token (xoxb-…). Keep it safe.

Next, enable Slash Commands (e.g., /voice) so you can trigger the bot with a simple command.

2. Hook Up ElevenLabs for Text‑to‑Speech

ElevenLabs provides a REST endpoint that accepts plain text and returns an audio file (MP3 by default). After signing up through the affiliate link, grab your API key from the dashboard.

The basic request looks like this:

curl -X POST "https://api.elevenlabs.io/v1/text-to-speech/{voice_id}" \
  -H "xi-api-key: YOUR_ELEVENLABS_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
        "text": "Hello, Slack!",
        "model_id": "eleven_monolingual_v1",
        "voice_settings": {"stability":0.75,"similarity_boost":0.85}
      }' \
  --output speech.mp3

Replace {voice_id} with the ID of the voice you want to use. You can also create a custom cloned voice directly in the ElevenLabs UI – great for giving your bot a unique personality.

3. Putting It All Together – A Flask‑Powered Bot

Below is a compact Flask app that:

  1. Receives a slash command payload (/voice <text>).
  2. Calls ElevenLabs to synthesize the text.
  3. Uploads the resulting MP3 back to the channel where the command originated.
import os
import io
import json
import requests
from flask import Flask, request, make_response
from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError

app = Flask(__name__)

SLACK_BOT_TOKEN = os.getenv("SLACK_BOT_TOKEN")          # xoxb-...
ELEVEN_API_KEY = os.getenv("ELEVEN_API_KEY")          # from ElevenLabs
ELEVEN_VOICE_ID = os.getenv("ELEVEN_VOICE_ID")        # e.g., "EXAMPLE_VOICE_ID"

slack_client = WebClient(token=SLACK_BOT_TOKEN)

def synthesize_speech(text: str) -> bytes:
    """Call ElevenLabs TTS and return raw MP3 bytes."""
    url = f"https://api.elevenlabs.io/v1/text-to-speech/{ELEVEN_VOICE_ID}"
    headers = {
        "xi-api-key": ELEVEN_API_KEY,
        "Content-Type": "application/json"
    }
    payload = {
        "text": text,
        "model_id": "eleven_monolingual_v1",
        "voice_settings": {"stability": 0.75, "similarity_boost": 0.85}
    }
    resp = requests.post(url, headers=headers, json=payload)
    resp.raise_for_status()
    return resp.content

@app.route("/slack/events", methods=["POST"])
def slack_events():
    # Verify the request token if you set one (omitted for brevity)
    data = request.form
    command_text = data.get("text", "").strip()
    channel_id = data.get("channel_id")
    user_id = data.get("user_id")

    if not command_text:
        return make_response("Usage: `/voice <your message>`", 200)

    try:
        # 1️⃣ Synthesize speech
        audio_bytes = synthesize_speech(command_text)

        # 2️⃣ Upload to Slack as a file
        upload_response = slack_client.files_upload(
            channels=channel_id,
            file=io.BytesIO(audio_bytes),
            filename="voice.mp3",
            title=f"Voice response for <@{user_id}>",
            initial_comment=f"Here’s what you asked me to say, <@{user_id}> :speaking_head:"
        )
        # Optional: post a threaded reply with a text version
        slack_client.chat_postMessage(
            channel=channel_id,
            thread_ts=upload_response["file"]["shares"]["public"][channel_id][0]["ts"],
            text=f"*You said:* {command_text}"
        )
    except SlackApiError as e:
        return make_response(f"Slack error: {e.response['error']}", 200)
    except requests.HTTPError as e:
        return make_response(f"TTS error: {e}", 200)

    return make_response("", 200)  # Slack expects an empty 200 response

if __name__ == "__main__":
    # Expose the server to the internet (ngrok example)
    # ngrok http 5000
    app.run(port=5000, debug=True)

How It Works

Step What Happens
Slash command Slack sends a POST to /slack/events with the user’s text.
Synthesize synthesize_speech() hits ElevenLabs, returning MP3 bytes.
Upload files_upload streams the MP3 back to Slack, attaching it to the channel.
Threaded reply A small text confirmation keeps the conversation tidy.

You can replace the Flask server with an Express app in Node.js; the core logic (HTTP POST to ElevenLabs, then files.upload via Slack SDK) stays the same.

4. Going Further – Voice Cloning & Personalization

ElevenLabs shines when you need a consistent brand voice or a playful clone of a team member. After uploading a few minutes of reference audio, the platform creates a custom voice ID you can swap into ELEVEN_VOICE_ID. The API call remains identical, letting you switch personalities on the fly:

# Example: toggle between “formal” and “casual” voices
voice_map = {"formal": "VOICE_ID_1", "casual": "VOICE_ID_2"}
selected_voice = voice_map.get(style, "VOICE_ID_1")

You can also experiment with the stability and similarity_boost parameters to make the output more expressive or more faithful to the reference voice.

5. Deploying to Production

For a production‑ready bot you’ll want to:

  • Secure the endpoint – verify Slack signatures using the X-Slack-Signature header.
  • Store secrets – use a secret manager (AWS Secrets Manager, GCP Secret Manager, etc.).
  • Use a managed runtime – AWS Lambda + API Gateway, Google Cloud Functions, or a container on Fly.io.
  • Handle rate limits – both Slack and ElevenLabs enforce limits; implement exponential back‑off.

Even a modest serverless function can handle dozens of requests per minute, which is more than enough for most internal tools.

6. Testing the Bot

  1. Start the Flask app locally: python app.py.
  2. Run ngrok http 5000 and copy the HTTPS URL.
  3. In the Slack App dashboard, set Request URL for your slash command to https://<ngrok-id>.ngrok.io/slack/events.
  4. In any channel, type: /voice Hey team, the build just succeeded!.
  5. You should see an MP3 file appear, ready to play with a single click.

If you run into errors, check the Flask console for stack traces and the Slack “Event Subscriptions” page for any request validation failures.

7. Why ElevenLabs Is a Good Fit

  • Naturalness – The generated speech sounds almost human, which reduces fatigue for listeners.
  • Voice cloning – Turn a short sample into a persistent voice for your bot.
  • Simple pricing – Free tier for prototyping; pay‑as‑you‑go for larger volumes.

Getting started is as easy as signing up here: https://try.elevenlabs.io/kr07zfuqn1bp. The dashboard gives you instant API keys and a UI to preview voices before you code.

Wrap‑Up & Next Steps

You now have a fully functional Slack bot that can speak back to your team. From here you might:

  • Hook the bot into CI pipelines to read out test results.
  • Combine it with sentiment analysis to adjust tone (e.g., calmer voice for error alerts).
  • Build a “voice channel” where users can leave spoken messages that get transcribed and stored.

The sky’s the limit when you blend Slack’s collaboration platform with ElevenLabs’ cutting‑edge TTS.

Ready to give your Slack bot a voice? Grab your ElevenLabs API key via the affiliate link, spin up the example code, and start experimenting today: https://try.elevenlabs.io/kr07zfuqn1bp. Happy coding!

📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.