mirror of
https://github.com/Dasemu/DiscordBot.git
synced 2026-11-26 07:16:12 +00:00
chore: import existing DiscordBot sources
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
4db5e780cb
commit
7142152fbc
7 files changed
+263
No files matched your search
@@ -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
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
.env
|
||||||
|
.venv/
|
||||||
|
__pycache__/
|
||||||
@@ -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.
|
||||||
@@ -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.
|
||||||
@@ -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 <url or search>` | 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 |
|
||||||
@@ -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))
|
||||||
@@ -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
|
||||||
Reference in new issue
Block a user