如何使用pyttsx3实现Discord机器人在语音频道播报文字频道消息
Discord文字转语音播报机器人实现方案
你当前的代码是将文字转换为本地音频播放,要对接Discord语音频道,需要完成两个核心调整:将TTS输出保存为音频文件、调用discord.py的语音接口播放音频到语音频道。
前置依赖准备
- 安装语音传输依赖:
pip install pynacl - 安装FFmpeg:discord.py播放音频需要调用FFmpeg做解码,Windows平台可下载FFmpeg二进制文件并添加到系统环境变量,Linux平台可直接执行
sudo apt install ffmpeg安装。
修改后的完整实现代码
import discord import pyttsx3 import os from tempfile import gettempdir class MyClient(discord.Client): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.voice_client = None self.tts_engine = pyttsx3.init() # 全局初始化一次TTS引擎,提升运行性能 async def on_ready(self): print('Logged on as', self.user) async def on_message(self, message): if message.author == self.user: return # 加入语音频道指令 if message.content == "!join": if not message.author.voice: await message.channel.send("你需要先加入一个语音频道") return self.voice_client = await message.author.voice.channel.connect() await message.channel.send("已加入语音频道,开始播报消息") return # 退出语音频道指令 if message.content == "!leave": if self.voice_client: await self.voice_client.disconnect() self.voice_client = None await message.channel.send("已退出语音频道") return # 未加入语音频道时不播报 if not self.voice_client: return # 如需限定仅播报指定文字频道消息,取消下方注释替换为目标频道ID即可 # if message.channel.id != 123456789: # return message_content = message.content # 生成临时音频文件路径 temp_audio_path = os.path.join(gettempdir(), f"tts_{message.id}.wav") # 将文字转换为音频文件存储 self.tts_engine.save_to_file(message_content, temp_audio_path) self.tts_engine.runAndWait() # 非播放状态时将音频输出到语音频道,播放完成自动删除临时文件 if not self.voice_client.is_playing(): self.voice_client.play(discord.FFmpegPCMAudio(temp_audio_path), after=lambda e: os.remove(temp_audio_path)) # 需在Discord开发者后台开启Message Content Intent权限 client = MyClient(intents=discord.Intents.all()) client.run('你的机器人TOKEN')
注意事项
- 若运行时报FFmpeg路径错误,可将
discord.FFmpegPCMAudio(temp_audio_path)修改为discord.FFmpegPCMAudio(temp_audio_path, executable="你的ffmpeg.exe完整路径") - 语音播报默认按消息接收顺序排队,避免多条消息同时播报冲突
内容的提问来源于stack exchange,提问作者Ritul Sherkar
相关产品推荐
相关产品推荐

