跳到正文
DEV Community· VoiceDeveloper·· 51 分鐘前AI 評分30

如何為 Discord 機械人加入 AI 語音

Adding AI Voice to Discord Bots

AI 導讀

這篇教學示範如何用 Python 將 ElevenLabs 的文字轉語音服務接入 Discord 機械人,讓機械人生成語音並在語音頻道播放訊息。內容涵蓋基本機械人設定、ElevenLabs API 呼叫及語音克隆,並使用 `eleven_multilingual_v2` 生成語音。

正文

Why Add AI Voice to Your Discord Bot?

Discord is already a hub for real‑time chat, gaming, and community building. Adding a voice component turns a text‑only bot into a more immersive experience—think automated announcements, dynamic NPC dialogue, or even a personal AI companion that can read messages out loud. With modern text‑to‑speech (TTS) services, you can generate natural‑sounding speech on the fly, and with voice‑cloning you can give your bot a unique personality that matches your brand or community vibe.

In this article we’ll walk through how to plug a high‑quality TTS service into a Discord bot using Python. We’ll focus on ElevenLabs, a service that delivers ultra‑realistic speech and even lets you clone a voice with just a few minutes of audio. By the end you’ll have a bot that can speak, react, and sound like a human—ready to wow your server members.

What You’ll Need

Item Reason
Python 3.9+ The language we’ll use for the bot
discord.py (pip install discord.py) Official Discord API wrapper
Requests (pip install requests) Simple HTTP client for calling ElevenLabs
ElevenLabs API key Access to the TTS endpoint (sign up here)
A Discord bot token Create a bot in the Discord Developer Portal and invite it to your server

Setting Up a Basic Discord Bot

First, let’s get a minimal bot that can join a voice channel and play an audio file.

# bot.py
import discord
from discord.ext import commands

intents = discord.Intents.default()
bot = commands.Bot(command_prefix='!', intents=intents)

@bot.event
async def on_ready():
    print(f'Logged in as {bot.user}!')

@bot.command()
async def join(ctx):
    if ctx.author.voice:
        channel = ctx.author.voice.channel
        await channel.connect()
        await ctx.send(f'Joined **{channel.name}**')
    else:
        await ctx.send('You are not in a voice channel!')

@bot.command()
async def leave(ctx):
    if ctx.voice_client:
        await ctx.voice_client.disconnect()
        await ctx.send('Goodbye!')
    else:
        await ctx.send('I am not connected to any voice channel.')

bot.run('YOUR_DISCORD_BOT_TOKEN')

Run python bot.py and test !join / !leave. You now have a bot that can hop into voice channels.

Adding Text‑to‑Speech with ElevenLabs

ElevenLabs provides a simple REST endpoint:

POST https://api.elevenlabs.io/v1/text-to-speech/{voice_id}

You send JSON with the text you want spoken and receive an MP3 stream. The service also offers a voice cloning endpoint, but we’ll start with a pre‑built voice.

1️⃣ Get Your API Key

Sign up at the affiliate link: https://try.elevenlabs.io/kr07zfuqn1bp. After confirming your email, copy the API key from the dashboard.

2️⃣ Choose a Voice ID

ElevenLabs ships with a few default voices (eleven_monolingual_v1). You can also create a cloned voice later; the ID will be returned by the cloning endpoint.

3️⃣ Write a Helper Function

import os
import requests

ELEVENLABS_API_KEY = os.getenv('ELEVENLABS_API_KEY')
DEFAULT_VOICE_ID = 'eleven_monolingual_v1'   # change if you clone your own voice

def synthesize_speech(text: str, voice_id: str = DEFAULT_VOICE_ID) -> bytes:
    url = f'https://api.elevenlabs.io/v1/text-to-speech/{voice_id}'
    headers = {
        'xi-api-key': ELEVENLABS_API_KEY,
        'Content-Type': 'application/json'
    }
    payload = {
        'text': text,
        'model_id': 'eleven_multilingual_v2',   # high‑quality multilingual model
        'voice_settings': {
            'stability': 0.75,
            'similarity_boost': 0.85
        }
    }
    response = requests.post(url, json=payload, headers=headers)
    response.raise_for_status()
    return response.content   # MP3 bytes

Store your API key in an environment variable (ELEVENLABS_API_KEY) so you don’t hard‑code secrets.

4️⃣ Play the Generated Audio

Discord expects an audio source that can be streamed. We’ll write the MP3 to a temporary file and feed it to discord.FFmpegPCMAudio.

import tempfile
import discord

