DEV Community

VoiceDeveloper
VoiceDeveloper

Posted on

Create AI Voice Responses for Slack Bots

Why Voice‑Enabled Slack Bots Are the Next Big Thing

If you’ve ever built a Slack bot that spits out plain text, you know the satisfaction of automating a workflow. But imagine a bot that can talk back to your team—reading out alerts, summarizing meeting notes, or even delivering a personalized welcome in the user’s own voice. With modern text‑to‑speech (TTS) and voice‑cloning services, turning that idea into reality is easier than ever.

In this post we’ll walk through the end‑to‑end process of adding AI‑generated voice responses to a Slack bot. We’ll use Python for the server side, the Slack Events API for interaction, and ElevenLabs as our TTS engine (the link works as an affiliate, so you’ll get a small credit when you sign up). By the end you’ll have a working prototype that can synthesize speech on the fly and send it back to a channel as an audio file.


What You’ll Need

Item Reason
Slack App with Bot Token and Event Subscriptions To receive messages and post audio files
Python 3.9+ Our demo server and the ElevenLabs client library
ngrok (or any public HTTPS tunnel) Slack needs a reachable URL for events
ElevenLabs API key The TTS service that produces high‑quality, cloned voices
ffmpeg (optional) Convert the raw .mp3 from ElevenLabs to a format Slack prefers (.wav or .mp3 works fine)

You can get a free API key from ElevenLabs by signing up here: https://try.elevenlabs.io/kr07zfuqn1bp.


Setting Up the ElevenLabs API

ElevenLabs offers a straightforward REST API. First, install the official Python SDK:

pip install elevenlabs
Enter fullscreen mode Exit fullscreen mode

Then, configure it with your API key:

import os
from elevenlabs import set_api_key, generate, save

ELEVEN_API_KEY = os.getenv("ELEVEN_API_KEY")
set_api_key(ELEVEN_API_KEY)
Enter fullscreen mode Exit fullscreen mode

If you prefer a raw curl call, here’s the equivalent:

curl -X POST "https://api.elevenlabs.io/v1/text-to-speech/{voice_id}" \
     -H "xi-api-key: $ELEVEN_API_KEY" \
     -H "Content-Type: application/json" \
     -d '{
           "text": "Hello Slack! This is your friendly bot speaking.",
           "model_id": "eleven_multilingual_v1",
           "voice_settings": { "stability": 0.75, "similarity_boost": 0.85 }
         }' \
     --output hello.mp3
Enter fullscreen mode Exit fullscreen mode

Replace {voice_id} with the ID of the voice you want to use (you can list your voices via the API or the ElevenLabs dashboard).


Building a Minimal Slack Bot

Create a new Slack app at https://api.slack.com/apps, enable Bot Token Scopes chat:write and files:write, and subscribe to the message.channels event.

Now spin up a tiny Flask server that listens for events:

from flask import Flask, request, jsonify
import requests
import json
import os
from elevenlabs import generate, save

app = Flask(__name__)

SLACK_BOT_TOKEN = os.getenv("SLACK_BOT_TOKEN")
SLACK_SIGNING_SECRET = os.getenv("SLACK_SIGNING_SECRET")

def post_audio_to_slack(channel_id, file_path, title):
    with open(file_path, "rb") as f:
        response = requests.post(
            "https://slack.com/api/files.upload",
            headers={"Authorization": f"Bearer {SLACK_BOT_TOKEN}"},
            data={"channels": channel_id, "title": title},
            files={"file": f},
        )
    return response.json()

@app.route("/slack/events", methods=["POST"])
def slack_events():
    payload = request.json

    # URL verification challenge
    if payload.get("type") == "url_verification":
        return jsonify({"challenge": payload["challenge"]})

    # Handle a message event
    event = payload.get("event", {})
    if event.get("type") == "message" and not event.get("bot_id"):
        text = event.get("text")
        channel = event.get("channel")

        # Simple trigger: if the message starts with "!speak"
        if text.lower().startswith("!speak"):
            # Strip the command and send the rest to ElevenLabs
            to_speak = text[6:].strip() or "I didn't hear anything."
            audio_bytes = generate(
                text=to_speak,
                voice="YOUR_VOICE_ID",   # get this from ElevenLabs
                model="eleven_multilingual_v1"
            )
            audio_path = "/tmp/output.mp3"
            save(audio_bytes, audio_path)

            # Upload the audio back to Slack
            post_audio_to_slack(channel, audio_path, "Voice reply")
            return "", 200

    return "", 200

if __name__ == "__main__":
    app.run(port=3000)
Enter fullscreen mode Exit fullscreen mode

Key points

  • The bot reacts to !speak <message> and sends the <message> to ElevenLabs.
  • The generated MP3 is saved locally and then uploaded to Slack using files.upload.
  • You can swap YOUR_VOICE_ID for any voice you own in ElevenLabs, including cloned voices of your own team members.

Using a Cloned Voice

One of the coolest features of ElevenLabs is voice cloning. Record a 30‑second sample of a team member’s voice, upload it through the ElevenLabs dashboard, and you’ll receive a new voice_id. Replace the static voice argument in the generate call with that ID, and the bot will now speak in that person’s voice.

audio_bytes = generate(
    text=to_speak,
    voice="cloned-voice-id-123",
    model="eleven_multilingual_v1"
)
Enter fullscreen mode Exit fullscreen mode

Be mindful of privacy and consent—always get permission before cloning a voice.


Deploying to Production

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

  1. Run behind a proper web server (Gunicorn + Nginx).
  2. Store secrets securely (AWS Secrets Manager, GCP Secret Manager, or .env with Docker secrets).
  3. Add rate‑limiting to avoid hitting ElevenLabs or Slack API quotas.
  4. Cache generated audio for repeated phrases to reduce cost.

A simple Redis cache example:

import redis
cache = redis.Redis(host="localhost", port=6379, db=0)

def get_or_generate(text, voice_id):
    key = f"tts:{voice_id}:{hash(text)}"
    cached = cache.get(key)
    if cached:
        return cached  # bytes

    audio = generate(text=text, voice=voice_id, model="eleven_multilingual_v1")
    cache.setex(key, 86400, audio)  # cache for 1 day
    return audio
Enter fullscreen mode Exit fullscreen mode

Tips & Best Practices

Tip Why It Matters
Limit text length ElevenLabs charges per generated character. Trim long messages or summarize before sending.
Set stability and similarity_boost Tweak these voice settings for a more natural tone. Values between 0.6‑0.9 work well for most use cases.
Provide fallback If the TTS service fails, send a plain‑text response so the conversation doesn’t stall.
Monitor latency Generating audio can take a second or two. Show a “typing…” indicator in Slack (chat.postMessage with typing flag) to keep users happy.

Wrap‑Up

Adding voice to a Slack bot opens up accessibility, engagement, and a touch of personality that plain text can’t match. With just a few lines of Python and the powerful ElevenLabs API, you can generate realistic speech, clone team members’ voices, and deliver the audio directly into Slack channels.

Ready to give your bot a voice? Grab your ElevenLabs API key here: https://try.elevenlabs.io/kr07zfuqn1bp and start experimenting. Happy coding!

Top comments (0)