[Python] Need help making a discord music bot

Discussão em 'Python' iniciado por Stack, Setembro 1, 2025.

  1. Stack

    Stack Membro Participativo

    I'm making a music bot, and, im struggling with some parts. I don't know how to make the skip part or play the next song in the queue once the current one ends. Any help? Here is all the code (all of it because just in case)

    The queue part is near the bottom, the skip part is also near the bottom and playing the song is right below here.

    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() for file in os.listdir("./")...king-a-discord-music-bot"]Continue reading...

Compartilhe esta Página