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

Create AI Voice Responses for Slack Bots

Why Voice‑Enabled Slack Bots Matter Slack has become a hub for everything from status updates to code reviews. Yet most bots still answer with plain text. Imagine a bot that can speak—announcing build results, reading

Why Voice‑Enabled Slack Bots Matter

Slack has become a hub for everything from status updates to code reviews. Yet most bots still answer with plain text. Imagine a bot that can speak—announcing build results, reading out meeting agendas, or even delivering personalized greetings in the voice of a brand mascot. Adding voice not only makes interactions more engaging but also opens up accessibility for users who prefer audio over text.

Voice‑enabled bots sit on top of two core technologies:

  1. Text‑to‑Speech (TTS) – Convert any string into natural‑sounding speech.
  2. Voice Cloning – Create a synthetic voice that sounds like a real person or a brand character.

With the right tools, you can add these capabilities to a Slack bot in a matter of minutes.

Choosing a TTS & Voice‑Cloning Service

There are dozens of TTS APIs out there, but a few stand out for their quality and developer experience:

  • ElevenLabs – Offers ultra‑natural voices, real‑time streaming, and voice cloning with just a few hundred lines of code.
  • Google Cloud Text‑to‑Speech – Reliable but a bit heavy on configuration.
  • Amazon Polly – Good integration with AWS but lacks the advanced neural voices that feel truly human.

For this guide we’ll focus on ElevenLabs because of its high‑fidelity output and straightforward API. If you’re curious, you can sign up with this affiliate link: https://try.elevenlabs.io/kr07zfuqn1bp.

Prerequisites

Item Why
Slack Bot Token Needed to post messages and upload files.
ElevenLabs API Key Required to generate audio.
Python 3.9+ (or Node.js 14+) For the code snippets.
requests or node-fetch To make HTTP calls.

Tip: Store your keys in environment variables or a secrets manager—never hard‑code them.

Step‑by‑Step: From Text to Slack Audio

Below is a minimal flow:

  1. Receive a trigger in Slack (e.g., /announce).
  2. Convert the text to an audio file using ElevenLabs.
  3. Upload the audio file to Slack as a message attachment.

1. Capture the Slack Event

Assuming you’re using the Events API, you’ll get a payload like:

{
  "type": "app_mention",
  "user": "U12345",
  "text": "/announce Build finished successfully!"
}

Parse the text field to extract the message you want to vocalize.

2. Convert Text to Speech with ElevenLabs

Python Example

import os
import requests

ELEVEN_API_KEY = os.getenv("ELEVEN_API_KEY")
ELEVEN_ENDPOINT = "https://api.elevenlabs.io/v1/text-to-speech/"

def synthesize_speech(text, voice_id="Rachel"):
    url = f"{ELEVEN_ENDPOINT}{voice_id}"
    headers = {
        "xi-api-key": ELEVEN_API_KEY,
        "Content-Type": "application/json"
    }
    payload = {
        "text": text,
        "voice_settings": {
            "stability": 0.5,
            "similarity_boost": 0.75
        }
    }
    response = requests.post(url, json=payload, headers=headers, stream=True)
    response.raise_for_status()
    return response.content  # raw MP3 bytes

audio_bytes = synthesize_speech("Build finished successfully!")
with open("build.mp3", "wb") as f:
    f.write(audio_bytes)

Node.js Example

const fetch = require('node-fetch');
const fs = require('fs');
require('dotenv').config();

const ELEVEN_API_KEY = process.env.ELEVEN_API_KEY;
const ELEVEN_ENDPOINT = 'https://api.elevenlabs.io/v1/text-to-speech/';

async function synthesizeSpeech(text, voiceId = 'Rachel') {
  const res = await fetch(`${ELEVEN_ENDPOINT}${voiceId}`, {
    method: 'POST',
    headers: {
      'xi-api-key': ELEVEN_API_KEY,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      text,
      voice_settings: { stability: 0.5, similarity_boost: 0.75 }
    })
  });
  if (!res.ok) throw new Error(`ElevenLabs error: ${res.statusText}`);
  const buffer = await res.buffer();
  return buffer;
}

(async () => {
  const audio = await synthesizeSpeech('Build finished successfully!');
  fs.writeFileSync('build.mp3', audio);
})();

Voice Cloning

If you want a custom voice, first upload a sample audio to ElevenLabs and generate a voice_id. Then pass that voice_id to the same endpoint.

3. Post the Audio to Slack

Slack’s files.upload method accepts an MP3 stream. The simplest way is to upload the file and then send a message referencing it.

SLACK_BOT_TOKEN = os.getenv("SLACK_BOT_TOKEN")
SLACK_UPLOAD_URL = "https://slack.com/api/files.upload"

def upload_to_slack(file_path, channel_id):
    with open(file_path, "rb") as f:
        res = requests.post(
            SLACK_UPLOAD_URL,
            headers={"Authorization": f"Bearer {SLACK_BOT_TOKEN}"},
            files={"file": f},
            data={
                "channels": channel_id,
                "title": "Build Notification",
                "initial_comment": "Here's the update."
            }
        )
    res.raise_for_status()
    return res.json()

upload_to_slack("build.mp3", "C12345")

Curl Alternative

curl -F file=@build.mp3 \
     -F channels=C12345 \
     -F title="Build Notification" \
     -F initial_comment="Here's the update." \
     -H "Authorization: Bearer $SLACK_BOT_TOKEN" \
     https://slack.com/api/files.upload

When the file is posted, Slack automatically renders an audio player in the channel.

Handling Real‑Time Streaming (Optional)

If you want the bot to “speak” live—e.g., during a call or a live Q&A—you can stream MP3 data directly to a WebSocket or use the Slack chat.postMessage API with a blocks layout that contains an audio element. ElevenLabs supports streaming responses via stream=True in the request. In a production bot, you’d pipe that stream into a temporary file or directly into Slack’s upload endpoint.

Deployment Tips

Concern Recommendation
Latency Cache common phrases as MP3s; pre‑generate if possible.
Cost ElevenLabs charges per minute of audio. Use short messages and moderate voice settings.
Scalability Wrap the TTS call in an async worker (e.g., Celery, Cloud Functions) to avoid blocking the Slack event handler.
Security Store API keys in secret stores (AWS Secrets Manager, Vault). Rotate keys regularly.

Troubleshooting Common Issues

Symptom Likely Cause Fix
“Audio file not playing” File type mismatch or corrupted upload Ensure the file is MP3 and the Content-Type header is set correctly.
“ElevenLabs API error 429” Rate limiting Implement exponential back‑off or queue requests.
“Slack returns 400 Bad Request” Missing or invalid channels parameter Double‑check the channel ID and ensure the bot has access to that channel.

Wrapping It Up

Adding AI voice responses to your Slack bot is surprisingly straightforward once you have the right API. ElevenLabs offers a simple, high‑quality TTS engine with voice‑cloning support that fits neatly into a typical bot workflow. Whether you’re building a CI/CD notifier, a virtual assistant, or a fun interactive game, the added dimension of sound can make your bot feel more human and approachable.

Give it a try in your next Slack integration. The first 10 minutes of audio are free, so you can experiment without any cost. Sign up today and start turning text into voice with ElevenLabs: https://try.elevenlabs.io/kr07zfuqn1bp.

Happy coding—and happy talking!

📰 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.