开发Discord音频播放机器人遭遇CommandNotFound错误求助
Discord机器人自定义命令无法响应的问题解决
问题重现
开发音频播放Discord机器人时,执行自定义命令(如join)触发错误:
discord.ext.commands.errors.CommandNotFound: Command "join" is not found
所有自定义命令均无响应。
核心原因与修复步骤
1. 启用Message Content Intent(discord.py v2.0+强制要求)
discord.py从v2.0版本开始,必须明确启用message_content意图才能读取用户发送的命令消息,否则机器人无法识别命令:
- 登录Discord开发者门户,找到你的机器人应用,进入"Bot"页面;
- 在"Privileged Gateway Intents"区域,开启"Message Content Intent";
- 代码中已使用
intents = discord.Intents.all(),会包含所有意图,但必须确保门户中的开关已打开,否则代码不生效。
2. 修正代码拼写错误(影响play命令执行)
music.py中play函数的FNPEG_OPTIONS存在两处错误:
# 错误写法 FNPEG_OPTIONS = {'before_optopms': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay max 5', 'options': '-vn'} # 修正后 FNPEG_OPTIONS = {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn'}
before_optopms改为before_options(拼写错误);reconnect_delay max改为reconnect_delay_max(FFmpeg参数格式错误)。
3. 确认命令触发格式正确
机器人命令前缀为?,触发命令时必须输入前缀+命令名,例如:
?join ?play https://www.youtube.com/watch?v=xxx
直接输入join不会被识别为命令。
4. 优化cog加载逻辑(可选,提升稳定性)
run.py中的cog加载循环可简化为更易读的形式:
# 原代码 for i in range(len(cogs)): cogs[i].setup(client) # 简化后 for cog in cogs: cog.setup(client)
完整修正后的代码片段
music.py(修正play函数)
import discord from discord.ext import commands import youtube_dl class music(commands.Cog): def __init__(self, client): self.client = client @commands.command() async def join(self, ctx): if ctx.author.voice is None: await ctx.send("Et ole puhelussa vitun apina!") voice_channel = ctx.author.voice.channel if ctx.voice_client is None: await voice_channel.connect() else: await ctx.voice_client.move_to(voice_channel) @commands.command() async def disconnect(self,ctx): await ctx.voice_client.disconnect() @commands.command() async def play(self,ctx,url): ctx.voice_client.stop() # 修正拼写错误和FFmpeg参数 FNPEG_OPTIONS = {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn'} YDL_OPTIONS = {'format': "bestaudio"} vc = ctx.voice_client with youtube_dl.YoutubeDL(YDL_OPTIONS) as ydl: info = ydl.extract_info(url, download=False) url2 = info['formats'][0]['url'] source = await discord.FFmpegOpusAudio.from_probe(url2,**FNPEG_OPTIONS) vc.play(source) @commands.command() async def pause(self, ctx): await ctx.voice_client.pause() await ctx.send("MUSIIKKI PYSÄYTETTY") @commands.command() async def resume(self, ctx): await ctx.voice_client.resume() await ctx.send("MUSIIKKI JATKUU") def setup(client): client.add_cog(music(client))
run.py(简化加载循环)
import discord from discord.ext import commands import music cogs = [music] client = commands.Bot(command_prefix="?", intents = discord.Intents.all()) # 简化加载循环 for cog in cogs: cog.setup(client) client.run("你的机器人Token")
内容的提问来源于stack exchange,提问作者Peruna9276
相关产品推荐
相关产品推荐

