Files
bot.py
requirements.txt
Code
2 88
bot.py
import logging
import os
import discord
from discord import app_commands
from discord.ext import commands
from dotenv import load_dotenv
load_dotenv()
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
)
logger = logging.getLogger("voice_bot")
intents = discord.Intents.default()
intents.voice_states = True
class VoiceBot(commands.Bot):
async def setup_hook(self) -> None:
await self.tree.sync()
logger.info("Slash commands synced")
bot = VoiceBot(command_prefix=commands.when_mentioned, intents=intents)
@bot.event
async def on_ready() -> None:
logger.info("Ready as %s (ID: %s)", bot.user, bot.user.id if bot.user else "unknown")
@bot.tree.command(name="join", description="Join the voice channel you are in.")
async def join(interaction: discord.Interaction) -> None:
if interaction.guild is None:
await interaction.response.send_message(
"This command can only be used in a server.", ephemeral=True
)
return
member = interaction.user
if not isinstance(member, discord.Member) or member.voice is None or member.voice.channel is None:
await interaction.response.send_message(
"Join a voice channel first, then try again.", ephemeral=True
)
return
channel = member.voice.channel
await interaction.response.defer(ephemeral=True)
try:
voice_client = interaction.guild.voice_client
if voice_client is None:
await channel.connect()
elif voice_client.channel != channel:
await voice_client.move_to(channel)
await interaction.followup.send(f"Joined **{channel.name}**.", ephemeral=True)
except (discord.Forbidden, discord.HTTPException, discord.ClientException) as error:
logger.warning("Could not join voice channel %s: %s", channel.id, error)
await interaction.followup.send(
"I couldn't join that voice channel. Check that I have permission to connect.",
ephemeral=True,
)
except Exception:
logger.exception("Unexpected error while joining voice channel %s", channel.id)
await interaction.followup.send(
"An unexpected error occurred while joining the voice channel.", ephemeral=True
)
async def main() -> None:
token = os.getenv("DISCORD_TOKEN")
if not token:
raise RuntimeError("DISCORD_TOKEN is missing. Add it to your .env file.")
async with bot:
await bot.start(token)
if __name__ == "__main__":
import asyncio
asyncio.run(main())