如何為 Slack Bot 建立 AI 語音回覆
Create AI Voice Responses for Slack Bots
這篇教學示範如何用 Bolt for Python 和 ElevenLabs TTS,讓 Slack Bot 將用戶訊息轉成語音,並以 MP3 回覆至同一頻道。Bot 會在收到 @VoiceBot 提及時移除提及標記、合成語音並上載音檔;範例需要 ElevenLabs API key。
Why Voice‑Enabled Slack Bots Are Worth It
Most Slack bots reply with plain text, but imagine a bot that can read out alerts, summarize meeting notes, or even deliver a personalized welcome in the user�s own voice. Adding text‑to‑speech (TTS) turns a static message into a richer, more accessible experience—especially for remote teams that spend a lot of time in channels while multitasking.
In this post you’ll learn how to:
- Set up a basic Slack bot (using Bolt for Python).
- Call a high‑quality TTS service (ElevenLabs) to generate audio from text.
- Upload the resulting MP3 back to Slack so it appears as a voice reply.
All the code is runnable locally, and the only external dependency you need is an ElevenLabs API key (sign‑up is free and you can start generating voice clips instantly).
Prerequisites
| What you need | Why |
|---|---|
| Python 3.9+ | The example uses Bolt for Python, but the same concepts apply to Node or curl. |
| Slack workspace | To install a custom app and obtain a Bot Token (xoxb-…). |
| ElevenLabs account | Their API produces natural‑sounding speech and offers voice cloning. Grab a key from the ElevenLabs dashboard. |
| ngrok (optional) | If you want to expose a local server for Slack events. |
You can install the required Python packages with:
pip install slack_bolt slack_sdk requests
1. Create a Slack App
- Go to api.slack.com/apps → Create New App.
- Choose From scratch, give it a name (e.g.,
VoiceBot), and pick your workspace. - Under OAuth & Permissions add the following scopes:
-
chat:write– to post messages. -
files:write– to upload audio files. -
app_mentions:read– to listen for@VoiceBotmentions.
Install the app to your workspace and copy the Bot User OAuth Token (
xoxb-…).Enable Event Subscriptions → Subscribe to bot events → add
app_mention. Set the request URL to your ngrok tunnel (e.g.,https://abcd1234.ngrok.io/slack/events). Save.
2. Get an ElevenLabs API Key
Sign up at the affiliate link: ElevenLabs – Free TTS API. After confirming your email, navigate to API Keys and copy the key. You’ll need it for the HTTP request that turns text into speech.
3. Generate Speech with ElevenLabs
ElevenLabs offers a simple REST endpoint:
POST https://api.elevenlabs.io/v1/text-to-speech/{voice_id}
-
voice_idcan be a default voice (e.g.,eleven_monolingual_v1) or a custom cloned voice you created in the dashboard. - The body is JSON:
{ "text": "Your message", "model_id": "eleven_monolingual_v1" }. - Include the header
xi-api-key: YOUR_ELEVENLABS_API_KEY.
Here’s a minimal Python helper:
import requests
ELEVEN_API_KEY = "YOUR_ELEVENLABS_API_KEY"
DEFAULT_VOICE = "eleven_monolingual_v1" # change to your cloned voice ID if you have one
def synthesize(text: str) -> bytes:
url = f"https://api.elevenlabs.io/v1/text-to-speech/{DEFAULT_VOICE}"
headers = {
"Accept": "audio/mpeg",
"Content-Type": "application/json",
"xi-api-key": ELEVEN_API_KEY,
}
payload = {"text": text, "model_id": "eleven_monolingual_v1"}
response = requests.post(url, json=payload, headers=headers)
response.raise_for_status()
return response.content # raw MP3 bytes
Tip: If you have a cloned voice, replace
DEFAULT_VOICEwith the ID you received after the cloning process. The same endpoint works for any voice you own.
4. Wire It Up with Bolt
Below is a complete, but concise, Bolt‑for‑Python app that listens for @VoiceBot mentions, turns the message (minus the mention) into speech, and posts the audio back to the channel.
import os
from slack_bolt import App
from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError
# ---- Slack setup -------------------------------------------------
app = App(token=os.getenv("SLACK_BOT_TOKEN"))
client = WebClient(token=os.getenv("SLACK_BOT_TOKEN"))
# ---- ElevenLabs helper (copy from previous section) ---------------
ELEVEN_API_KEY = os.getenv("ELEVEN_API_KEY")
DEFAULT_VOICE = "eleven_monolingual_v1"
def synthesize(text: str) -> bytes:
url = f"https://api.elevenlabs.io/v1/text-to-speech/{DEFAULT_VOICE}"
headers = {
"Accept": "audio/mpeg",
"Content-Type": "application/json",
"xi-api-key": ELEVEN_API_KEY,
}
payload = {"text": text, "model_id": "eleven_monolingual_v1"}
resp = requests.post(url, json=payload, headers=headers)
resp.raise_for_status()
return resp.content
# ---- Event handler ------------------------------------------------
@app.event("app_mention")
def handle_mention(body, say, logger):
try:
# Extract the raw text after the bot mention
text = body["event"]["text"]
user = body["event"]["user"]
# Remove the mention syntax (<@Uxxxx>) so we only synthesize the actual message
cleaned = " ".join(part for part in text.split() if not part.startswith("<@"))
if not cleaned.strip():
say(f"<@{user}> Hey, give me something to read! 🎤")
return
logger.info(f"Synthesizing: {cleaned}")
audio_bytes = synthesize(cleaned)
# Upload MP3 to Slack
upload_resp = client.files_upload(
channels=body["event"]["channel"],
file=audio_bytes,
filename="voice_response.mp3",
title="Voice reply",
initial_comment=f"Here’s what I heard, <@{user}>:",
)
logger.info(f"Uploaded file: {upload_resp['file']['id']}")
except SlackApiError as e:
logger.error(f"Slack error: {e.response['error']}")
say(f"Sorry <@{user}>, I hit a snag.")
except Exception as exc:
logger.exception(exc)
say(f"Something went wrong, <@{user}>. Check the logs.")
# ---- Start the server ---------------------------------------------
if __name__ == "__main__":
# For local testing you can use `python app.py` and expose via ngrok
app.start(port=int(os.getenv("PORT", 3000)))
How It Works
-
Event trigger – Slack sends an
app_mentionpayload whenever someone writes@VoiceBot …. -
Message cleaning – We strip out the
<@Uxxxx>token so the TTS engine only receives the actual content. -
Call ElevenLabs – The
synthesizefunction returns MP3 bytes. -
Upload –
files_uploadposts the audio file to the same channel, automatically creating a playable message.
That’s it! The bot now replies with a voice clip every time you mention it.
5. Testing with curl (optional)
If you prefer not to run a full Bolt app, you can hit the ElevenLabs endpoint directly with curl:
curl -X POST "https://api.elevenlabs.io/v1/text-to-speech/eleven_monolingual_v1" \
-H "Accept: audio/mpeg" \
-H "Content-Type: application/json" \
-H "xi-api-key: YOUR_ELEVENLABS_API_KEY" \
-d '{"text":"Hello Slack! This is a test.", "model_id":"eleven_monolingual_v1"}' \
--output hello.mp3
Upload hello.mp3 manually in Slack (+ → Upload a file) and you’ll hear the same quality you’d get from the bot.
6. Going Further
| Idea | What you need |
|---|---|
| Voice cloning | Record ~30 seconds of a team member’s voice in the ElevenLabs UI, then use that voice_id in the code. |
| Dynamic language switching | Pass a language parameter (ElevenLabs supports multiple locales) based on Slack user preferences. |
| Cache frequent phrases | Store MP3s in a local Redis cache to avoid repeated API calls for static messages (e.g., “Standup starts in 5 minutes”). |
| Interactive audio | Combine with Slack’s Block Kit to add play/pause buttons or transcripts alongside the file. |
All of these enhancements build on the same simple request/response pattern shown above.
7. Deploying to Production
-
Containerize – Put the script in a Dockerfile (
FROM python:3.11-slim) and expose port 3000. -
Serverless – The same handler can be wrapped in an AWS Lambda using the
slack_bolt.adapter.aws_lambdaadapter. -
Secrets management – Store
SLACK_BOT_TOKENandELEVEN_API_KEYin your platform’s secret store (e.g., AWS Secrets Manager, GCP Secret Manager).
Make sure your production URL is HTTPS; Slack will reject non‑TLS endpoints.
8. Wrap‑Up
Adding voice to Slack bots doesn’t have to be a research‑paper‑level effort. With just a few lines of Python and a robust TTS provider like ElevenLabs, you can turn any textual response into a natural‑sounding audio clip—opening the door to more inclusive, engaging, and fun interactions.
Ready to give your Slack bot a voice? Grab an ElevenLabs API key today at the affiliate link below, copy the code, and start experimenting.
👉 Try ElevenLabs now: https://try.elevenlabs.io/kr07zfuqn1bp
Happy coding, and may your bots always be heard loud and clear!
來源:DEV Community · dev.to