DEV Community

VoiceDeveloper
VoiceDeveloper

Posted on

Create AI Voice Responses for Slack Bots

Introduction

If you’ve ever wished your Slack bot could talk back to you, you’re not alone. Adding voice responses turns a plain text interaction into a more engaging, accessible experience—perfect for status updates, alerts, or just a little fun. In this article we’ll walk through building a Slack bot that speaks using modern text‑to‑speech (TTS) and voice‑cloning technology. We’ll use ElevenLabs as the TTS engine (the affiliate link is included below) and glue everything together with a few lines of Python.

TL;DR – By the end of this guide you’ll have a Slack bot that receives a message, generates a realistic voice clip with ElevenLabs, uploads it to Slack, and posts the audio file back to the channel.


Why Voice in Slack?

  • Accessibility – Team members who are on the move or have visual impairments can listen to updates instead of reading them.
  • Speed – A quick “standup completed” audio clip can be processed faster than a long text thread.
  • Personality – A bot that sounds like a real person (or even a custom clone of your own voice) feels more human‑centric, which can improve adoption.

All of this is possible today without building a deep learning model from scratch. Services like ElevenLabs provide high‑quality, low‑latency TTS APIs that can even clone a voice from a few minutes of audio.


Getting Started with ElevenLabs

ElevenLabs offers a straightforward REST API for generating speech. Sign up through the affiliate link below, grab your API key, and you’re ready to go:

🔗 Try ElevenLabs here →

Once you have the key, you can request speech in a variety of voices, set speaking rates, and even use your own cloned voice model (if you’ve uploaded a sample). The API returns an MP3 stream that we’ll later upload to Slack.


Setting Up a Slack Bot

First, create a Slack app:

  1. Go to https://api.slack.com/apps and click Create New App.
  2. Choose From scratch, give it a name (e.g., VoiceBot), and select your workspace.
  3. Under OAuth & Permissions, add the following scopes:
    • chat:write
    • files:write
    • app_mentions:read
  4. Install the app to your workspace and copy the Bot User OAuth Token (it starts with xoxb-).

You’ll also need the Signing Secret under Basic Information for request verification.


Converting Text to Speech with ElevenLabs

Below is a minimal Python function that sends a prompt to ElevenLabs and returns the raw MP3 bytes.

import requests

ELEVENLABS_API_KEY = "YOUR_ELEVENLABS_API_KEY"
ELEVENLABS_TTS_URL = "https://api.elevenlabs.io/v1/text-to-speech/EXAMPLE_VOICE_ID"

def synthesize_speech(text: str) -> bytes:
    """Call ElevenLabs TTS and return MP3 data."""
    headers = {
        "xi-api-key": ELEVENLABS_API_KEY,
        "Content-Type": "application/json"
    }
    payload = {
        "text": text,
        "model_id": "eleven_monolingual_v1",
        "voice_settings": {
            "stability": 0.75,
            "similarity_boost": 0.85
        }
    }
    response = requests.post(ELEVENLABS_TTS_URL, json=payload, headers=headers)
    response.raise_for_status()
    return response.content
Enter fullscreen mode Exit fullscreen mode

Tip: Replace EXAMPLE_VOICE_ID with the ID of the voice you want to use. You can list your voices via the /v1/voices endpoint or use a cloned voice ID if you’ve uploaded a custom sample.


Uploading Audio to Slack

Slack doesn’t support streaming audio directly in a message, but you can upload an MP3 file and share it. Here’s a helper that takes the MP3 bytes from the previous step and posts it back to the channel where the bot was mentioned.

from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError

SLACK_BOT_TOKEN = "xoxb-YOUR_SLACK_BOT_TOKEN"
slack_client = WebClient(token=SLACK_BOT_TOKEN)

def upload_and_post(audio_bytes: bytes, channel: str, title: str = "Voice reply"):
    try:
        # Upload the file first
        upload_resp = slack_client.files_upload(
            channels=channel,
            file=audio_bytes,
            filename="reply.mp3",
            title=title,
            filetype="mp3"
        )
        # Share the file in a message
        slack_client.chat_postMessage(
            channel=channel,
            text=f"Here’s the voice response:",
            attachments=[
                {
                    "fallback": title,
                    "title": title,
                    "file_id": upload_resp["file"]["id"]
                }
            ]
        )
    except SlackApiError as e:
        print(f"Slack error: {e.response['error']}")
Enter fullscreen mode Exit fullscreen mode

Wiring It All Together

Now let’s create a simple Flask endpoint that Slack will hit whenever the bot is mentioned. The flow is:

  1. Slack sends an event_callback with the message text.
  2. Verify the request signature (omitted here for brevity).
  3. Strip the bot mention and feed the remaining text to synthesize_speech.
  4. Upload the MP3 back to the same channel.
from flask import Flask, request, jsonify
import hmac
import hashlib
import os

app = Flask(__name__)

SLACK_SIGNING_SECRET = os.getenv("SLACK_SIGNING_SECRET")

def verify_slack_request(req):
    timestamp = req.headers.get("X-Slack-Request-Timestamp")
    sig_basestring = f"v0:{timestamp}:{req.get_data(as_text=True)}"
    my_sig = "v0=" + hmac.new(
        SLACK_SIGNING_SECRET.encode(),
        sig_basestring.encode(),
        hashlib.sha256
    ).hexdigest()
    slack_sig = req.headers.get("X-Slack-Signature")
    return hmac.compare_digest(my_sig, slack_sig)

@app.route("/slack/events", methods=["POST"])
def slack_events():
    if not verify_slack_request(request):
        return "Invalid request", 403

    data = request.json
    # Respond to URL verification challenge
    if data.get("type") == "url_verification":
        return jsonify({"challenge": data["challenge"]})

    # Only handle app_mention events
    if data.get("event", {}).get("type") == "app_mention":
        event = data["event"]
        channel = event["channel"]
        user_text = event["text"]
        # Remove the bot mention part
        cleaned_text = user_text.split(">")[1].strip() if ">" in user_text else user_text

        # Generate speech
        audio = synthesize_speech(cleaned_text)

        # Post back to Slack
        upload_and_post(audio, channel, title=f"Reply to <@{event['user']}>")

    return "", 200

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

What you need to run this:

  • pip install flask slack_sdk requests
  • Set environment variables:
    • SLACK_SIGNING_SECRET
    • SLACK_BOT_TOKEN
    • ELEVENLABS_API_KEY

Expose the Flask server with a tool like ngrok and add the public URL to your Slack app’s Event Subscriptions (subscribe to app_mention).


Going Further

  • Voice Cloning – Upload a short audio sample to ElevenLabs, create a custom voice ID, and replace EXAMPLE_VOICE_ID with that ID. Your bot can now sound like your team lead, mascot, or even yourself.
  • Dynamic Parameters – Let users control speed, pitch, or emotion via slash commands (/voice speed=1.2 text=Hello).
  • Persisted Audio – Store generated clips in an S3 bucket and reuse them for frequently asked questions, saving API calls.

Next Steps

You now have a fully functional Slack bot that listens, converts text to a natural‑sounding voice, and replies with an audio file—all powered by ElevenLabs. Play around with different voices, experiment with voice cloning, and consider adding a UI in Slack to let users pick their favorite voice.

🔊 Ready to give your Slack bot a voice? Try ElevenLabs today and bring your bots to life: https://try.elevenlabs.io/kr07zfuqn1bp

Happy coding! 🚀

Top comments (0)