Добавление функционала асинхронной очереди в дискорд бота
Всех приветствую
Что делаю: простого музыкального бота, который должен уметь стримить с ютуба аудио
В чем проблема: не понимаю, как добавить функционал очереди в код. (как сделать отдельную асинхронную функцию, которая будет просматривать статус проигрывателя и на его основе переключать музло)
Пример проблемы: включаю одну песню, пока она играет, я не могу ничего сделать с другими песнями, которые хочу включить(добавить их куда то, что бы бот продолжил воспроизведение песен, которые я добавлю).
Код:
import discord
from discord.ext import commands
from config import settings
from discord import FFmpegPCMAudio
import youtube_dl
import os
import Paparser as parser
import asyncio
bot = commands.Bot(command_prefix = settings['prefix'])
queue = []
@bot.event
async def on_ready():
print("bruh")
ffmpeg_options = {
'options': '-vn'
}
ytdl_opts = {
'format': 'bestaudio/best',
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '192',
}],
}
ytdl = youtube_dl.YoutubeDL(ytdl_opts)
class YTDLSource(discord.PCMVolumeTransformer):
def __init__(self, source, *, data, volume=0.5):
super().__init__(source, volume)
self.data = data
self.title = data.get('title')
self.url = data.get('url')
@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:
# take first item from a playlist
data = data['entries'][0]
filename = data['url'] if stream else ytdl.prepare_filename(data)
return cls(discord.FFmpegPCMAudio(filename, **ffmpeg_options), data=data)
@bot.command()
async def join(ctx):
vc = ctx.voice_client
channel = ctx.message.author.voice.channel
voice = discord.utils.get(ctx.guild.voice_channels, name=channel.name)
if vc == None:
await voice.connect()
@bot.command()
async def play(ctx, *url: str):
url = " ".join(url)
print(url)
if (not (url.startswith("https://you")) and not (url.startswith("https://www.you"))):
url = parser.music(url)
channel = ctx.message.author.voice.channel
voice = discord.utils.get(ctx.guild.voice_channels, name=channel.name)
vc = ctx.voice_client
if vc == None:
await voice.connect()
else:
await vc.move_to(channel)
if vc.is_playing():
queue.append(url)
await ctx.send("Added to queue")
return
async with ctx.typing():
player = await YTDLSource.from_url(url, loop=bot.loop, stream=True)
try:
ctx.voice_client.play(player, after=lambda e: print(f'Player error: {e}') if e else None)
except:
await ctx.send("doesnt work")
return
await ctx.send(f'Now playing: {player.title}')
async def checkQueue(ctx):
vc = discord.VoiceClient
while vc.is_playing():
pass
song = queue.pop(0)
play(song)
asyncio.get_event_loop().run_until_complete(checkQueue())
@bot.command()
async def leave(ctx):
vc = ctx.voice_client
if not vc:
await ctx.send("I am not in a voice channel.")
return
await vc.disconnect()
await ctx.send("I have left the voice channel!")
@bot.command()
async def pause(ctx):
vc = ctx.voice_client
if vc.is_playing():
vc.pause()
else:
await ctx.send("Nothing is playing")
@bot.command()
async def resume(ctx):
vc = ctx.voice_client
if vc.is_paused():
vc.resume()
else:
await ctx.send("audio is not paused")
@bot.command()
async def stop(ctx):
vc=ctx.voice_client
vc.stop()
bot.run(settings['token'])
В коде еще достаточно мусорного кода, который я попозже почищу