想要自动播放队列中的下一首歌曲

时间:2021-01-04 10:49:32

标签: python discord.py discord.py-rewrite

我有一个不和谐机器人的代码,我想自动播放队列中的下一首歌曲。 这是我的代码:

import discord
from discord.ext import commands
from discord.ext import commands,tasks
from discord.client import VoiceClient
import asyncio
import youtube_dl
import os
from discord.ext.commands.errors import ClientException, CommandInvokeError
from random import choice
client = commands.Bot(command_prefix='-')

youtube_dl.utils.bug_reports_message = lambda: ''

ytdl_format_options = {
    'format': 'bestaudio/best',
    'outtmpl': '%(extractor)s-%(id)s-%(title)s.%(ext)s',
    'restrictfilenames': True,
    'noplaylist': True,
    'nocheckcertificate': True,
    'ignoreerrors': False,
    'logtostderr': False,
    'quiet': True,
    'no_warnings': True,
    'default_search': 'auto',
    'source_address': '0.0.0.0' # bind to ipv4 since ipv6 addresses cause issues sometimes
}

ffmpeg_options = {
    'options': '-vn'
}

ytdl = youtube_dl.YoutubeDL(ytdl_format_options)

dir_name = "C:/Users/Ishan/Desktop/Bots"
test = os.listdir(dir_name)


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')
        self.dictMeta = data.get('duration')
    @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]
            
        # dictMeta = data['duration']
        # print(dictMeta)
        filename = data['url'] if stream else ytdl.prepare_filename(data)
        return cls(discord.FFmpegPCMAudio(filename, **ffmpeg_options), data=data)

token = 'Token'
q = []


@client.command(name="join",help="Bot joins the voice channel music")
async def join(ctx):
    try:
        voiceChannel = discord.utils.get(ctx.guild.voice_channels, name='Music')
        await voiceChannel.connect()
        voice = discord.utils.get(client.voice_clients, guild=ctx.guild)
    except ClientException:
        await ctx.send('Already in Voice Channel')


@client.command(name="play",help="Plays a song from queue")
async def play(ctx):
    voice = discord.utils.get(client.voice_clients, guild=ctx.guild)

    global q

    if len(q) >=1:
        if voice != None:
            try:
                async with ctx.typing():
                    player = await YTDLSource.from_url(q[0],loop=client.loop)
                    voice.play(player,after=lambda e: print('Player error: %s' % e) if e else None)
                    del q[0]

                await ctx.send(f"**Now Playing** {player.title}")
            except ClientException:
                await ctx.send("Wait for the current playing music to end or use the 'stop' command")
            except CommandInvokeError:
                await ctx.send("Video not found")
        else:
            await ctx.send("Please connect Bot to Voice Channel First using -join")

    else:
        await ctx.send("Please add a song using '-queue' command")


@client.command(name="leave",help="The Bots leaves the voice channel")
async def leave(ctx):
    voice = discord.utils.get(client.voice_clients, guild=ctx.guild)
    if voice.is_connected():
        await voice.disconnect()
    else:
        await ctx.send("The Bot is Not connected to a voice channel")

@client.command(name="pause",help="Pauses the playing song")
async def pause(ctx):
    voice = discord.utils.get(client.voice_clients, guild=ctx.guild)

    if voice.is_playing():
        voice.pause()
    else:
        await ctx.send('No Audio Playing')

@client.command(name="resume",help="Resumes the paused song")
async def resume(ctx):
    voice = discord.utils.get(client.voice_clients, guild=ctx.guild)
    if voice.is_paused():
        voice.resume()
    else:
        await ctx.send('The Audio is Not Paused')

@client.command(name="stop",help="Stops the playing song")
async def stop(ctx):
    voice = discord.utils.get(client.voice_clients, guild=ctx.guild)
    voice.stop()

@client.command(name="queue",help="Adds a song to Queue")
async def queue(ctx,url,*args):
    global q
    a = '_'.join(args)
    c = url+'_'+a
    x = ' '.join(args)
    y= url + ' '+ x
    q.append(c)
    await ctx.send(f"Added To Queue :**{y}**")

@client.command(help="Removes a song from queue")
async def remove(ctx,number):
    global q
    try:
        del(q[int(number)])
        await ctx.send(f'Your queue is now {q}')

    except:
        await ctx.send(f"Your queue is empty")

@client.command(help="view the songs in queue")
async def view(ctx):
    await ctx.send(f'Your queue is : ')
    for i in q:
        x = i.replace('_'," ")
        await ctx.send(f'``{x}``')




client.run(token)

这里我首先使用队列命令创建一个包含歌曲名称的列表,然后播放命令播放列表中的第一首歌曲,但我不知道如何循环这个过程。 请告诉我如何自动播放下一首歌曲。

在上面的代码中,如果歌曲已结束播放队列中的下一首歌曲,我们必须再次输入“-play”。

0 个答案:

没有答案