Python Discord Очередь для YouTube DL - PullRequest
0 голосов
/ 14 мая 2018
  class BOT(object):

    def __init__(self, client):
        self.client = client

    player = None
    vc = None

    async def play(self, url):
        if self.player is None:
            channel = self.client.get_channel("id")
            self.vc = await self.client.join_voice_channel(channel)
            self.player = await self.vc.create_ytdl_player(url, after=lambda: play_next(client))
            self.player.start()

    def play_next(self):
        asyncio.run_coroutine_threadsafe(play(self.client, nexturl), client.loop)


client = discord.Client(commands_prefix="!")


def run_bot():
    client.run("token")


@client.event
async def on_ready():
    print('Logged in as')
    print(client.user.name)
    print(client.user.id)
    print('------')

bot = BOT(client)

@client.event
async def on_message(message):
    await bot.play("https://www.youtube.com/watch?v=bpOSxM0rNPM")


run_bot()

Итак, у меня есть этот код, но я не представляю, как это сделать, чтобы я мог поставить следующий URL в очередь, чтобы он воспроизводился один за другим. Я пытался использовать Очередь, но она всегда терпела неудачу!

1 Ответ

0 голосов
/ 28 апреля 2019

Ничего себе, 11 месяцев, и никто не ответил, я думаю, что это действительно просто, вам нужно иметь две очереди asyncio для URL и названий песен, вы можете посмотреть, как я устроил своего бота, чтобы сделать это, это прекрасно работает:

@bot.command(pass_context=True)
async def basta(ctx):
    global bot_voice_status
    await bot.say(":pause_button: OK, i'm leaving the voice channel, ciao")
    player.stop()
    await vc.disconnect()
    bot_voice_status = 0

@bot.command(pass_context=True)
async def skip(ctx):
    global player
    if songs_url_queue.qsize != 0:
        player.stop()

@bot.command(pass_context=True)
async def song(ctx, *, content:str):
    server = discord.Server(id="") #put server id
    song_name = ""

    if str(content).find("https://www.youtube.com") == -1:
        song_id= await Get_Song_Id(str(content))
        url = "https://www.youtube.com/watch?v=" + song_id
        if url == None:
         await bot.say("Song not found")
         return
    else:
        url = str(content)

    author = ctx.message.author
    if(author != "St3veB0T"):
        if songs_url_queue.qsize() == 0 and not bot.is_voice_connected(server):
            await songs_url_queue.put(url)
            song_name = await Get_Song_Name(str(content))
            mess = "<:youtube:568148804084170753> **Searching** :mag_right: `"+ str(content) + "`\n:musical_note: **Now playing** `" + song_name + "` :notes: Use !basta for stopping and !skip for next song"  
            await bot.say(mess)
        else:
            await songs_url_queue.put(url)
            song_name = await Get_Song_Name(str(content))
            await songs_names_queue.put(song_name)
            mess = "<:youtube:568148804084170753> **Searching** :mag_right: `"+ str(content) + "`\n:musical_note: **Added** `" + song_name + "` to play next :notes: Use !basta for stopping and !skip for next song"  
            await bot.say(mess)

        voice_channel = author.voice_channel
        global vc
        global bot_voice_status
        bot_voice_status = 1

        if songs_url_queue.qsize() == 1:
            try:
                vc = await bot.join_voice_channel(voice_channel)
            except: 
                bot.say("I'm already in a voice channel")
                return

        global player
        options = "-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 2"
        while songs_url_queue.qsize() != 0:
            if songs_names_queue.qsize() >= 1:
                await bot.say(":musical_note: **Now playing** `" + str(await songs_names_queue.get()) + "` :notes: Use !basta for stopping and !skip for next song")

            try:
               player = await vc.create_ytdl_player(str(await songs_url_queue.get()), before_options=options)
            except:
                await vc.disconnect()
                bot_voice_status = 0
                return

            player.start()
            while not player.is_done():
                await asyncio.sleep(1)

        player.stop()
        await vc.disconnect()
        bot_voice_status = 0

в самой первой части вашего сценария добавьте следующие строки:

songs_url_queue = asyncio.Queue()
songs_names_queue = asyncio.Queue()

и я полагаю, вам не нужна глобальная переменная bot_voice_status, если вы не хотите выполнять какую-либо проверку других функций, чтобы посмотреть, играет ли бот песню. Кстати, если вы хотите, просто установите его в 0, когда бот не играет, и в 1, когда он играет.

bot_voice_status = 0
...