如何开发类似Rythm的Discord音乐机器人 加入语音频道自动播放待机音乐
Discord音乐机器人自动播放待机音乐实现方案
可以直接在你现有代码基础上做少量修改完成需求,具体改动如下:
- 抽取通用音频播放方法:将原有play命令里的音频解析、加载逻辑封装为独立内部方法,避免join和play命令重复写相同逻辑
- 在join命令末尾新增自动播放逻辑:机器人完成语音频道加入/移动操作后,直接调用通用播放方法加载你预设的待机音乐
- 修复原有代码问题:修正play命令里的频道归属判断错误,将阻塞式的time.sleep替换为异步休眠,避免机器人事件循环被卡住
修改后的完整代码如下:
import discord from discord.ext import commands import youtube_dl import random import asyncio from quotes import * # 预设待机音乐链接,你已配置的LBP舱室音乐 standby = "https://www.youtube.com/watch?v=5T4wrSDaQvY" class music(commands.Cog): def __init__(self, client): self.client = client # 播放器通用配置 self.FFMPEG_OPTIONS = {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn'} self.YDL_OPTIONS = {'format':"bestaudio"} # 抽离的通用播放方法,供join和play命令调用 async def _play_audio(self, vc, url): vc.stop() with youtube_dl.YoutubeDL(self.YDL_OPTIONS) as ydl: info = ydl.extract_info(url, download=False) audio_url = info['formats'][0]['url'] source = await discord.FFmpegOpusAudio.from_probe(audio_url, **self.FFMPEG_OPTIONS) vc.play(source) @commands.command() async def join(self,ctx): if ctx.author.voice is None: await ctx.send(random.choice(notinvc)) return voice_channel = ctx.author.voice.channel if ctx.voice_client is None: vc = await voice_channel.connect() else: await ctx.voice_client.move_to(voice_channel) vc = ctx.voice_client # 加入完成后自动播放待机音乐 await self._play_audio(vc, standby) @commands.command() async def disconnect(self,ctx): if ctx.voice_client: await ctx.voice_client.disconnect() @commands.command() async def leave(self,ctx): if ctx.voice_client: await ctx.voice_client.disconnect() @commands.command() async def play(self,ctx,url): if ctx.author.voice is None: await ctx.send(random.choice(notinvc)) return # 未加入频道时先自动加入 if ctx.voice_client is None: voice_channel = ctx.author.voice.channel vc = await voice_channel.connect() else: # 修正原有频道判断逻辑 if ctx.voice_client.channel != ctx.author.voice.channel: voice_channel = ctx.author.voice.channel await asyncio.sleep(1) await ctx.voice_client.move_to(voice_channel) await ctx.send("已切换到你所在的语音频道") vc = ctx.voice_client # 调用通用播放方法加载用户指定的新歌曲,会自动停止当前待机音乐 await self._play_audio(vc, url)
功能验证逻辑:
- 发送
.join命令:机器人加入你所在的语音频道后会立刻播放预设的待机音乐 - 发送
.play 其他Youtube链接:机器人会自动停止当前播放的待机音乐,切换为你指定的新歌曲 - 原有断开连接等命令逻辑保持不变
内容的提问来源于stack exchange,提问作者arandomjordan
相关产品推荐
相关产品推荐

