code a full working soundboard discord bot, make it have functionalities like adding sounds and playing them, deleting them etc. make it also stay in the call for a specified amount before leaving. import discord token from .env
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
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:
bash
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:
code
DISCORD_TOKEN=your_discord_token_here
Now, here's the bot code:
python
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:
code
!addsound sound_name
Replace sound_name with the desired name for your sound.
Play a Sound:
Use the command:
code
!playsound sound_name [timeout]
sound_name: The name of the sound you want to play.
timeout(optional): The time in seconds the bot should wait after the sound finishes playing before disconnecting from the voice channel. Default is 60 seconds.
Delete a Sound:
Use the command:
code
!delsound sound_name
Replace sound_name with the name of the sound you want to delete.
List All Sounds:
Use the command:
code
!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:
Adding a sound:
code
!addsound hello
(Attach an audio file when sending this command.)
Playing a sound:
code
!playsound hello 30
(Plays the "hello" sound and disconnects after 30 seconds of inactivity.)