Discord音乐机器人play命令不存在报错问题求助
问题排查与修复
你遇到的 CommandNotFound: Command "play" is not found 错误主要由以下几个代码问题导致,下面是具体的排查和修复步骤:
1. Cog 类构造函数拼写错误
在 cogs/playcommand.py 中,Cog 类的构造函数被错误地写成了 __int__,正确的应该是 __init__。这个拼写错误会导致 Cog 无法被正确初始化,进而无法注册 play 命令。
修复后的 playcommand.py 构造函数:
class PlayCommand(commands.Cog): def __init__(self, bot): # 修正拼写:__init__ 而非 __int__ self.bot = bot
2. 扩展加载逻辑错误
在 main.py 中,load_extensions 函数存在两个问题:
- 调用
load_extension()时没有传入扩展名称参数 - 该函数从未被执行,导致扩展根本没有被加载
推荐使用 Discord.py 新版推荐的 setup_hook 方法来加载扩展,替代手动定义加载函数。
修复后的 main.py:
import discord from discord.ext import commands TOKEN = 'token here' intents = discord.Intents.all() class MusicBot(commands.Bot): initial_extensions = ['cogs.playcommand'] async def setup_hook(self): # 在 bot 启动前自动加载所有扩展 for extension in self.initial_extensions: await self.load_extension(extension) async def on_ready(self): print('Music online!') async def on_message(self, message): print(f'Message from {message.author}: {message.content}') await self.process_commands(message) client = MusicBot(command_prefix='!', intents=intents) client.run(TOKEN)
3. 额外的潜在问题修复
除了上述核心问题,还有几个小问题可以提前修复,避免后续运行报错:
- 在
play命令中添加songs目录的创建逻辑,防止因目录不存在导致文件操作失败 - 修正拼写错误(如
Donwloading→Downloading、delte→delete等)
修复后的 play 命令片段:
@commands.command(name='play') async def play(self, ctx, url): # 创建 songs 目录(如果不存在) os.makedirs('songs', exist_ok=True) voicec = ctx.author.voice if voicec: channel = voicec.channel if channel: songname = f'songs/{ctx.guild.id}_current.mp3' song_there = os.path.isfile(songname) try: if song_there: os.remove(songname) print('Removed old song file') except PermissionError: print('Trying to delete file, but its being played') await ctx.send('Error: Music playing') return voice = await channel.connect() ydl_opts = { 'format': "bestaudio/best", 'postprocessors': [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', 'preferredquality': '192' }] } with youtube_dl.YoutubeDL(ydl_opts) as ydl: print('Downloading audio now\n') # 修正拼写 ydl.download([url]) # 找到下载的 mp3 文件并重命名 for file in os.listdir('./'): if file.endswith('.mp3'): print(f'Renamed file: {file}\n') os.rename(file, songname) break # 找到第一个 mp3 文件后停止遍历 voice.play(discord.FFmpegPCMAudio(songname), after=lambda e: print('Song ended.')) voice.source = discord.PCMVolumeTransformer(voice.source) print('Ok.')
总结
修复上述问题后,play 命令应该能正常被识别和执行。核心问题是 Cog 构造函数的拼写错误以及扩展未被正确加载,这两个问题都会导致命令无法注册到 Bot 中。
内容的提问来源于stack exchange,提问作者DanRex
相关产品推荐
相关产品推荐

