make a cool embed fo rlist sounds, also make a queue system for the soundboard (also in a embed)
and for the add sound command oyu need to make it, that it has a file upload thing to upload the sound.
Code:
import discord
from discord.ext import commands
import os
from dotenv import load_dotenv
import asyncio
@bot.event
async def on_ready():
print(f'{bot.user.name} has connected to Discord!')
try:
synced = await bot.tree.sync()
print(f'Synced {len(synced)} commands.')
except Exception as e:
print(f'Error syncing commands: {e}')
Add a sound command
@bot.tree.command(name='addsound', description='Add a new sound to the soundboard')
async def addsound(interaction: discord.Interaction, name: str):
if len(interaction.message.attachments) == 0:
await interaction.response.send_message('Please attach a sound file.', ephemeral=True)
return
@bot.tree.command(name='playsound', description='Play a sound from the soundboard')
async def playsound(interaction: discord.Interaction, name: str, timeout: int = 60):
global disconnect_tasks
if not interaction.user.voice or not interaction.user.voice.channel:
await interaction.response.send_message('You are not connected to a voice channel.', ephemeral=True)
return
code
Assistant
voice_channel = interaction.user.voice.channel
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 interaction.response.send_message('Sound not found.', ephemeral=True)
return
vc = interaction.guild.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 interaction.guild.id in disconnect_tasks:
disconnect_tasks[interaction.guild.id].cancel()
vc.play(discord.FFmpegPCMAudio(sound_path))
# Start a new disconnect task
disconnect_tasks[interaction.guild.id] = bot.loop.create_task(
disconnect_after_timeout(vc, interaction.guild.id, timeout)
)
await interaction.response.send_message(f'Playing "{name}".')
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
Delete a sound command
@bot.tree.command(name='delsound', description='Delete a sound from the soundboard')
async def delsound(interaction: discord.Interaction, name: str):
filepath = os.path.join(sounds_dir, name)
code
# 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 interaction.response.send_message('Sound not found.', ephemeral=True)
return
os.remove(sound_path)
await interaction.response.send_message(f'Sound "{name}" deleted.')
List sounds command
@bot.tree.command(name='listsounds', description='List all available sounds')
async def listsounds(interaction: discord.Interaction):
files = os.listdir(sounds_dir)
if not files:
await interaction.response.send_message('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 interaction.response.send_message(f'Available sounds: {sound_list}')
Run the bot
bot.run(TOKEN)
Certainly! Based on your requirements, I've updated your Discord bot code to:
Create a cool embed for the listsounds command to display available sounds.
Implement a queue system for the soundboard, displaying the queue in an embed.
Modify the addsound command to accept file uploads for adding new sounds.
Here is the updated 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
# Initialize the bot with a command tree (for application commands)
bot = commands.Bot(command_prefix='!', intents=intents)
disconnect_tasks = {} # Keep track of disconnect tasks for each guild
queues = {} # Dictionary mapping guild IDs to sound queues
# Create a 'sounds' directory if it doesn't exist
sounds_dir = 'sounds'
os.makedirs(sounds_dir, exist_ok=True)
# Event when the bot is ready
@bot.event
async def on_ready():
print(f'{bot.user.name} has connected to Discord!')
try:
synced = await bot.tree.sync()
print(f'Synced {len(synced)} commands.')
except Exception as e:
print(f'Error syncing commands: {e}')
# Add a sound command
@bot.tree.command(name='addsound', description='Add a new sound to the soundboard')
async def addsound(interaction: discord.Interaction, name: str, file: discord.Attachment):
valid_extensions = ['.mp3', '.wav', '.ogg', '.aac', '.m4a']
if not any(file.filename.endswith(ext) for ext in valid_extensions):
await interaction.response.send_message('Invalid file type. Please upload an audio file.', ephemeral=True)
return
# Save the file
filename = name + os.path.splitext(file.filename)[1] # Keep the file extension
filepath = os.path.join(sounds_dir, filename)
await file.save(filepath)
await interaction.response.send_message(f'Sound "{name}" added.', ephemeral=True)
# Play a sound command
@bot.tree.command(name='playsound', description='Play a sound from the soundboard')
async def playsound(interaction: discord.Interaction, name: str, timeout: int = 60):
if not interaction.user.voice or not interaction.user.voice.channel:
await interaction.response.send_message('You are not connected to a voice channel.', ephemeral=True)
return
voice_channel = interaction.user.voice.channel
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 interaction.response.send_message('Sound not found.', ephemeral=True)
return
vc = interaction.guild.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)
guild_id = interaction.guild.id
# Cancel any previous disconnect task
if guild_id in disconnect_tasks:
disconnect_tasks[guild_id].cancel()
disconnect_tasks.pop(guild_id, None)
# Initialize the queue if it doesn't exist
if guild_id not in queues:
queues[guild_id] = []
# Add the sound to the queue
queues[guild_id].append(sound_path)
# If bot is not playing, start playing the next sound
if not vc.is_playing():
await play_next_in_queue(vc, guild_id, timeout)
else:
pass # Bot will play the sound after the current sound finishes
# Create an embed of the current queue
queue_display = [os.path.basename(path) for path in queues[guild_id]]
queue_embed = discord.Embed(title='Sound Queue', description='\n'.join(queue_display), color=discord.Color.green())
await interaction.response.send_message(f'Added "{name}" to the queue.', embed=queue_embed)
async def play_next_in_queue(vc, guild_id, timeout):
if queues[guild_id]:
sound_path = queues[guild_id][0] # Peek at the first item
vc.play(discord.FFmpegPCMAudio(sound_path), after=lambda e: bot.loop.create_task(after_playing(vc, guild_id, timeout)))
else:
# Queue is empty
disconnect_tasks[guild_id] = bot.loop.create_task(disconnect_after_timeout(vc, guild_id, timeout))
async def after_playing(vc, guild_id, timeout):
# Remove the sound that just finished playing
if queues[guild_id]:
queues[guild_id].pop(0)
if queues[guild_id]:
await play_next_in_queue(vc, guild_id, timeout)
else:
# Queue is empty, start disconnect timer
disconnect_tasks[guild_id] = bot.loop.create_task(disconnect_after_timeout(vc, guild_id, timeout))
async def disconnect_after_timeout(vc, guild_id, timeout=60):
try:
# Wait for the specified timeout before disconnecting
await asyncio.sleep(timeout)
await vc.disconnect()
# Remove the task and queue from the dictionaries
disconnect_tasks.pop(guild_id, None)
queues.pop(guild_id, None)
except asyncio.CancelledError:
# Task was canceled because a new sound was played
pass
# Delete a sound command
@bot.tree.command(name='delsound', description='Delete a sound from the soundboard')
async def delsound(interaction: discord.Interaction, name: str):
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 interaction.response.send_message('Sound not found.', ephemeral=True)
return
os.remove(sound_path)
await interaction.response.send_message(f'Sound "{name}" deleted.')
# List sounds command
@bot.tree.command(name='listsounds', description='List all available sounds')
async def listsounds(interaction: discord.Interaction):
files = os.listdir(sounds_dir)
if not files:
await interaction.response.send_message('No sounds have been added yet.')
return
sound_names = [os.path.splitext(f)[0] for f in files]
unique_sounds = sorted(set(sound_names))
sound_list = '\n'.join(unique_sounds)
embed = discord.Embed(title='Available Sounds', description=sound_list, color=discord.Color.blue())
await interaction.response.send_message(embed=embed)
# Run the bot
bot.run(TOKEN)
Explanation of Changes:
addsound Command:
Modified to accept a file parameter of type discord.Attachment.
Checks for valid audio file extensions before saving.
Saves the uploaded file to the sounds directory.
Sends a confirmation message upon successful addition.
Queue System Implementation:
Introduced a queues dictionary to maintain a queue for each guild.
Modified the playsound command to add sounds to the queue instead of playing immediately.
Created play_next_in_queue, after_playing, and updated disconnect_after_timeout functions to manage playback and disconnect logic.
The queue is displayed using an embed when a new sound is added.
listsounds Command:
Updated to display available sounds in a visually appealing embed.
The embed lists all unique sound names added to the soundboard.
Embeds:
Used embeds in the listsounds and playsound commands to provide a better visual representation of information.
Note: This code assumes you're using discord.py version 2.x, which supports slash commands and the discord.Attachment type for file uploads in application commands.
Additional Suggestions:
Error Handling: You might want to add more error checking (e.g., file size limits, duplicate sound names).
Permissions: Consider adding permission checks so that only authorized users can add or delete sounds.
Commands for Queue Management: Implement additional commands like skip, clearqueue, or pause to enhance user control over the queue.
Feel free to customize the embeds and add any additional features to suit your needs!