需要帮助制作不和谐的音乐机器人

时间:2020-09-30 14:34:05

标签: python discord.py

我正在制作一个音乐机器人,并且在某些方面很挣扎。我不知道当当前曲目结束后如何制作跳过部分或播放队列中的下一首歌曲。有什么帮助吗? 这是所有代码(所有这些都是为了以防万一)

队列部分位于底部附近,跳过部分也位于底部附近,并且正在此处播放歌曲。

import os
import re
import urllib.request
import youtube_dl
import shutil
import discord

from discord.ext import commands
from discord.utils import get

bot = commands.Bot(command_prefix='g.')
token = '<mytoken>'

@bot.command(pass_context=True)
async def play(ctx, *args: str):
    search = '+'.join(args)
    print(search)
    if search == " ":
        await ctx.send("Uso: g.play (Video)")
        return
    else:
        html = urllib.request.urlopen("https://www.youtube.com/results?search_query=" + search)
        video_ids = re.findall(r"watch\?v=(\S{11})", html.read().decode())
        url = "https://www.youtube.com/watch?v=" + video_ids[0]
        print(url)

        def check_queue():
            Queue_infile = os.path.isdir("./Queue")
            if Queue_infile is True:
                DIR = os.path.abspath(os.path.realpath("Queue"))
                length = len(os.listdir(DIR))
                still_q = length - 1
                try:
                    first_file = os.listdir(DIR)[0]
                except:
                    print("No more queued song(s)\n")
                    queues.clear()
                    return
                main_location = os.path.dirname(os.path.realpath(__file__))
                song_path = os.path.abspath(os.path.realpath("Queue") + "\\" + first_file)
                if length != 0:
                    print("Song done, playing next queued\n")
                    print(f"Songs still in queue: {still_q}")
                    song_there = os.path.isfile("song.mp3")
                    if song_there:
                        os.remove("song.mp3")
                    shutil.move(song_path, main_location)
                    for file in os.listdir("./"):
                        if file.endswith(".mp3"):
                            os.rename(file, 'song.mp3')
                            enfile = file

                    voice.play(discord.FFmpegPCMAudio("song.mp3"), after=lambda e: check_queue())
                    voice.source = discord.PCMVolumeTransformer(voice.source)
                    voice.source.volume = 0.07
                    print(f"Playing {nname[0]}")

                else:
                    queues.clear()
                    return
            else:
                queues.clear()
                print("No songs were queued before the ending of the last song\n")

        song_there = os.path.isfile("song.mp3")
        try:
            if song_there:
                os.remove("song.mp3")
                queues.clear()
                print("Removed old song file")
        except PermissionError:
            print("Trying to delete song file, but it's being played.")
            print("ERROR: Music Playing")
            await ctx.send("Error: Ya estoy poniendo musica! Usa g.queue (cancion) para agregar una cancion a la lista.")
            search = ' '.join(args)
            channel = ctx.message.channel
            return

    Queue_infile = os.path.isdir("./Queue")
    try:
        Queue_folder = "./Queue"
        if Queue_infile is True:
            print("Removed old Queue Folder")
            shutil.rmtree(Queue_folder)
    except:
        print("No old queue folder.")

    print("Getting everytihng ready now.")
    await ctx.send("Preparando cancion...")

    voice = get(bot.voice_clients, guild=ctx.guild)

    ydl_opts = {
        'format': 'bestaudio/best',
        'quiet': True,
        'postprocessors': [{
            'key': 'FFmpegExtractAudio',
            'preferredcodec': 'mp3',
            'preferredquality': '192',

        }],
    }

    with youtube_dl.YoutubeDL(ydl_opts) as ydl:
        print("Downloading audio now\n")
        ydl.download([url])

    for file in os.listdir("./"):
        if file.endswith(".mp3"):
            name = file
            print(f"Renamed file: {file}\n")
            os.rename(file, "song.mp3")
            nfile = file

    print(str(voice))
    channel = ctx.message.author.voice.channel

    voice.play(discord.FFmpegPCMAudio("song.mp3"), after=lambda e: check_queue())
    voice.source = discord.PCMVolumeTransformer(voice.source)
    voice.source.volume = 0.3

    nname = name.rsplit("-", 2)
    print(f"Playing {nname[0]}")
    await embed(ctx, url, nfile, video_ids[0])

queues = {}


@bot.command(pass_context=True)
async def queue(ctx, *searchs):
    search = '+'.join(searchs)
    Queue_infile = os.path.isdir("./Queue")
    if Queue_infile is False:
        os.mkdir("Queue")
    DIR = os.path.abspath(os.path.realpath("Queue"))
    q_num = len(os.listdir(DIR))
    q_num += 1
    add_queue = True
    while add_queue:
        if q_num in queues:
            q_num += 1
        else:
            add_queue = False
            queues[q_num] = q_num

    queue_path = os.path.abspath(os.path.realpath("Queue") + f"\song{q_num}.%(ext)s")

    ydl_opts = {
        'format': 'bestaudio/best',
        'quiet': True,
        'outtmpl': queue_path,
        'postprocessors': [{
            'key': 'FFmpegExtractAudio',
            'preferredcodec': 'mp3',
            'preferredquality': '192'
        }],
    }
    with youtube_dl.YoutubeDL(ydl_opts) as ydl:
        print("Downloading audio now\n")
        html = urllib.request.urlopen("https://www.youtube.com/results?search_query=" + search)
        video_ids = re.findall(r"watch\?v=(\S{11})", html.read().decode())
        url = "https://www.youtube.com/watch?v=" + video_ids[0]
        print(url)
        ydl.download([url])
    await ctx.send("Añadiendo cancion " + str(q_num) + " a la lista!")

    print("Song added to the queue:" + str(q_num))


@bot.event
async def on_ready():
    print(f"""Bot {bot.user} has connected to discord!""")




bot.run(token)```

1 个答案:

答案 0 :(得分:0)

您可以获得了解其代码不是正确的代码,但可以帮助您。

Music Bot Code

您将了解如何编写这些命令。