Discord.py 1.7.3 向语音频道播放网页音乐的最简单合规方法是什么?
Discord.py 1.7.3 语音频道播放网页音乐最简实现方案
第一步:环境依赖配置
先解决语音组件依赖和网页音乐播放需要的额外工具:
- 安装discord.py官方语音支持库和网页音频流解析工具,执行命令:
pip install pynacl yt-dlp - 安装FFmpeg音频转码工具:Windows系统可下载便携版将
ffmpeg.exe放到项目根目录,Linux/macOS可通过对应包管理器直接全局安装,这是实时转码音频流的必须依赖。
第二步:功能代码实现
基于你现有的初始化代码,只需添加以下命令即可实现完整播放功能,无需修改discord.py内核代码,完全基于官方原生API实现:
import discord from discord.ext import commands import yt_dlp # 1.7.3版本需要开启语音状态意图才能正常识别用户语音频道状态 intents = discord.Intents.default() intents.voice_states = True # 你的原有初始化代码,仅补充intents参数即可 client = commands.Bot(command_prefix="!", intents=intents) # yt-dlp配置,仅提取最高音质的音频流,无需下载到本地 ydl_opts = { 'format': 'bestaudio/best', 'quiet': True, 'no_warnings': True, 'default_search': 'auto', 'source_address': '0.0.0.0' } # FFmpeg配置,开启自动重连优化网络波动时的播放稳定性 ffmpeg_opts = { 'options': '-vn', 'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5' } # 加入用户所在语音频道的命令 @client.command(name='join') async def join(ctx): if not ctx.author.voice: await ctx.send("你需要先加入一个语音频道") return channel = ctx.author.voice.channel await channel.connect() await ctx.send(f"已加入语音频道 {channel.name}") # 播放网页音乐的命令,调用格式为!play 音乐链接 @client.command(name='play') async def play(ctx, url): if not ctx.voice_client: await ctx.invoke(join) # 在线解析音频流地址 with yt_dlp.YoutubeDL(ydl_opts) as ydl: info = ydl.extract_info(url, download=False) audio_url = info['url'] # 直接推送音频流到语音频道 ctx.voice_client.stop() ctx.voice_client.play(discord.FFmpegPCMAudio(audio_url, **ffmpeg_opts)) await ctx.send(f"正在播放:{info['title']}") # 离开语音频道的命令 @client.command(name='leave') async def leave(ctx): if ctx.voice_client: await ctx.voice_client.disconnect() await ctx.send("已离开语音频道") # 替换为你的机器人Token即可启动 client.run("你的机器人Token")
注意事项
- 需要提前在Discord开发者门户中给机器人开启语音相关权限
- 该实现支持绝大多数主流音乐/视频站点的音频解析,部分有特殊防盗链限制的站点需要额外适配yt-dlp规则
- 如果播放时出现卡顿,可自行调整FFmpeg的缓存参数优化播放体验
内容的提问来源于stack exchange,提问作者Eric
相关产品推荐
相关产品推荐

