From 7142152fbcf3e831430a8b3b98eb767df234fc07 Mon Sep 17 00:00:00 2001 From: Dasemu Date: Mon, 16 Nov 2026 21:37:42 +0100 Subject: [PATCH] chore: import existing DiscordBot sources Co-Authored-By: Claude Opus 5.5 --- .env.example | 4 + .gitignore | 3 + CLAUDE.md | 17 ++++ LESSONS.md | 6 ++ README.md | 27 +++++++ bot.py | 201 +++++++++++++++++++++++++++++++++++++++++++++++ requirements.txt | 5 ++ 7 files changed, 263 insertions(+) create mode 100644 .env.example create mode 100644 .gitignore create mode 100644 CLAUDE.md create mode 100644 LESSONS.md create mode 100644 README.md create mode 100644 bot.py create mode 100644 requirements.txt diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..bb3b17b --- /dev/null +++ b/.env.example @@ -0,0 +1,4 @@ +DISCORD_TOKEN= +# Optional: sync slash commands to one server instantly (global sync can take up to an hour) +DISCORD_GUILD_ID= +LOG_LEVEL=INFO diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..35236e6 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +.env +.venv/ +__pycache__/ diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..557dc33 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,17 @@ +# DiscordBot + +## Overview +Single-file Discord music bot (`bot.py`) using discord.py slash commands, yt-dlp for YouTube extraction and ffmpeg for streaming. + +## Commands +- Dev: `python bot.py` (needs `.env` with `DISCORD_TOKEN`) +- Install: `pip install -r requirements.txt` (inside `.venv`) +- Lint/test: none configured yet + +## Architecture +Per-guild `GuildPlayer` (queue + current track) held by `MusicBot`. `/play` resolves title/URL in a thread and queues it; `play_next` pipes `yt-dlp -o -` into ffmpeg (googlevideo returns 403 to ffmpeg's own HTTP client) and chains playback via the `after` callback. + +## Gotchas +- yt-dlp breaks often when YouTube changes; fix with `pip install -U yt-dlp`. +- Set `DISCORD_GUILD_ID` for instant slash-command sync during development. +- `davey` is pinned `<0.2`: with 0.2.0 the bot joins voice and "plays" but nobody hears it (DAVE session never ready). Check `vc._connection.can_encrypt` when audio is silent. diff --git a/LESSONS.md b/LESSONS.md new file mode 100644 index 0000000..1a04180 --- /dev/null +++ b/LESSONS.md @@ -0,0 +1,6 @@ +# Lessons + +Recurring mistakes and how to avoid them. + +- Silent voice with no errors: check the DAVE (E2EE) state before blaming the audio source. Bisect with a local tone (`-f lavfi -i sine=frequency=440`) instead of YouTube. +- Only one bot instance per token: a second instance steals the voice session and its logs end up in another terminal. diff --git a/README.md b/README.md new file mode 100644 index 0000000..2900f63 --- /dev/null +++ b/README.md @@ -0,0 +1,27 @@ +# DiscordBot + +Discord music bot: plays audio from YouTube (URL or search terms) in a voice channel. + +## Quick start + +Requirements: Python 3.10+, `ffmpeg` on PATH. + +```bash +python -m venv .venv && . .venv/bin/activate +pip install -r requirements.txt +cp .env.example .env # fill in DISCORD_TOKEN +python bot.py +``` + +Create the bot at https://discord.com/developers/applications and invite it with the +`bot` and `applications.commands` scopes and the Connect + Speak permissions. + +## Commands + +| Command | Description | +|---|---| +| `/play ` | Play or queue a song | +| `/skip` | Skip the current song | +| `/pause`, `/resume` | Pause / resume | +| `/queue` | Show the queue | +| `/stop` | Clear the queue and leave the channel | diff --git a/bot.py b/bot.py new file mode 100644 index 0000000..8c60855 --- /dev/null +++ b/bot.py @@ -0,0 +1,201 @@ +import asyncio +import logging +import os +import subprocess +import sys +from collections import deque +from dataclasses import dataclass + +import discord +import yt_dlp +from discord import app_commands +from dotenv import load_dotenv + +load_dotenv() + +log = logging.getLogger("discord.musicbot") + +YDL_OPTIONS = { + "format": "bestaudio/best", + "noplaylist": True, + "quiet": True, + "default_search": "ytsearch", + "js_runtimes": {"node": {}}, +} + + +@dataclass +class Track: + title: str + page_url: str + requested_by: str + + +class GuildPlayer: + def __init__(self) -> None: + self.queue: deque[Track] = deque() + self.current: Track | None = None + + +def extract_track(query: str, requested_by: str) -> Track: + with yt_dlp.YoutubeDL(YDL_OPTIONS) as ydl: + info = ydl.extract_info(query, download=False) + if "entries" in info: + entries = [e for e in info["entries"] if e] + if not entries: + raise ValueError("No results found") + info = entries[0] + return Track( + title=info.get("title", "Unknown"), + page_url=info.get("webpage_url", query), + requested_by=requested_by, + ) + + +class MusicBot(discord.Client): + def __init__(self) -> None: + intents = discord.Intents.default() + super().__init__(intents=intents) + self.tree = app_commands.CommandTree(self) + self.players: dict[int, GuildPlayer] = {} + + async def setup_hook(self) -> None: + guild_id = os.getenv("DISCORD_GUILD_ID") + if guild_id: + guild = discord.Object(id=int(guild_id)) + self.tree.copy_global_to(guild=guild) + await self.tree.sync(guild=guild) + else: + await self.tree.sync() + + def player(self, guild_id: int) -> GuildPlayer: + return self.players.setdefault(guild_id, GuildPlayer()) + + def play_next(self, guild: discord.Guild) -> None: + player = self.player(guild.id) + vc = guild.voice_client + if vc is None or not player.queue: + player.current = None + return + track = player.queue.popleft() + player.current = track + # googlevideo answers 403 to ffmpeg's own HTTP client, so yt-dlp downloads and pipes the audio + proc = subprocess.Popen( + [sys.executable, "-m", "yt_dlp", "-q", "--no-playlist", "--js-runtimes", "node", + "-f", "bestaudio/best", "-o", "-", track.page_url], + stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, + ) + source = discord.FFmpegOpusAudio(proc.stdout, pipe=True, options="-vn") + + def after(err: Exception | None) -> None: + log.info("Playback ended for %r (error: %s)", track.title, err) + proc.kill() + self.loop.call_soon_threadsafe(self.play_next, guild) + + log.info("Playing %r (connected=%s)", track.title, vc.is_connected()) + vc.play(source, after=after) + + +bot = MusicBot() + + +async def ensure_voice(interaction: discord.Interaction) -> discord.VoiceClient | None: + member = interaction.user + if not isinstance(member, discord.Member) or member.voice is None or member.voice.channel is None: + await interaction.followup.send("Join a voice channel first.", ephemeral=True) + return None + vc = interaction.guild.voice_client + if vc is None: + return await member.voice.channel.connect() + if vc.channel != member.voice.channel: + await vc.move_to(member.voice.channel) + return vc + + +@bot.tree.command(name="play", description="Play a song from a YouTube URL or search term") +@app_commands.describe(query="YouTube URL or search terms") +@app_commands.guild_only() +async def play(interaction: discord.Interaction, query: str) -> None: + await interaction.response.defer() + vc = await ensure_voice(interaction) + if vc is None: + return + try: + track = await asyncio.to_thread(extract_track, query, interaction.user.display_name) + except Exception as exc: + await interaction.followup.send(f"Could not load that: {exc}") + return + player = bot.player(interaction.guild.id) + player.queue.append(track) + if vc.is_playing() or vc.is_paused(): + await interaction.followup.send(f"Queued: [{track.title}](<{track.page_url}>)") + else: + bot.play_next(interaction.guild) + await interaction.followup.send(f"Now playing: [{track.title}](<{track.page_url}>)") + + +@bot.tree.command(name="skip", description="Skip the current song") +@app_commands.guild_only() +async def skip(interaction: discord.Interaction) -> None: + vc = interaction.guild.voice_client + if vc and (vc.is_playing() or vc.is_paused()): + vc.stop() + await interaction.response.send_message("Skipped.") + else: + await interaction.response.send_message("Nothing is playing.", ephemeral=True) + + +@bot.tree.command(name="pause", description="Pause playback") +@app_commands.guild_only() +async def pause(interaction: discord.Interaction) -> None: + vc = interaction.guild.voice_client + if vc and vc.is_playing(): + vc.pause() + await interaction.response.send_message("Paused.") + else: + await interaction.response.send_message("Nothing is playing.", ephemeral=True) + + +@bot.tree.command(name="resume", description="Resume playback") +@app_commands.guild_only() +async def resume(interaction: discord.Interaction) -> None: + vc = interaction.guild.voice_client + if vc and vc.is_paused(): + vc.resume() + await interaction.response.send_message("Resumed.") + else: + await interaction.response.send_message("Nothing is paused.", ephemeral=True) + + +@bot.tree.command(name="queue", description="Show the queue") +@app_commands.guild_only() +async def show_queue(interaction: discord.Interaction) -> None: + player = bot.player(interaction.guild.id) + lines = [] + if player.current: + lines.append(f"**Now playing:** {player.current.title}") + for i, track in enumerate(list(player.queue)[:10], start=1): + lines.append(f"{i}. {track.title} (by {track.requested_by})") + if len(player.queue) > 10: + lines.append(f"...and {len(player.queue) - 10} more") + await interaction.response.send_message("\n".join(lines) or "The queue is empty.") + + +@bot.tree.command(name="stop", description="Stop playback, clear the queue and leave the channel") +@app_commands.guild_only() +async def stop(interaction: discord.Interaction) -> None: + player = bot.player(interaction.guild.id) + player.queue.clear() + player.current = None + vc = interaction.guild.voice_client + if vc: + await vc.disconnect() + await interaction.response.send_message("Stopped.") + + +if __name__ == "__main__": + token = os.getenv("DISCORD_TOKEN") + if not token: + raise SystemExit("DISCORD_TOKEN is not set (see .env.example)") + bot.run(token, log_level=getattr(logging, os.getenv("LOG_LEVEL", "INFO").upper(), logging.INFO)) diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..b0627ea --- /dev/null +++ b/requirements.txt @@ -0,0 +1,5 @@ +discord.py[voice]>=2.4 +# davey 0.2.0 never marks the DAVE session ready under discord.py 2.7.1, so audio goes out unencrypted and clients drop it +davey>=0.1,<0.2 +yt-dlp[default] +python-dotenv>=1.0