Zanteri - Programs

Programmer, Writer, Whatever Else

Discord Local Music Bot

      

import discord
from discord.ext import commands
import asyncio
import os
import random

#SUBDIRECTORY NAMES
dir1 = ''
dir2 = ''
dir3 = ''
dir4 = ''
#BOTKEY
bot_key = ''


intents = discord.Intents.all()
intents.messages = True

bot = commands.Bot(command_prefix='1', intents=intents)
bot.voice = None

music_files = [17]

music_dir = "Music"  # Replace with actual path

###
###     HELP MESSAGE
###
@bot.command(aliases=['00'])
async def help_me(ctx):
    # Define the help message
    help_message = """
    Here are the available commands:
    100 - Help
    101 - Join a voice channel
    102 - Leave a voice channel

    103 - Play a specific file
    104 - Play the main folder

    105 - dir1 music
    106 - dir2 music
    107 - dir3 music
    108 - dir4 music
    """
    
    # Send the help message as an ephemeral message visible only to the user who issued the command
    await ctx.send(help_message, ephemeral=True)

###
###     JOIN THE VC
###
@bot.command(aliases=['01'])
async def join(ctx):
    # Check if user is in a voice channel
    if not ctx.author.voice:
        await ctx.send("You must be in a voice channel to use this command.")
        return

    # Join the voice channel
    voice_channel = ctx.author.voice.channel
    bot.voice = await voice_channel.connect()
    await ctx.send(f"Joined {voice_channel}")

###
###     LEAVE THE VC
###
@bot.command(aliases=['02'])
async def leave(ctx):
    # Check if bot is connected to a voice channel
    if ctx.voice_client:
        #Stop playing
        if ctx.voice_client.is_playing():
            ctx.voice_client.stop()
            await asyncio.sleep(0.5)  # Wait for audio playback to stop
        # Disconnect from the voice channel
        await ctx.voice_client.disconnect()
        await ctx.send("Left voice channel")
    else:
        await ctx.send("Not connected to a voice channel")

###
###     PLAY A SPECIFIC FILE        (103 [filename])
###
@bot.command(aliases=['03'])
async def play(ctx, song: str):
    # Check if bot is connected to a voice channel
    if not bot.voice:
        await ctx.send("Bot is not connected to a voice channel. Use !join first.")
        return
    
    # Check if bot is already playing audio
    if ctx.voice_client:
        try:
            bot.voice.stop()
        except Exception as e:
            print(f"Error stopping audio: {e}")  # Log the error

    # Validate and access the song file
    song_path = f"{music_dir}/{song}.mp3"  # Assuming .mp3 format
    try:
        audio_source = discord.FFmpegPCMAudio(song_path)
        bot.voice.play(audio_source)
    except FileNotFoundError:
        await ctx.send(f"Song '{song}' not found.")
        return

    # Handle song playback events (optional)
    while bot.voice.is_playing():
        await asyncio.sleep(1)

    await print(f"Now playing: {song}")

###
###     PLAY MAIN FOLDER
###
@bot.command(aliases=['04'])
async def playlist1(ctx):
    # Check if bot is connected to a voice channel
    if not ctx.voice_client:
        await ctx.send("Bot is not connected to a voice channel. Use !join first.")
        return

    # Check if bot is already playing audio
    if ctx.voice_client.is_playing():
        try:
            bot.voice.stop()
        except Exception as e:
            print(f"Error stopping audio: {e}")  # Log the error

    # Validate and access the music files
    try:
        music_files = [f for f in os.listdir(music_dir) if f.endswith('.mp3')]
        random.shuffle(music_files)

        for file in music_files:
            # Create audio source from the file
            file_path = os.path.join(music_dir, file)
            audio_source = discord.FFmpegPCMAudio(file_path)

            # Play the audio in the voice channel
            bot.voice.play(audio_source)
            print(f"Now playing: {file}")
            
            # Wait until the audio is finished playing
            while bot.voice.is_playing():
                await asyncio.sleep(1)
    except FileNotFoundError:
        await ctx.send("No music files found in the directory.")
        return

    #await ctx.send("Playlist finished playing.")

###
###     PLAY DIR1 FOLDER
###
@bot.command(aliases=['05'])
async def playlist2(ctx):
    # Check if bot is connected to a voice channel
    if not ctx.voice_client:
        await ctx.send("Bot is not connected to a voice channel. Use !join first.")
        return
    
    this_music_dir = music_dir + r'\dir1'

    # Check if bot is already playing audio
    if ctx.voice_client.is_playing():
        try:
            bot.voice.stop()
        except Exception as e:
            print(f"Error stopping audio: {e}")  # Log the error

    # Validate and access the music files
    try:
        music_files = [f for f in os.listdir(this_music_dir) if f.endswith('.mp3')]
        random.shuffle(music_files)

        for file in music_files:
            # Create audio source from the file
            file_path = os.path.join(this_music_dir, file)
            audio_source = discord.FFmpegPCMAudio(file_path)

            # Play the audio in the voice channel
            bot.voice.play(audio_source)
            print(f"Now playing: {file}")
            #await ctx.send(music_files)
            #await ctx.send(file_path)
            
            # Wait until the audio is finished playing
            while bot.voice.is_playing():
                await asyncio.sleep(1)
    except FileNotFoundError:
        await ctx.send("No music files found in the directory.")
        return

    await ctx.send("Playlist finished playing.")


