Here's a fully functional Discord bot that acts as a soundboard. It allows users to add, play, delete sounds, and stays in the voice channel for a specified amount of time before leaving. The bot token is imported from a .env file.
First, make sure you have the required packages installed:
pip install discord.py python-dotenv
You'll also need to have FFmpeg installed on your system, as it's required for audio playback.
Create a .env file in the same directory as your script with the following content:
DISCORD_TOKEN=your_discord_token_here
Now, here's the bot code:
import discord
from discord.ext import commands
import os
from dotenv import load_dotenv
import asyncio
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
intents = discord.Intents.default()
intents.message_content = True
intents.voice_states = True # Required for voice channel operations
bot = commands.Bot(command_prefix='!', intents=intents)
disconnect_tasks = {} # Keep track of disconnect tasks for each guild
@bot.event
async def on_ready():
print(f'{bot.user.name} has connected to Discord!')
@bot.command(name='addsound')
async def addsound(ctx, name: str):
"""Adds a new sound to the soundboard."""
if len(ctx.message.attachments) == 0:
await ctx.send('Please attach a sound file.')
return
attachment = ctx.message.attachments[0]
filename = name + os.path.splitext(attachment.filename)[1] # Keep the file extension
sounds_dir = 'sounds'
os.makedirs(sounds_dir, exist_ok=True)
filepath = os.path.join(sounds_dir, filename)
await attachment.save(filepath)
await ctx.send(f'Sound "{name}" added.')
@bot.command(name='playsound')
async def playsound(ctx, name: str, timeout: int = 60):
"""Plays a sound from the soundboard."""
global disconnect_tasks
if not ctx.author.voice:
await ctx.send('You are not connected to a voice channel.')
return
voice_channel = ctx.author.voice.channel
sounds_dir = 'sounds'
filepath = os.path.join(sounds_dir, name)
# Check for the sound file with common audio extensions
sound_path = None
for ext in ['.mp3', '.wav', '.ogg', '.aac', '.m4a']:
if os.path.exists(filepath + ext):
sound_path = filepath + ext
break
if sound_path is None:
await ctx.send('Sound not found.')
return
vc = ctx.voice_client
if not vc or not vc.is_connected():
vc = await voice_channel.connect()
elif vc.channel != voice_channel:
await vc.move_to(voice_channel)
# Cancel any previous disconnect task
if ctx.guild.id in disconnect_tasks:
disconnect_tasks[ctx.guild.id].cancel()
vc.play(discord.FFmpegPCMAudio(sound_path))
# Start a new disconnect task
disconnect_tasks[ctx.guild.id] = bot.loop.create_task(disconnect_after_timeout(vc, ctx.guild.id, timeout))
async def disconnect_after_timeout(vc, guild_id, timeout):
try:
# Wait until the audio is done playing
while vc.is_playing():
await asyncio.sleep(1)
# Wait for the specified timeout before disconnecting
await asyncio.sleep(timeout)
await vc.disconnect()
# Remove the task from the dictionary
disconnect_tasks.pop(guild_id, None)
except asyncio.CancelledError:
# Task was canceled because a new sound was played
pass
@bot.command(name='delsound')
async def delsound(ctx, name: str):
"""Deletes a sound from the soundboard."""
sounds_dir = 'sounds'
filepath = os.path.join(sounds_dir, name)
# Check for the sound file with common audio extensions
sound_path = None
for ext in ['.mp3', '.wav', '.ogg', '.aac', '.m4a']:
if os.path.exists(filepath + ext):
sound_path = filepath + ext
break
if sound_path is None:
await ctx.send('Sound not found.')
return
os.remove(sound_path)
await ctx.send(f'Sound "{name}" deleted.')
@bot.command(name='listsounds')
async def listsounds(ctx):
"""Lists all available sounds."""
sounds_dir = 'sounds'
if not os.path.exists(sounds_dir):
os.makedirs(sounds_dir)
files = os.listdir(sounds_dir)
if not files:
await ctx.send('No sounds have been added yet.')
return
sound_names = [os.path.splitext(f)[0] for f in files]
sound_list = ', '.join(sorted(set(sound_names)))
await ctx.send(f'Available sounds: {sound_list}')
# Run the bot
bot.run(TOKEN)
How to Use the Bot:
-
Add a Sound:
- Upload an audio file (e.g., MP3, WAV) with the command:
!addsound sound_name
Replace sound_name with the desired name for your sound.
-
Play a Sound:
-
Delete a Sound:
- Use the command:
!delsound sound_name
Replace sound_name with the name of the sound you want to delete.
-
List All Sounds:
- Use the command:
!listsounds
Notes:
- The bot will automatically disconnect from the voice channel after the specified timeout if no new sounds are played.
- If a new sound is played before the timeout, the disconnect timer resets.
- Make sure the bot has permission to connect and speak in voice channels.
- Supported audio formats include MP3, WAV, OGG, AAC, and M4A.
Ensure FFmpeg is Installed:
The bot uses FFmpeg for audio playback. Download and install FFmpeg from https://ffmpeg.org/download.html. Make sure FFmpeg is added to your system's PATH environment variable so that it's accessible from the command line.
Example Commands:
Enjoy your soundboard bot!