Create the bot.py Script
Below is the complete bot.py script with detailed comments explaining each part.
bot.py
import discord
from discord.ext import commands, tasks
import os
from dotenv import load_dotenv
import asyncio
from discord import FFmpegPCMAudio
from discord.utils import get
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
# Intents are required for certain functionalities. Adjust as needed.
intents = discord.Intents.default()
intents.message_content = True
intents.guilds = True
intents.voice_states = True
# Define the command prefix (e.g., '!')
bot = commands.Bot(command_prefix='!', intents=intents)
# Directory to store sound files
SOUND_DIR = "sounds"
# Ensure the sounds directory exists
if not os.path.exists(SOUND_DIR):
os.makedirs(SOUND_DIR)
# Dictionary to keep track of voice disconnect timers per guild
disconnect_tasks = {}
@bot.event
async def on_ready():
print(f'Bot connected as {bot.user}')
# Command to add a sound
@bot.command(name='add')
async def add_sound(ctx, sound_name: str):
"""
Usage: !add sound_name
The user should attach an audio file when using this command.
"""
if not ctx.message.attachments:
await ctx.send("Please attach an audio file to add.")
return
attachment = ctx.message.attachments[0]
if not attachment.filename.lower().endswith(('.mp3', '.wav', '.ogg', '.flac')):
await ctx.send("Unsupported file format. Please upload MP3, WAV, OGG, or FLAC files.")
return
file_path = os.path.join(SOUND_DIR, f"{sound_name}{os.path.splitext(attachment.filename)[1]}")
if os.path.exists(file_path):
await ctx.send(f"A sound with the name `{sound_name}` already exists.")
return
await attachment.save(file_path)
await ctx.send(f"Sound `{sound_name}` has been added successfully.")
# Command to play a sound
@bot.command(name='play')
async def play_sound(ctx, sound_name: str, duration: int = 60):
"""
Usage: !play sound_name [duration_in_seconds]
Duration is optional and defaults to 60 seconds.
The bot will leave the voice channel after the specified duration.
"""
# Check if the user is in a voice channel
if not ctx.author.voice:
await ctx.send("You need to be in a voice channel to use this command.")
return
voice_channel = ctx.author.voice.channel
# Connect to the voice channel if not already connected
voice_client = get(bot.voice_clients, guild=ctx.guild)
if not voice_client:
voice_client = await voice_channel.connect()
# Start a background task to disconnect after duration
if ctx.guild.id in disconnect_tasks:
disconnect_tasks[ctx.guild.id].cancel()
disconnect_tasks[ctx.guild.id] = bot.loop.create_task(disconnect_after(voice_client, duration))
else:
# Move to the user's voice channel if connected elsewhere
if voice_client.channel != voice_channel:
await voice_client.move_to(voice_channel)
# Reset the disconnect timer
if ctx.guild.id in disconnect_tasks:
disconnect_tasks[ctx.guild.id].cancel()
disconnect_tasks[ctx.guild.id] = bot.loop.create_task(disconnect_after(voice_client, duration))
# Locate the sound file
for file in os.listdir(SOUND_DIR):
name, ext = os.path.splitext(file)
if name == sound_name:
file_path = os.path.join(SOUND_DIR, file)
break
else:
await ctx.send(f"Sound `{sound_name}` not found.")
return
# Play the sound
if voice_client.is_playing():
voice_client.stop()
# Ensure FFmpeg is available
ffmpeg_path = 'ffmpeg' # Assuming FFmpeg is in PATH
source = FFmpegPCMAudio(file_path, executable=ffmpeg_path)
voice_client.play(source)
await ctx.send(f"Playing sound `{sound_name}` for {duration} seconds.")
# Helper function to disconnect after a certain duration
async def disconnect_after(voice_client, duration):
try:
await asyncio.sleep(duration)
await voice_client.disconnect()
except asyncio.CancelledError:
pass # Task was cancelled because a new play command was issued
# Command to delete a sound
@bot.command(name='delete')
@commands.has_permissions(administrator=True)
async def delete_sound(ctx, sound_name: str):
"""
Usage: !delete sound_name
Only users with administrator permissions can use this command.
"""
# Locate the sound file
for file in os.listdir(SOUND_DIR):
name, ext = os.path.splitext(file)
if name == sound_name:
file_path = os.path.join(SOUND_DIR, file)
break
else:
await ctx.send(f"Sound `{sound_name}` not found.")
return
# Delete the file
os.remove(file_path)
await ctx.send(f"Sound `{sound_name}` has been deleted.")
# Command to list all available sounds
@bot.command(name='list')
async def list_sounds(ctx):
"""
Usage: !list
Lists all available sounds.
"""
sounds = [os.path.splitext(file)[0] for file in os.listdir(SOUND_DIR)]
if sounds:
sound_list = '\n'.join(sounds)
await ctx.send(f"Available sounds:\n{sound_list}")
else:
await ctx.send("No sounds available. Add some using the `!add` command.")
# Error handling for missing permissions
@delete_sound.error
async def delete_sound_error(ctx, error):
if isinstance(error, commands.MissingPermissions):
await ctx.send("You don't have permission to delete sounds.")
else:
await ctx.send("An error occurred while trying to delete the sound.")
# Run the bot
bot.run(TOKEN)