Discord.py 音乐机器人已加入语音频道但无法播放音乐问题求助
Discord.py 音乐机器人播放故障修正方案
代码存在的核心问题
- 缩进错误导致命令注册失败:原代码中
@client.command装饰器下方的async def join(ctx)存在多余缩进,会直接触发Python缩进语法错误,导致join命令根本无法正常注册,看似机器人能进频道,大多是其他零散逻辑误触发的连接,并非join命令正常生效 - 播放流程无前置校验:执行play命令时,既没有校验机器人是否已经成功接入语音频道(即
server.voice_client是否存在),也没有校验播放队列是否为空,直接索引queue[0]、调用voice_channel.play(),很容易触发空值报错导致播放流程直接中断 - ffmpeg调用参数缺失:哪怕本地已经安装ffmpeg,没有补充网络流重连参数时,YouTube等流媒体源的音频流很容易连接超时、无声音输出
- 控制命令无异常兜底:pause/resume/stop/leave等命令直接调用voice_client的方法,没有判断机器人是否处于语音连接状态,一旦用户在机器人未入频道时发送指令,会直接抛出空值错误打断运行
- 全局队列作用域混乱:直接使用全局变量存储播放队列,多服务器场景下不同公会的播放任务会互相干扰,且没有实现播放完成后自动续播队列下一首的逻辑,播完第一首就会完全停止
- 基础字符串语法错误:原remove命令的f字符串标记位置错误,
f'Your queue is now{queue}!'把反引号包在了感叹号外侧,实际输出格式和预期不一致,甚至会触发字符串解析异常
修正后的核心实现参考
import asyncio import discord from discord.ext import commands import yt_dlp # 启用必要的机器人权限 intents = discord.Intents.default() intents.message_content = True client = commands.Bot(command_prefix='!', intents=intents) # 按服务器ID隔离存储播放队列,避免多场景串队 queues = {} # yt-dlp 基础配置 ytdl_format_options = { 'format': 'bestaudio/best', 'noplaylist': True, 'nocheckcertificate': True, 'ignoreerrors': False, 'quiet': True, 'no_warnings': True, 'default_search': 'auto', 'source_address': '0.0.0.0' } # 补充ffmpeg重连参数,规避网络流中断问题 ffmpeg_options = { 'options': '-vn', 'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5' } ytdl = yt_dlp.YoutubeDL(ytdl_format_options) # 正确的音频源类实现 class YTDLSource(discord.PCMVolumeTransformer): def __init__(self, source, *, data, volume=0.5): super().__init__(source, volume) self.data = data self.title = data.get('title') @classmethod async def from_url(cls, url, *, loop=None, stream=False): loop = loop or asyncio.get_event_loop() data = await loop.run_in_executor( None, lambda: ytdl.extract_info(url, download=not stream) ) if 'entries' in data: data = data['entries'][0] filename = data['url'] if stream else ytdl.prepare_filename(data) return cls(discord.FFmpegPCMAudio(filename, **ffmpeg_options), data=data) @client.command(name='join', help='让机器人加入你所在的语音频道') async def join(ctx): if not ctx.message.author.voice: await ctx.send("你当前没有连接到任何语音频道") return channel = ctx.message.author.voice.channel # 处理机器人已经在其他频道的场景 if ctx.voice_client: await ctx.voice_client.move_to(channel) else: await channel.connect() @client.command(name='remove', help='从播放队列中移除指定位置的条目') async def remove(ctx, number: int): guild_id = ctx.guild.id try: del queues[guild_id][number] await ctx.send(f'当前播放队列: `{queues[guild_id]}`') except (KeyError, IndexError): await ctx.send('当前队列为空,或者输入的位置索引超出范围') @client.command(name='play', help='播放指定链接/队列中的音乐') async def play(ctx, url=None): # 校验机器人连接状态 if not ctx.voice_client: await ctx.send("机器人还未接入语音频道,请先发送join命令") return guild_id = ctx.guild.id # 初始化当前服务器的队列 if guild_id not in queues: queues[guild_id] = [] # 传入链接则直接加入队列 if url: queues[guild_id].append(url) # 校验队列是否为空 if not queues[guild_id]: await ctx.send("当前播放队列为空,请先添加要播放的歌曲链接") return # 处理正在播放的场景 if ctx.voice_client.is_playing(): await ctx.send("机器人正在播放中,已将新歌曲加入队列") return async with ctx.typing(): play_url = queues[guild_id].pop(0) player = await YTDLSource.from_url(play_url, loop=client.loop, stream=True) # 播放完成自动触发下一首的回调 def after_play(error): if error: print(f"播放错误: {error}") asyncio.run_coroutine_threadsafe(play(ctx), client.loop) ctx.voice_client.play(player, after=after_play) await ctx.send(f"**正在播放:** {player.title}") @client.command(name='pause', help='暂停当前播放') async def pause(ctx): if not ctx.voice_client or not ctx.voice_client.is_playing(): await ctx.send("当前没有正在播放的内容") return ctx.voice_client.pause() @client.command(name='resume', help='恢复已暂停的播放') async def resume(ctx): if not ctx.voice_client or not ctx.voice_client.is_paused(): await ctx.send("当前没有处于暂停状态的播放内容") return ctx.voice_client.resume() @client.command(name='stop', help='停止播放并清空当前服务器队列') async def stop(ctx): if not ctx.voice_client: await ctx.send("机器人未连接到语音频道") return ctx.voice_client.stop() guild_id = ctx.guild.id if guild_id in queues: queues[guild_id].clear() @client.command(name='leave', help='让机器人离开当前语音频道') async def leave(ctx): if not ctx.voice_client: await ctx.send("机器人未连接到语音频道") return await ctx.voice_client.disconnect()
注意:如果你本地安装的ffmpeg没有加入系统环境变量,需要在
ffmpeg_options字典中增加executable= "你的ffmpeg可执行文件绝对路径"配置,否则就算安装了ffmpeg也无法正常触发音频解码流程。
内容的提问来源于stack exchange,提问作者Yash
相关产品推荐
相关产品推荐