###
###     PLAY DIR2 FOLDER
###
@bot.command(aliases=['06'])
async def playlist3(ctx):
    # Check if bot is connected to a voice channel
    if not ctx.voice_client:
        await ctx.send("Bot is not connected to a voice channel. Use !join first.")
        return
    
    this_music_dir = music_dir + r'\dir2'

    # Check if bot is already playing audio
    if ctx.voice_client.is_playing():
        try:
            bot.voice.stop()
        except Exception as e:
            print(f"Error stopping audio: {e}")  # Log the error

    # Validate and access the music files
    try:
        music_files = [f for f in os.listdir(this_music_dir) if f.endswith('.mp3')]
        random.shuffle(music_files)

        for file in music_files:
            # Create audio source from the file
            file_path = os.path.join(this_music_dir, file)
            audio_source = discord.FFmpegPCMAudio(file_path)

            # Play the audio in the voice channel
            bot.voice.play(audio_source)
            print(f"Now playing: {file}")
            #await ctx.send(music_files)
            #await ctx.send(file_path)
            
            # Wait until the audio is finished playing
            while bot.voice.is_playing():
                await asyncio.sleep(1)
    except FileNotFoundError:
        await ctx.send("No music files found in the directory.")
        return

    await ctx.send("Playlist finished playing.")

###
###     PLAY DIR3 FOLDER
###
@bot.command(aliases=['07'])
async def playlist4(ctx):
    # Check if bot is connected to a voice channel
    if not ctx.voice_client:
        await ctx.send("Bot is not connected to a voice channel. Use !join first.")
        return
    
    #if bot.voice.is_playing():
        #await ctx.send("already palying")
    
    this_music_dir = music_dir + r'\dir3'

    if ctx.voice_client.is_playing():
        try:
            bot.voice.stop()
        except Exception as e:
            print(f"Error stopping audio: {e}")  # Log the error
    # Check if bot is already playing audio
    if ctx.voice_client.is_playing():
        #ctx.voice_client.stop()
        await ctx.voice_client.stop()
        await asyncio.sleep(0.5)  # Wait for audio playback to stop

    # Validate and access the music files
    try:
        music_files = [f for f in os.listdir(this_music_dir) if f.endswith('.mp3')]
        random.shuffle(music_files)

        for file in music_files:
            # Create audio source from the file
            file_path = os.path.join(this_music_dir, file)
            audio_source = discord.FFmpegPCMAudio(file_path)

            # Play the audio in the voice channel
            bot.voice.play(audio_source)
            print(f"Now playing: {file}")
            #await ctx.send(music_files)
            #await ctx.send(file_path)
            
            # Wait until the audio is finished playing
            while bot.voice.is_playing():
                await asyncio.sleep(1)
    except FileNotFoundError:
        await ctx.send("No music files found in the directory.")
        return

    await ctx.send("Playlist finished playing.")

###
###     PLAY DIR4 FOLDER
###
@bot.command(aliases=['08'])
async def playlist5(ctx):
    # Check if bot is connected to a voice channel
    if not ctx.voice_client:
        await ctx.send("Bot is not connected to a voice channel. Use !join first.")
        return
    
    #if bot.voice.is_playing():
        #await ctx.send("already palying")
    
    this_music_dir = music_dir + r'\dir4'

    if ctx.voice_client.is_playing():
        try:
            bot.voice.stop()
        except Exception as e:
            print(f"Error stopping audio: {e}")  # Log the error
    # Check if bot is already playing audio
    if ctx.voice_client.is_playing():
        #ctx.voice_client.stop()
        await ctx.voice_client.stop()
        await asyncio.sleep(0.5)  # Wait for audio playback to stop

    # Validate and access the music files
    try:
        music_files = [f for f in os.listdir(this_music_dir) if f.endswith('.mp3')]
        random.shuffle(music_files)

        for file in music_files:
            # Create audio source from the file
            file_path = os.path.join(this_music_dir, file)
            audio_source = discord.FFmpegPCMAudio(file_path)

            # Play the audio in the voice channel
            bot.voice.play(audio_source)
            print(f"Now playing: {file}")
            #await ctx.send(music_files)
            #await ctx.send(file_path)
            
            # Wait until the audio is finished playing
            while bot.voice.is_playing():
                await asyncio.sleep(1)
    except FileNotFoundError:
        await ctx.send("No music files found in the directory.")
        return

    await ctx.send("Playlist finished playing.")



bot.run('boy_key')
        


        
    

Requirements:

  • discord.py
This bot is intended to play local mp3 files through a discord voice channel.

Made by Zanteri

Feel free to email me any comments and feedback at [email protected]