async def say(ctx, text: str):
    if not ctx.voice_client:
        await ctx.invoke(bot.get_command('join'))

    # Get MP3 bytes from ElevenLabs
    mp3_data = synthesize_speech(text)

    # Write to a temp file (FFmpeg needs a file path)
    with tempfile.NamedTemporaryFile(delete=False, suffix='.mp3') as tmp:
        tmp.write(mp3_data)
        tmp_path = tmp.name

    source = discord.FFmpegPCMAudio(tmp_path, executable='ffmpeg')
    ctx.voice_client.play(source, after=lambda e: os.remove(tmp_path))

Now add a command that triggers it:

@bot.command()
async def speak(ctx, *, message: str):
    """Make the bot say something in the voice channel."""
    await say(ctx, message)
    await ctx.send(f'🔊 Speaking: "{message}"')

With !speak Hello, Discord! the bot will join (if not already there) and read the message using ElevenLabs’ natural voice.

Voice Cloning – Giving Your Bot a Unique Identity

ElevenLabs lets you upload a short sample (≈30 seconds) of a voice you own, then creates a clone you can reference by a new voice_id. Here’s a quick curl example:

curl -X POST "https://api.elevenlabs.io/v1/voices/add" \
  -H "xi-api-key: YOUR_API_KEY" \
  -F "name=MyBotVoice" \
  -F "files=@/path/to/sample.wav"

The response contains a voice_id. Replace DEFAULT_VOICE_ID in the Python helper with that ID, and your bot will speak with your voice.

Full Example – Putting It All Together

# full_bot.py
import os
import discord
from discord.ext import commands
import requests, tempfile

intents = discord.Intents.default()
bot = commands.Bot(command_prefix='!', intents=intents)

ELEVENLABS_API_KEY = os.getenv('ELEVENLABS_API_KEY')
DEFAULT_VOICE_ID = os.getenv('ELEVEN_VOICE_ID', 'eleven_monolingual_v1')

def synthesize_speech(text: str, voice_id: str = DEFAULT_VOICE_ID) -> bytes:
    url = f'https://api.elevenlabs.io/v1/text-to-speech/{voice_id}'
    headers = {
        'xi-api-key': ELEVENLABS_API_KEY,
        'Content-Type': 'application/json'
    }
    payload = {
        'text': text,
        'model_id': 'eleven_multilingual_v2',
        'voice_settings': {'stability': 0.75, 'similarity_boost': 0.85}
    }
    resp = requests.post(url, json=payload, headers=headers)
    resp.raise_for_status()
    return resp.content

async def ensure_voice(ctx):
    if not ctx.voice_client:
        if ctx.author.voice:
            await ctx.author.voice.channel.connect()
        else:
            await ctx.send('You need to be in a voice channel!')
            raise commands.CommandError('No voice channel.')

async def say(ctx, text: str):
    await ensure_voice(ctx)
    mp3 = synthesize_speech(text)
    with tempfile.NamedTemporaryFile(delete=False, suffix='.mp3') as tmp:
        tmp.write(mp3)
        path = tmp.name
    source = discord.FFmpegPCMAudio(path, executable='ffmpeg')
    ctx.voice_client.play(source, after=lambda e: os.remove(path))

@bot.event
async def on_ready():
    print(f'🤖 {bot.user} is ready!')

@bot.command()
async def speak(ctx, *, message: str):
    """Speak the given message using ElevenLabs TTS."""
    await say(ctx, message)
    await ctx.send(f'🔈 Speaking: "{message}"')

@bot.command()
async def leave(ctx):
    if ctx.voice_client:
        await ctx.voice_client.disconnect()
        await ctx.send('👋 Bye!')
    else:
        await ctx.send('I am not in a voice channel.')

bot.run(os.getenv('DISCORD_TOKEN'))

Save this as full_bot.py, set the environment variables (DISCORD_TOKEN, ELEVENLABS_API_KEY, optionally ELEVEN_VOICE_ID), and run it. You now have a fully functional AI‑voice Discord bot powered by ElevenLabs.

Tips for Production Use

Tip Why it matters
Cache audio If the same phrase is spoken often, cache the MP3 to avoid extra API calls and latency.
Rate limits ElevenLabs enforces usage limits; batch requests or implement back‑off logic if you hit a 429.
Error handling Wrap the API call in try/except and provide a fallback (e.g., Discord’s built‑in TTS) so the bot never goes silent.
Voice privacy When cloning a voice, ensure you have the speaker’s permission—legal compliance is essential.

Next Steps

  • Add slash commands with discord.app_commands for a modern UI.
  • Integrate speech‑to‑text (e.g., Whisper) so the bot can listen and respond.
  • Create a “story mode” where the bot narrates a game session using a custom cloned voice.

If you’re ready to give your Discord bot a human‑like voice, start experimenting with ElevenLabs today. Their API is straightforward, the quality is impressive, and you can even clone a voice to make your bot truly unique. Grab your API key and try it out now: https://try.elevenlabs.io/kr07zfuqn1bp. Happy coding!

來源:DEV Community · dev.to