Here's a Discord bot that joins voice calls automatically, listens to your voice commands, and performs actions like muting and deafening users:
import discord
import asyncio
import speech_recognition as sr
import io
import wave
import json
import os
from pydub import AudioSegment
from discord.ext import commands
# Bot configuration
with open('config.json', 'r') as f:
config = json.load(f)
TOKEN = config['token']
GUILD_ID = config['guild_id']
VOICE_CHANNEL_ID = config['voice_channel_id']
COMMAND_PREFIX = "!"
# Setup intents
intents = discord.Intents.default()
intents.voice_states = True
intents.message_content = True
intents.members = True
bot = commands.Bot(command_prefix=COMMAND_PREFIX, intents=intents)
class VoiceCommandHandler:
def __init__(self, bot):
self.bot = bot
self.voice_client = None
self.recognizer = sr.Recognizer()
self.is_listening = False
async def join_voice_channel(self):
"""Join the configured voice channel"""
guild = bot.get_guild(GUILD_ID)
voice_channel = guild.get_channel(VOICE_CHANNEL_ID)
if voice_channel:
self.voice_client = await voice_channel.connect()
print(f"Joined voice channel: {voice_channel.name}")
return True
return False
async def start_listening(self):
"""Start listening to voice commands"""
if not self.voice_client:
success = await self.join_voice_channel()
if not success:
return
self.is_listening = True
# Set up audio sink to capture audio
self.voice_client.listen(discord.AudioSink())
print("Now listening for voice commands...")
# Start processing audio
while self.is_listening:
# This is where we would process incoming audio packets
# For demonstration purposes, we'll simulate receiving voice data
try:
# Process audio data (simplified)
await self.process_voice_command()
await asyncio.sleep(1) # Check for commands every second
except Exception as e:
print(f"Error processing voice command: {e}")
async def process_voice_command(self):
"""Process incoming audio to detect commands"""
# In a real implementation, you would:
# 1. Buffer audio data
# 2. Convert it to a format suitable for speech recognition
# 3. Use speech_recognition to detect commands
# For demonstration, we'll simulate detecting commands
# In a real implementation, you would use the audio data from the voice channel
guild = bot.get_guild(GUILD_ID)
# Example of command detection logic
text = await self.simulate_speech_recognition()
if text:
print(f"Detected: {text}")
# Handle mute commands
if "mute" in text.lower():
parts = text.lower().split()
if len(parts) > 1:
username = parts[parts.index("mute") + 1]
await self.mute_user(guild, username)
# Handle deafen commands
elif "deafen" in text.lower():
parts = text.lower().split()
if len(parts) > 1:
username = parts[parts.index("deafen") + 1]
await self.deafen_user(guild, username)
# Handle unmute commands
elif "unmute" in text.lower():
parts = text.lower().split()
if len(parts) > 1:
username = parts[parts.index("unmute") + 1]
await self.unmute_user(guild, username)
# Handle undeafen commands
elif "undeafen" in text.lower():
parts = text.lower().split()
if len(parts) > 1:
username = parts[parts.index("undeafen") + 1]
await self.undeafen_user(guild, username)
async def simulate_speech_recognition(self):
"""Simulate speech recognition (replace with actual implementation)"""
# In a real implementation, you would:
# 1. Get audio data from the Discord voice channel
# 2. Process it with a speech recognition library
return None # Return None to simulate no command detected
async def mute_user(self, guild, username):
"""Mute a user by username"""
member = self.find_member_by_name(guild, username)
if member and member.voice:
await member.edit(mute=True)
print(f"Muted {member.display_name}")
async def unmute_user(self, guild, username):
"""Unmute a user by username"""
member = self.find_member_by_name(guild, username)
if member and member.voice:
await member.edit(mute=False)
print(f"Unmuted {member.display_name}")
async def deafen_user(self, guild, username):
"""Deafen a user by username"""
member = self.find_member_by_name(guild, username)
if member and member.voice:
await member.edit(deafen=True)
print(f"Deafened {member.display_name}")
async def undeafen_user(self, guild, username):
"""Undeafen a user by username"""
member = self.find_member_by_name(guild, username)
if member and member.voice:
await member.edit(deafen=False)
print(f"Undeafened {member.display_name}")
def find_member_by_name(self, guild, name):
"""Find a member by name or nickname"""
for member in guild.members:
if (member.name.lower() == name.lower() or
(member.nick and member.nick.lower() == name.lower())):
return member
return None
# Bot events
@bot.event
async def on_ready():
print(f'Logged in as {bot.user.name}')
# Initialize the voice command handler
handler = VoiceCommandHandler(bot)
# Start listening for voice commands
bot.loop.create_task(handler.start_listening())
# Run the bot
bot.run(TOKEN)
Important Note: This is a simplified version that demonstrates the structure of such a bot. For the bot to fully work, you'd need to implement the actual speech recognition part, which requires more advanced audio processing.
How to use this bot:
- Create a file named
config.json with the following content:
{
"token": "YOUR_BOT_TOKEN",
"guild_id": YOUR_SERVER_ID,
"voice_channel_id": YOUR_VOICE_CHANNEL_ID
}
- Install the required packages:
pip install discord.py SpeechRecognition pydub PyNaCl
- Install system dependencies:
- FFmpeg: needed for audio processing
- PyAudio: required by SpeechRecognition for microphone access
Important Limitations:
-
The actual speech recognition part is simulated in this code. In reality, Discord doesn't provide direct access to raw audio streams from other users, making voice command recognition challenging.
-
For a production-ready solution, you would need to:
- Implement a custom audio sink to capture audio data
- Process the audio to separate speakers and filter noise
- Use a reliable speech recognition service (like Google's or Mozilla's)
-
Speech recognition in noisy Discord channels with multiple speakers is technically challenging.
Would you like me to explain more about how to implement the actual speech recognition part, or do you have questions about specific parts of the code?