mirror of
https://github.com/Dasemu/DiscordBot.git
synced 2026-11-26 07:16:12 +00:00
202 lines
6.8 KiB
Python
202 lines
6.8 KiB
Python
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))
|