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

使用discord.py开发Discord机器人时调用VoiceClient.play()报错:缺少必填参数'source'求助

使用discord.py开发Discord机器人时调用VoiceClient.play()报错:缺少必填参数'source'求助

嘿,我一眼就发现问题出在哪啦!你直接用VoiceClient这个类去调用play()方法,但play()是个实例方法——它需要通过已经连接到语音频道的VoiceClient实例来调用,而不是类本身,这就是为什么明明传了source却还报“缺少必填参数”的错误。

给你修正后的完整代码,我还补上了必要的前置步骤(比如让机器人先加入用户所在的语音频道):

from discord import Intents, Client, app_commands, Object
from discord.voice_client import VoiceClient
import discord

# 初始化客户端(记得补全你的intents配置)
intents = Intents.default()
intents.message_content = True
client = Client(intents=intents)
tree = app_commands.CommandTree(client)

@tree.command(
    name="play",
    description="insert a youtube url for music",
    guild = Object(id=806555220468432906)
)
async def play_command(interaction: discord.Interaction) -> None:
    # 第一步:检查用户是否在语音频道里
    if not interaction.user.voice:
        await interaction.response.send_message("你得先加入一个语音频道才能让我播放音乐哦!")
        return
    
    # 第二步:获取用户所在的语音频道并连接,得到VoiceClient实例
    voice_channel = interaction.user.voice.channel
    voice_client = await voice_channel.connect()
    
    # 第三步:加载音频源并调用实例的play方法
    source = discord.PCMVolumeTransformer(discord.FFmpegPCMAudio("Music.m4a"))
    voice_client.play(source)
    
    await interaction.response.send_message("音乐开始播放啦!🎵")

# 记得加上客户端启动的代码
client.run("你的机器人令牌")

另外还要提醒你几个关键点:

  • 确保你的机器人在服务器里有连接语音频道和语音发言的权限,不然连不上频道哦
  • 要确认你的运行环境已经安装了FFmpeg,discord.py依赖它来处理音频编码解码
  • 如果之后要做暂停、切换歌曲、断开频道这类操作,记得妥善维护voice_client这个实例的状态,避免重复连接或者内存泄漏

备注:内容来源于stack exchange,提问作者Nick_27

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.14 09:08:01