Discord机器人进入语音频道后无法播放音频 无报错如何解决
修复方案
- 补全语音频道连接校验逻辑
原有代码未对语音连接状态做合法性校验,若ctx.voice_client为空会直接静默失败,需在调用停止逻辑前增加校验: - 修正FFMPEG配置参数错误
原有FFMPEG_OPTIONS中的before_options字段缺少首个参数前缀-,FFmpeg无法识别该配置,同时需添加-vn参数过滤视频流,只保留音频流。 - 替换已停止维护的youtube_dl
youtube_dl已多年未更新,对新的Youtube页面适配存在问题,可直接替换为API完全兼容的yt-dlp:
- 安装命令:
pip install yt-dlp - 代码中替换导入语句:
import yt_dlp as youtube_dl,其余调用逻辑无需修改
- 确认Discord Intents配置
若使用discord.py 2.0及以上版本,需完成两处配置:
- 前往Discord开发者后台,在对应Bot的「Privileged Gateway Intents」设置中开启
Voice States Intent - 代码初始化Bot时启用对应Intent
- 确认FFmpeg环境有效性
执行ffmpeg -version确认FFmpeg已正确加入系统环境变量,若未生效可在创建音频源时手动指定FFmpeg绝对路径。
修改后完整代码
@commands.command() async def play(self, ctx, url): # 校验用户是否在语音频道 if not ctx.author.voice: await ctx.send("请先加入语音频道") return # 机器人未加入频道时自动加入 if not ctx.voice_client: await ctx.author.voice.channel.connect() vc = ctx.voice_client if vc.is_playing(): vc.stop() FFMPEG_OPTIONS = { 'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn' } YDL_OPTIONS = {'format': 'bestaudio/best'} with youtube_dl.YoutubeDL(YDL_OPTIONS) as ydl: info = ydl.extract_info(url, download=False) url2 = info['formats'][0]['url'] # 若FFmpeg未配置环境变量,可添加executable参数指定路径 # source = await discord.FFmpegOpusAudio.from_probe(url2, executable="你的FFmpeg绝对路径", **FFMPEG_OPTIONS) source = await discord.FFmpegOpusAudio.from_probe(url2, **FFMPEG_OPTIONS) vc.play(source)
内容的提问来源于stack exchange,提问作者Ethan Culp
相关产品推荐
相关产品推荐

