Files
main.py
README.md
requirements.txt
Code
3 329
main.py
import asyncio
import logging
import os
from collections import defaultdict, deque
from dataclasses import dataclass
import discord
from discord import app_commands
from discord.ext import commands
from dotenv import load_dotenv
import yt_dlp
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
)
logger = logging.getLogger("music_bot")
YTDL_OPTIONS = {
"format": "bestaudio/best",
"quiet": True,
"no_warnings": True,
"default_search": "ytsearch1",
"noplaylist": True,
}
FFMPEG_BEFORE_OPTIONS = "-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5"
FFMPEG_OPTIONS = "-vn"
@dataclass(frozen=True)
class Track:
title: str
url: str
requester: str
def find_track(query: str) -> Track:
with yt_dlp.YoutubeDL(YTDL_OPTIONS) as ytdl:
info = ytdl.extract_info(query, download=False)
if info is None:
raise ValueError("No track was found for that search.")
if "entries" in info:
info = next((entry for entry in info["entries"] if entry), None)
if not info:
raise ValueError("No track was found for that search.")
url = info.get("webpage_url") or info.get("original_url")
if not url:
raise ValueError("Could not get a playable URL for that track.")
return Track(title=info.get("title", "Unknown title"), url=url, requester="")
def get_stream_url(url: str) -> str:
with yt_dlp.YoutubeDL(YTDL_OPTIONS) as ytdl:
info = ytdl.extract_info(url, download=False)
if not info or not info.get("url"):
raise ValueError("Could not retrieve the audio stream.")
return info["url"]
class MusicBot(commands.Bot):
def __init__(self) -> None:
intents = discord.Intents.default()
intents.voice_states = True
super().__init__(command_prefix="!", intents=intents)
self.queues: dict[int, deque[Track]] = defaultdict(deque)
self.now_playing: dict[int, Track] = {}
self.text_channels: dict[int, discord.abc.Messageable] = {}
self.starting: set[int] = set()
self.generations: dict[int, int] = defaultdict(int)
async def setup_hook(self) -> None:
synced = await self.tree.sync()
logger.info("Synced %d application commands", len(synced))
async def play_next(self, guild_id: int) -> None:
if guild_id in self.starting:
return
voice_client = self.get_voice_client(guild_id)
if voice_client is None or voice_client.is_playing() or voice_client.is_paused():
return
self.starting.add(guild_id)
try:
while self.queues[guild_id]:
generation = self.generations[guild_id]
track = self.queues[guild_id].popleft()
try:
stream_url = await asyncio.to_thread(get_stream_url, track.url)
if generation != self.generations[guild_id]:
continue
voice_client = self.get_voice_client(guild_id)
if voice_client is None:
return
source = discord.PCMVolumeTransformer(
discord.FFmpegPCMAudio(
stream_url,
before_options=FFMPEG_BEFORE_OPTIONS,
options=FFMPEG_OPTIONS,
),
volume=0.5,
)
self.now_playing[guild_id] = track
loop = asyncio.get_running_loop()
def after(error: Exception | None) -> None:
if error:
logger.error("Audio playback failed: %s", error)
asyncio.run_coroutine_threadsafe(self.play_next(guild_id), loop)
voice_client.play(source, after=after)
await self.notify(guild_id, f"▶️ Now playing **{track.title}**")
return
except Exception:
logger.exception("Could not play track: %s", track.title)
await self.notify(guild_id, f"Couldn't play **{track.title}**. Skipping it.")
self.now_playing.pop(guild_id, None)
finally:
self.starting.discard(guild_id)
def get_voice_client(self, guild_id: int) -> discord.VoiceClient | None:
return discord.utils.get(self.voice_clients, guild__id=guild_id)
async def notify(self, guild_id: int, message: str) -> None:
channel = self.text_channels.get(guild_id)
if channel is not None:
try:
await channel.send(message)
except discord.HTTPException:
logger.exception("Could not send playback status message")
bot = MusicBot()
def user_voice_channel(interaction: discord.Interaction) -> discord.abc.GuildChannel | None:
if not isinstance(interaction.user, discord.Member) or interaction.user.voice is None:
return None
return interaction.user.voice.channel
@bot.tree.command(name="join", description="Join your current voice channel")
async def join(interaction: discord.Interaction) -> None:
channel = user_voice_channel(interaction)
if channel is None:
await interaction.response.send_message("Join a voice channel first.", ephemeral=True)
return
await interaction.response.defer(ephemeral=True)
voice_client = bot.get_voice_client(interaction.guild_id)
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)
@bot.tree.command(name="play", description="Play a song or add it to the queue")
@app_commands.describe(query="A song name or URL")
async def play(interaction: discord.Interaction, query: str) -> None:
channel = user_voice_channel(interaction)
if channel is None:
await interaction.response.send_message("Join a voice channel first.", ephemeral=True)
return
await interaction.response.defer()
voice_client = bot.get_voice_client(interaction.guild_id)
if voice_client is None:
voice_client = await channel.connect()
elif voice_client.channel != channel:
await interaction.followup.send(
"I'm already playing in another voice channel. Use `/join` to move me.",
ephemeral=True,
)
return
try:
track = await asyncio.to_thread(find_track, query)
except Exception as error:
logger.exception("Track search failed")
await interaction.followup.send(f"Couldn't find that track: {error}", ephemeral=True)
return
track = Track(track.title, track.url, interaction.user.display_name)
guild_id = interaction.guild_id
bot.text_channels[guild_id] = interaction.channel
bot.queues[guild_id].append(track)
if voice_client.is_playing() or voice_client.is_paused() or guild_id in bot.starting:
await interaction.followup.send(f"Added **{track.title}** to the queue.")
else:
await interaction.followup.send(f"Queued **{track.title}**.")
await bot.play_next(guild_id)