import asyncio import os from collections import deque from dataclasses import dataclass, field from enum import Enum from typing import Deque, Optional, Union from pathlib import Path import sys import discord from discord.ext import commands import yt_dlp # ---------------------------- # Konfiguration # ---------------------------- PREFIX = "!" AUTO_DISCONNECT_SECONDS = 300 FFMPEG_BEFORE_OPTIONS = "-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5" FFMPEG_OPTIONS = "-vn" YTDLP_METADATA_OPTIONS = { "quiet": True, "no_warnings": True, "noplaylist": True, "skip_download": True, "extract_flat": False, "default_search": "auto", "source_address": "0.0.0.0", } YTDLP_STREAM_OPTIONS = { "quiet": True, "no_warnings": True, "noplaylist": True, "skip_download": True, "format": "bestaudio/best", "default_search": "auto", "source_address": "0.0.0.0", } # ---------------------------- # Discord Setup # ---------------------------- intents = discord.Intents.default() intents.message_content = True intents.guilds = True intents.voice_states = True bot = commands.Bot(command_prefix=PREFIX, intents=intents, help_command=None) # ---------------------------- # Datenmodelle # ---------------------------- class PlaybackMode(str, Enum): IDLE = "idle" RADIO = "radio" YT = "yt" @dataclass class QueueEntry: title: str webpage_url: str requested_by: str duration: Optional[int] = None @dataclass class CurrentItem: title: str source_url: str kind: PlaybackMode @dataclass class GuildAudioState: mode: PlaybackMode = PlaybackMode.IDLE current: Optional[CurrentItem] = None queue: Deque[QueueEntry] = field(default_factory=deque) paused: bool = False text_channel_id: Optional[int] = None auto_disconnect_task: Optional[asyncio.Task] = None auto_disconnect_seconds: int = AUTO_DISCONNECT_SECONDS skip_after_once: bool = False lock: asyncio.Lock = field(default_factory=asyncio.Lock) guild_states: dict[int, GuildAudioState] = {} # ---------------------------- # Helfer # ---------------------------- def load_token() -> str: env_token = os.getenv("DISCORD_TOKEN") if env_token: return env_token.strip() token_file = Path(__file__).resolve().parent / "bot_token.txt" if token_file.exists(): return token_file.read_text(encoding="utf-8").strip() raise RuntimeError("Kein Discord-Token gefunden. DISCORD_TOKEN oder bot_token.txt setzen.") def get_state(guild_id: int) -> GuildAudioState: state = guild_states.get(guild_id) if state is None: state = GuildAudioState() guild_states[guild_id] = state return state def get_text_channel( guild: discord.Guild, state: GuildAudioState ) -> Optional[discord.abc.Messageable]: if state.text_channel_id is None: return None return guild.get_channel(state.text_channel_id) async def send_status(guild: discord.Guild, message: str) -> None: state = get_state(guild.id) channel = get_text_channel(guild, state) if channel is None: return try: await channel.send(message) except discord.HTTPException: pass def human_members_in_channel(channel: Optional[discord.abc.GuildChannel]) -> int: if channel is None or not hasattr(channel, "members"): return 0 return sum(1 for member in channel.members if not member.bot) def bot_is_alone(voice_client: Optional[discord.VoiceClient]) -> bool: if voice_client is None or not voice_client.is_connected() or voice_client.channel is None: return False return human_members_in_channel(voice_client.channel) == 0 def format_duration(seconds: Optional[int]) -> str: if seconds is None: return "--:--" minutes, sec = divmod(seconds, 60) hours, minutes = divmod(minutes, 60) if hours: return f"{hours:d}:{minutes:02d}:{sec:02d}" return f"{minutes:d}:{sec:02d}" def normalize_info_dict(info: dict) -> dict: if "entries" in info and info["entries"]: for entry in info["entries"]: if entry: return normalize_info_dict(entry) return info def _extract_metadata(url: str) -> QueueEntry: with yt_dlp.YoutubeDL(YTDLP_METADATA_OPTIONS) as ydl: info = ydl.extract_info(url, download=False) info = normalize_info_dict(info) title = info.get("title") or info.get("webpage_url") or info.get("original_url") or "Unbekannter Titel" webpage_url = info.get("webpage_url") or info.get("original_url") or url duration = info.get("duration") return QueueEntry( title=title, webpage_url=webpage_url, requested_by="unknown", duration=duration, ) async def extract_metadata(url: str, requested_by: str) -> QueueEntry: entry = await asyncio.to_thread(_extract_metadata, url) entry.requested_by = requested_by return entry def _resolve_stream(url: str) -> tuple[str, str]: with yt_dlp.YoutubeDL(YTDLP_STREAM_OPTIONS) as ydl: info = ydl.extract_info(url, download=False) info = normalize_info_dict(info) stream_url = info.get("url") if not stream_url: raise RuntimeError("Konnte keine Stream-URL aus yt-dlp ermitteln.") title = info.get("title") or info.get("webpage_url") or url return stream_url, title async def resolve_stream(url: str) -> tuple[str, str]: return await asyncio.to_thread(_resolve_stream, url) async def ensure_user_in_voice( ctx: commands.Context, ) -> Union[discord.VoiceChannel, discord.StageChannel]: voice_state = getattr(ctx.author, "voice", None) if voice_state is None or voice_state.channel is None: raise commands.CommandError("Du musst in einem Voice-Channel sein.") return voice_state.channel async def ensure_connected(ctx: commands.Context) -> discord.VoiceClient: state = get_state(ctx.guild.id) state.text_channel_id = ctx.channel.id target_channel = await ensure_user_in_voice(ctx) voice_client = ctx.guild.voice_client if voice_client and voice_client.is_connected(): if voice_client.channel != target_channel: await voice_client.move_to(target_channel) else: voice_client = await target_channel.connect(self_deaf=True) await cancel_disconnect_timer(ctx.guild, announce=False) return voice_client async def ensure_same_voice_channel(ctx: commands.Context) -> discord.VoiceClient: state = get_state(ctx.guild.id) state.text_channel_id = ctx.channel.id voice_client = ctx.guild.voice_client if voice_client is None or not voice_client.is_connected(): raise commands.CommandError("Bot ist in keinem Voice-Channel.") user_voice = getattr(ctx.author, "voice", None) if user_voice is None or user_voice.channel is None: raise commands.CommandError("Du musst in einem Voice-Channel sein.") if user_voice.channel != voice_client.channel: raise commands.CommandError("Du musst im selben Voice-Channel wie der Bot sein.") await cancel_disconnect_timer(ctx.guild, announce=False) return voice_client async def ensure_connected_or_same_channel(ctx: commands.Context) -> discord.VoiceClient: voice_client = ctx.guild.voice_client if voice_client is None or not voice_client.is_connected(): return await ensure_connected(ctx) return await ensure_same_voice_channel(ctx) async def stop_playback( guild: discord.Guild, *, clear_queue: bool, disconnect: bool, reset_mode: bool, ) -> None: state = get_state(guild.id) voice_client = guild.voice_client if voice_client and (voice_client.is_playing() or voice_client.is_paused()): state.skip_after_once = True voice_client.stop() if clear_queue: state.queue.clear() state.current = None state.paused = False if reset_mode: state.mode = PlaybackMode.IDLE if disconnect and voice_client and voice_client.is_connected(): await voice_client.disconnect(force=False) def make_after_callback(guild_id: int): def _after(error: Optional[Exception]) -> None: coro = on_track_finished(guild_id, error) future = asyncio.run_coroutine_threadsafe(coro, bot.loop) try: future.result() except Exception: pass return _after async def play_radio(guild: discord.Guild, url: str) -> None: state = get_state(guild.id) voice_client = guild.voice_client if voice_client is None or not voice_client.is_connected(): raise RuntimeError("Bot ist nicht mit einem Voice-Channel verbunden.") source = discord.FFmpegPCMAudio( url, executable=get_ffmpeg_path(), before_options=FFMPEG_BEFORE_OPTIONS, options=FFMPEG_OPTIONS, ) state.current = CurrentItem(title=url, source_url=url, kind=PlaybackMode.RADIO) state.mode = PlaybackMode.RADIO state.paused = False voice_client.play(source, after=make_after_callback(guild.id)) async def play_next_yt(guild: discord.Guild) -> bool: state = get_state(guild.id) voice_client = guild.voice_client if voice_client is None or not voice_client.is_connected(): state.mode = PlaybackMode.IDLE state.current = None state.paused = False return False while state.queue: entry = state.queue.popleft() try: stream_url, resolved_title = await resolve_stream(entry.webpage_url) except Exception as exc: await send_status( guild, f"⚠️ Konnte Titel nicht starten: **{discord.utils.escape_markdown(entry.title)}**\n`{exc}`", ) continue source = discord.FFmpegPCMAudio( stream_url, executable=get_ffmpeg_path(), before_options=FFMPEG_BEFORE_OPTIONS, options=FFMPEG_OPTIONS, ) state.current = CurrentItem( title=resolved_title, source_url=entry.webpage_url, kind=PlaybackMode.YT, ) state.mode = PlaybackMode.YT state.paused = False voice_client.play(source, after=make_after_callback(guild.id)) await send_status( guild, f"▶ Jetzt spielt: **{discord.utils.escape_markdown(resolved_title)}**", ) return True state.current = None state.paused = False state.mode = PlaybackMode.IDLE return False async def on_track_finished(guild_id: int, error: Optional[Exception]) -> None: guild = bot.get_guild(guild_id) if guild is None: return state = get_state(guild_id) async with state.lock: if state.skip_after_once: state.skip_after_once = False return state.current = None state.paused = False if error: await send_status(guild, f"⚠️ Fehler bei der Wiedergabe:\n`{error}`") if state.mode == PlaybackMode.YT: started = await play_next_yt(guild) if not started: await send_status(guild, "📃 Playlist beendet.") elif state.mode == PlaybackMode.RADIO: state.mode = PlaybackMode.IDLE await send_status(guild, "📻 Radio-Stream beendet.") async def start_disconnect_timer(guild: discord.Guild) -> None: state = get_state(guild.id) if state.auto_disconnect_task and not state.auto_disconnect_task.done(): return async def _timer(): try: await send_status( guild, f"⚠️ Ich bin allein im Channel. Verlasse den Kanal in {state.auto_disconnect_seconds} Sekunden.", ) await asyncio.sleep(state.auto_disconnect_seconds) async with state.lock: voice_client = guild.voice_client if voice_client and voice_client.is_connected() and bot_is_alone(voice_client): await stop_playback( guild, clear_queue=True, disconnect=True, reset_mode=True, ) await send_status(guild, "👋 Kanal wegen Inaktivität verlassen.") except asyncio.CancelledError: pass finally: state.auto_disconnect_task = None state.auto_disconnect_task = asyncio.create_task(_timer()) async def cancel_disconnect_timer(guild: discord.Guild, *, announce: bool) -> None: state = get_state(guild.id) if state.auto_disconnect_task and not state.auto_disconnect_task.done(): state.auto_disconnect_task.cancel() state.auto_disconnect_task = None if announce: await send_status(guild, "✅ Auto-Disconnect abgebrochen.") def build_list_output(guild: discord.Guild) -> str: state = get_state(guild.id) lines: list[str] = [] lines.append(f"**Modus:** `{state.mode.value}`") if state.current: lines.append( f"**Jetzt spielt:** {discord.utils.escape_markdown(state.current.title)}" ) else: lines.append("**Jetzt spielt:** nichts") if state.queue: lines.append("**Queue:**") for index, entry in enumerate(state.queue, start=1): lines.append( f"{index}. {discord.utils.escape_markdown(entry.title)} " f"(`{format_duration(entry.duration)}`) — von {discord.utils.escape_markdown(entry.requested_by)}" ) else: lines.append("**Queue:** leer") return "\n".join(lines) def build_now_output(guild: discord.Guild) -> str: state = get_state(guild.id) voice_client = guild.voice_client if state.current is None: return "ℹ️ Aktuell läuft nichts." status = "gestoppt" if voice_client and voice_client.is_connected(): if voice_client.is_paused(): status = "pausiert" elif voice_client.is_playing(): status = "spielt" if state.mode == PlaybackMode.RADIO: return ( f"📻 **Jetzt läuft Radio**\n" f"**Status:** {status}\n" f"**Quelle:** `{state.current.source_url}`" ) if state.mode == PlaybackMode.YT: lines = [ "🎵 **Jetzt spielt**", f"**Status:** {status}", f"**Titel:** {discord.utils.escape_markdown(state.current.title)}", f"**URL:** {state.current.source_url}", ] if state.queue: next_entry = state.queue[0] lines.append( f"**Als Nächstes:** {discord.utils.escape_markdown(next_entry.title)}" ) lines.append(f"**Noch in Queue:** {len(state.queue)}") return "\n".join(lines) return "ℹ️ Aktuell läuft nichts." def get_ffmpeg_path() -> str: # Wenn später als EXE gestartet: if getattr(sys, "frozen", False): base_dir = Path(sys.executable).resolve().parent else: base_dir = Path(__file__).resolve().parent ffmpeg_path = base_dir / "plugins" / "ffmpeg-8.0.1" / "bin" / "ffmpeg.exe" if ffmpeg_path.exists(): return str(ffmpeg_path) # Fallback auf System-PATH return "ffmpeg" # ---------------------------- # Events # ---------------------------- @bot.event async def on_ready(): print(f"Eingeloggt als {bot.user} (ID: {bot.user.id})") @bot.event async def on_voice_state_update( member: discord.Member, before: discord.VoiceState, after: discord.VoiceState, ): guild = member.guild state = guild_states.get(guild.id) if state is None: return voice_client = guild.voice_client if voice_client is None: return bot_channel = voice_client.channel if bot_channel is None: return if member.id == bot.user.id and after.channel is None: async with state.lock: await cancel_disconnect_timer(guild, announce=False) state.current = None state.queue.clear() state.paused = False state.mode = PlaybackMode.IDLE return affected = ( before.channel == bot_channel or after.channel == bot_channel or member.id == bot.user.id ) if not affected: return if bot_is_alone(voice_client): await start_disconnect_timer(guild) else: await cancel_disconnect_timer(guild, announce=True) @bot.event async def on_command_error(ctx: commands.Context, error: Exception): if isinstance(error, commands.CommandNotFound): return if isinstance(error, commands.CommandError): await ctx.send(f"❌ {error}") return await ctx.send(f"❌ Unerwarteter Fehler: `{error}`") # ---------------------------- # Commands # ---------------------------- @commands.guild_only() @bot.command(name="call") async def call_command(ctx: commands.Context): state = get_state(ctx.guild.id) async with state.lock: voice_client = await ensure_connected(ctx) await ctx.send(f"📞 Verbunden mit **{voice_client.channel.name}**.") @commands.guild_only() @bot.command(name="radio") async def radio_command(ctx: commands.Context, *, url: str): state = get_state(ctx.guild.id) async with state.lock: await ensure_connected_or_same_channel(ctx) await stop_playback( ctx.guild, clear_queue=True, disconnect=False, reset_mode=True, ) await play_radio(ctx.guild, url) await ctx.send(f"📻 Radio gestartet: `{url}`") @commands.guild_only() @bot.command(name="yt") async def yt_command(ctx: commands.Context, *, url: str): state = get_state(ctx.guild.id) async with state.lock: await ensure_connected_or_same_channel(ctx) try: entry = await extract_metadata(url, ctx.author.display_name) except Exception as exc: raise commands.CommandError(f"YT-Link konnte nicht gelesen werden: {exc}") from exc voice_client = ctx.guild.voice_client if voice_client is None: raise commands.CommandError("Bot ist nicht im Voice-Channel.") if state.mode == PlaybackMode.RADIO: await stop_playback( ctx.guild, clear_queue=True, disconnect=False, reset_mode=True, ) if not voice_client.is_playing() and not voice_client.is_paused() and state.current is None: state.queue.append(entry) await play_next_yt(ctx.guild) return state.mode = PlaybackMode.YT state.queue.append(entry) await ctx.send( f"➕ Zur Playlist hinzugefügt: **{discord.utils.escape_markdown(entry.title)}** " f"(Position {len(state.queue)})" ) @commands.guild_only() @bot.command(name="pause") async def pause_command(ctx: commands.Context): state = get_state(ctx.guild.id) async with state.lock: voice_client = await ensure_same_voice_channel(ctx) if voice_client.is_playing(): voice_client.pause() state.paused = True await ctx.send("⏸ Wiedergabe pausiert.") return await ctx.send("ℹ️ Aktuell läuft nichts.") @commands.guild_only() @bot.command(name="play") async def play_command(ctx: commands.Context): state = get_state(ctx.guild.id) async with state.lock: voice_client = await ensure_same_voice_channel(ctx) if voice_client.is_paused(): voice_client.resume() state.paused = False await ctx.send("▶ Wiedergabe fortgesetzt.") return if not voice_client.is_playing() and state.mode == PlaybackMode.YT and state.queue: started = await play_next_yt(ctx.guild) if started: return await ctx.send("ℹ️ Nichts zum Abspielen vorhanden.") @commands.guild_only() @bot.command(name="stop") async def stop_command(ctx: commands.Context): state = get_state(ctx.guild.id) async with state.lock: await ensure_same_voice_channel(ctx) await stop_playback( ctx.guild, clear_queue=True, disconnect=False, reset_mode=True, ) await ctx.send("⏹ Wiedergabe gestoppt, Playlist geleert.") @commands.guild_only() @bot.command(name="skip") async def skip_command(ctx: commands.Context): state = get_state(ctx.guild.id) async with state.lock: voice_client = await ensure_same_voice_channel(ctx) if state.mode != PlaybackMode.YT: raise commands.CommandError("!skip funktioniert nur bei der YouTube-Playlist.") if not voice_client.is_playing() and not voice_client.is_paused(): raise commands.CommandError("Aktuell läuft kein YouTube-Track.") current_title = state.current.title if state.current else "Unbekannter Titel" state.skip_after_once = False voice_client.stop() await ctx.send( f"⏭ Übersprungen: **{discord.utils.escape_markdown(current_title)}**" ) @commands.guild_only() @bot.command(name="leave") async def leave_command(ctx: commands.Context): state = get_state(ctx.guild.id) async with state.lock: await ensure_same_voice_channel(ctx) await cancel_disconnect_timer(ctx.guild, announce=False) await stop_playback( ctx.guild, clear_queue=True, disconnect=True, reset_mode=True, ) await ctx.send("👋 Voice-Channel verlassen.") @commands.guild_only() @bot.command(name="now") async def now_command(ctx: commands.Context): state = get_state(ctx.guild.id) async with state.lock: await ctx.send(build_now_output(ctx.guild)) @commands.guild_only() @bot.command(name="list") async def list_command(ctx: commands.Context): state = get_state(ctx.guild.id) async with state.lock: await ctx.send(build_list_output(ctx.guild)) @commands.guild_only() @bot.command(name="helpme") async def helpme_command(ctx: commands.Context): await ctx.send( "**Verfügbare Befehle:**\n" "`!call` – Bot in deinen Voice-Channel holen\n" "`!radio ` – Radio-Stream starten\n" "`!yt ` – YouTube-Link sofort starten oder in Queue einreihen\n" "`!play` – fortsetzen / nächsten Track starten\n" "`!pause` – pausieren\n" "`!stop` – stoppen und Queue löschen\n" "`!skip` – aktuellen YT-Track überspringen\n" "`!leave` – Bot aus dem Voice-Channel werfen\n" "`!now` – aktuell laufenden Titel / Stream anzeigen\n" "`!list` – aktuelle Wiedergabe und Queue anzeigen" ) # ---------------------------- # Start # ---------------------------- def main() -> None: token = load_token() bot.run(token) if __name__ == "__main__": main()