python - 如何为自定义 Discord Bot 添加/创建队列 - Python
问题描述
我是编码新手,目前正在学习如何创建自定义 Discord 音乐机器人。我开始了可以将机器人添加到服务器并让它播放来自 youtube 的歌曲的部分。但是,我还想实现一个队列,这样每当一首歌曲结束时,下一首歌曲就会自动播放,但无济于事。我很想听听有人提出任何可以指导我在代码中实现队列的建议。
import discord
from discord.ext import commands
import youtube_dl
from discord import FFmpegPCMAudio
import random
class music(commands.Cog):
def __init__(self, client):
self.client = client
# adding a "join" command:
@commands.command()
async def join(self,ctx):
if ctx.author.voice is None:
await ctx.send("You're not in a voice channel!")
voice_channel = ctx.author.voice.channel
if ctx.voice_client is None:
# random audio array:
audio_file = ['1.wav','2.wav','3.wav','4.wav','5.wav','6.wav','7.wav','8.wav','8.wav','9.wav','9.wav','10.wav','11.wav']
randomized = random.SystemRandom()
item = randomized.choice(audio_file)
print(item)
voice = await voice_channel.connect()
# making the bot say something upon entering:
source = FFmpegPCMAudio(f'{item}')
voice.play(source)
else:
await ctx.voice_client.move_to(voice_channel)
# adding a "disconnect" command:
@commands.command()
async def d(self,ctx):
await ctx.voice_client.disconnect()
# playing new song if new song is added:
@commands.command()
async def play(self,ctx,url):
ctx.voice_client.stop()
# ffmpeg handles the steaming on discord official api:
FFMPEG_OPTIONS = {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn'}
# YDL options for audio format:
YDL_OPTIONS = {'format': 'bestaudio'}
vc = ctx.voice_client
# streaming the audio:
with youtube_dl.YoutubeDL(YDL_OPTIONS) as ydl:
info = ydl.extract_info(url, download=False)
url2 = info['formats'][0]['url']
source = await discord.FFmpegOpusAudio.from_probe(url2, **FFMPEG_OPTIONS)
vc.play(source)
await ctx.channel.send('**Now playing** - ' + info.get('title'))
# adding pause button:
@commands.command()
async def pause(self,ctx):
await ctx.voice_client.pause()
await ctx.send("Paused ⏸")
# adding resume button:
@commands.command()
async def resume(self,ctx):
await ctx.voice_client.resume()
await ctx.send("Resume ▶")
def setup(client):
client.add_cog(music(client))
解决方案
推荐阅读
- python-3.x - 错误“AttributeError:‘NoneType’对象没有属性‘文本’”
- sql - 使用 SQL 查询从 mongodb 获取以前的日期记录
- python - 两个名称相同但值不同的键
- c# - 输入时自动突出显示所有文本框控件中的文本(获得焦点)
- python - 如何使用python从庞大的数据集中删除重复值
- regex - 正则表达式搜索 2 个词
- r - “截断”数字在R中快速位于一个范围内
- ansible - 如何使用 Ansible dig 获取 DNS A 记录的域区域
- java - 如何使用数据提供者中的字符串列表运行测试 - Testng
- laravel - Laravel 急切加载特定列错误