You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Discord.py交互指令实现VC音频播放与退出功能求助

解决Discord交互指令播放音频与退出语音频道问题

问题根源

Interaction对象本身并没有voice_client属性,你得从交互对应的服务器(Guild)里获取语音客户端,也就是用interaction.guild.voice_client来替代错误的调用方式。

完整实现代码示例

先确保已经安装带语音支持的discord.py:pip install discord.py[voice],以下是播放和退出指令的完整实现:

import discord
from discord import app_commands
from discord.ext import commands
from discord import FFmpegPCMAudio

class AudioCommands(commands.Cog):
    def __init__(self, bot: commands.Bot):
        self.bot = bot

    # 播放音频的交互指令
    @app_commands.command(name="play", description="播放指定路径的音频文件")
    async def play_audio(self, interaction: discord.Interaction, audio_file: str):
        # 获取当前服务器的语音客户端
        voice_client = interaction.guild.voice_client
        
        # 检查机器人是否在语音频道里
        if not voice_client:
            await interaction.response.send_message("机器人还没加入任何语音频道!", ephemeral=True)
            return
        
        # 检查用户是否和机器人在同一个频道
        if not interaction.user.voice or interaction.user.voice.channel != voice_client.channel:
            await interaction.response.send_message("你得和机器人在同一个语音频道才能操作!", ephemeral=True)
            return
        
        # 加载并播放音频
        try:
            audio_source = FFmpegPCMAudio(audio_file)
            voice_client.play(audio_source)
            await interaction.response.send_message(f"开始播放:{audio_file}", ephemeral=True)
        except Exception as err:
            await interaction.response.send_message(f"播放失败:{str(err)}", ephemeral=True)

    # 退出语音频道的交互指令
    @app_commands.command(name="leave", description="让机器人退出当前语音频道")
    async def leave_vc(self, interaction: discord.Interaction):
        voice_client = interaction.guild.voice_client
        
        if not voice_client:
            await interaction.response.send_message("机器人没在任何语音频道里!", ephemeral=True)
            return
        
        await voice_client.disconnect()
        await interaction.response.send_message("已退出语音频道", ephemeral=True)

# 把指令组注册到机器人
async def setup(bot: commands.Bot):
    await bot.add_cog(AudioCommands(bot))

关键注意事项

  • 系统必须安装FFmpeg:Windows需要下载FFmpeg并添加到系统环境变量,Linux可以用apt install ffmpeg或对应包管理器安装,否则无法加载音频文件。
  • 音频文件建议用绝对路径,避免相对路径导致找不到文件的问题。
  • 机器人需要在服务器里拥有Connect和Speak权限,否则无法加入频道或播放声音。
  • 如果需要支持多音频排队,自己加一个队列结构管理待播放的音频源即可。

内容的提问来源于stack exchange,提问作者Ori

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 16:20:33