import asyncio import hashlib import logging import os import shutil import sys import threading import traceback from collections import deque from dataclasses import dataclass, field from enum import Enum from pathlib import Path from typing import Deque, Optional, Union import discord import yt_dlp from discord.ext import commands # ---------------------------- # Konfiguration # ---------------------------- PREFIX = "!" AUTO_DISCONNECT_SECONDS = 300 FFMPEG_BEFORE_OPTIONS = "-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5" FFMPEG_OPTIONS = "-vn" RESOURCE_ROOT = Path(getattr(sys, "_MEIPASS", Path(__file__).resolve().parent)) FFMPEG_EXECUTABLE = RESOURCE_ROOT / "plugins" / "ffmpeg-8.0.1" / "bin" / "ffmpeg.exe" DENO_ROOT = Path(getattr(sys, "_MEIPASS", Path(sys.executable).resolve().parent)) DENO_EXECUTABLE = DENO_ROOT / "deno.exe" class YtDlpLogger: def debug(self, message: str) -> None: logging.getLogger("yt_dlp").debug(message) def info(self, message: str) -> None: logging.getLogger("yt_dlp").info(message) def warning(self, message: str) -> None: logging.getLogger("yt_dlp").warning(message) def error(self, message: str) -> None: logging.getLogger("yt_dlp").error(message) YTDLP_COMMON_OPTIONS = { "quiet": True, "no_warnings": False, "noplaylist": True, "skip_download": True, "default_search": "auto", "source_address": "0.0.0.0", "ffmpeg_location": str(FFMPEG_EXECUTABLE.parent), "js_runtimes": {"deno": {"path": str(DENO_EXECUTABLE)}}, "logger": YtDlpLogger(), } YTDLP_METADATA_OPTIONS = { **YTDLP_COMMON_OPTIONS, "extract_flat": False, } YTDLP_STREAM_OPTIONS = { **YTDLP_COMMON_OPTIONS, "format": "bestaudio/best", } # ---------------------------- # 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" class AvatarStatus(str, Enum): IDLE = "idle" RADIO = "radio" YOUTUBE = "youtube" LEAVING = "leaving" DEFAULT = "default" @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 requested_by: str = "unknown" duration: Optional[int] = None @dataclass class GuildAudioState: mode: PlaybackMode = PlaybackMode.IDLE current: Optional[CurrentItem] = None queue: Deque[QueueEntry] = field(default_factory=deque) paused: bool = False auto_paused: bool = False suspended: 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] = {} avatar_status_aliases: dict[AvatarStatus, tuple[str, ...]] = { AvatarStatus.IDLE: ("idle",), AvatarStatus.RADIO: ("radio",), AvatarStatus.YOUTUBE: ("youtube", "yt"), AvatarStatus.LEAVING: ("leaving", "leave"), AvatarStatus.DEFAULT: ("default", "fallback"), } avatar_supported_extensions = (".png", ".jpg", ".jpeg", ".webp", ".gif") avatar_state_lock: Optional[asyncio.Lock] = None last_avatar_signature: Optional[tuple[AvatarStatus, str, str]] = None # ---------------------------- # Logging / Basis-Helfer # ---------------------------- def get_base_dir() -> Path: if getattr(sys, "frozen", False): return Path(sys.executable).resolve().parent return Path(__file__).resolve().parent def get_resource_dir() -> Path: if getattr(sys, "frozen", False): if hasattr(sys, "_MEIPASS"): return Path(sys._MEIPASS) return Path(__file__).resolve().parent return Path(__file__).resolve().parent def get_runtime_dir() -> Path: if getattr(sys, "frozen", False): return Path(sys.executable).resolve().parent return Path(__file__).resolve().parent def get_avatar_dir() -> Path: return get_runtime_dir() / "avatars" def ensure_avatar_dir() -> Path: avatar_dir = get_avatar_dir() avatar_dir.mkdir(parents=True, exist_ok=True) bundled_avatar_dir = get_resource_dir() / "avatars" if bundled_avatar_dir.resolve() != avatar_dir.resolve() and bundled_avatar_dir.is_dir(): for source_file in bundled_avatar_dir.iterdir(): if not source_file.is_file() or source_file.suffix.lower() not in avatar_supported_extensions: continue destination = avatar_dir / source_file.name if not destination.exists(): shutil.copy2(source_file, destination) logging.info("Gebündelten Standard-Avatar bereitgestellt: %s", destination) return avatar_dir def get_log_path() -> Path: return get_runtime_dir() / "debu.log.txt" def setup_logging() -> None: log_path = get_log_path() logging.basicConfig( level=logging.DEBUG, format="%(asctime)s [%(levelname)s] %(name)s: %(message)s", handlers=[ logging.FileHandler(log_path, encoding="utf-8"), logging.StreamHandler(sys.stdout), ], force=True, ) logging.info("========== Bot-Start ==========") logging.info("Runtime-Ordner: %s", get_runtime_dir()) logging.info("Resource-Ordner: %s", get_resource_dir()) logging.info("Log-Datei: %s", log_path) logging.info("Python: %s", sys.version) logging.info("discord.py: %s", discord.__version__) logging.info("yt-dlp: %s", yt_dlp.version.__version__) logging.info("Deno: %s (vorhanden=%s)", DENO_EXECUTABLE, DENO_EXECUTABLE.is_file()) logging.info("Frozen: %s", getattr(sys, "frozen", False)) def log_uncaught_exception(exc_type, exc_value, exc_tb) -> None: if issubclass(exc_type, KeyboardInterrupt): sys.__excepthook__(exc_type, exc_value, exc_tb) return logging.critical( "Ungefangene Ausnahme:\n%s", "".join(traceback.format_exception(exc_type, exc_value, exc_tb)), ) def log_thread_exception(args) -> None: logging.critical( "Ungefangene Thread-Ausnahme in %s:\n%s", getattr(args.thread, "name", "unknown"), "".join( traceback.format_exception( args.exc_type, args.exc_value, args.exc_traceback, ) ), ) def handle_asyncio_exception(loop, context) -> None: exc = context.get("exception") if exc is not None: logging.error( "Asyncio-Ausnahme:\n%s", "".join(traceback.format_exception(type(exc), exc, exc.__traceback__)), ) else: logging.error("Asyncio-Fehler: %s", context.get("message", "Unbekannter Fehler")) async def _setup_hook() -> None: loop = asyncio.get_running_loop() loop.set_exception_handler(handle_asyncio_exception) logging.info("Asyncio-Exception-Handler gesetzt.") bot.setup_hook = _setup_hook # ---------------------------- # Helfer # ---------------------------- def load_token() -> str: env_token = os.getenv("DISCORD_TOKEN") if env_token: logging.info("Discord-Token aus Umgebungsvariable geladen.") return env_token.strip() token_file = get_runtime_dir() / "bot_token.txt" if token_file.exists(): token = token_file.read_text(encoding="utf-8").strip() if token: logging.info("Discord-Token aus Datei geladen: %s", token_file) return token raise RuntimeError("Kein Discord-Token gefunden. DISCORD_TOKEN oder bot_token.txt setzen.") def get_ffmpeg_path() -> str: ffmpeg_path = FFMPEG_EXECUTABLE logging.info("Suche FFmpeg unter: %s", ffmpeg_path) if ffmpeg_path.exists(): logging.info("FFmpeg gefunden: %s", ffmpeg_path) return str(ffmpeg_path) logging.warning("FFmpeg nicht lokal gefunden, verwende PATH-Fallback.") return "ffmpeg" 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: logging.debug("Kein Textkanal für Statusmeldung gesetzt: %s", message) return try: await channel.send(message) except discord.HTTPException: logging.exception("Konnte Statusmeldung nicht senden: %s", message) 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 get_avatar_lock() -> asyncio.Lock: global avatar_state_lock if avatar_state_lock is None: avatar_state_lock = asyncio.Lock() return avatar_state_lock def iter_avatar_candidates(status: AvatarStatus): avatar_dir = ensure_avatar_dir() for stem in avatar_status_aliases[status]: for extension in avatar_supported_extensions: yield avatar_dir / f"{stem}{extension}" def resolve_avatar_path(status: AvatarStatus) -> Optional[Path]: fallback_order = (status, AvatarStatus.IDLE, AvatarStatus.DEFAULT) seen_paths: set[Path] = set() for candidate_status in fallback_order: for candidate in iter_avatar_candidates(candidate_status): if candidate in seen_paths: continue seen_paths.add(candidate) if candidate.exists() and candidate.is_file(): return candidate return None def get_avatar_inventory() -> dict[str, list[str]]: avatar_dir = ensure_avatar_dir() inventory = { status.value: [] for status in AvatarStatus } for file_path in sorted(avatar_dir.iterdir()): if not file_path.is_file(): continue suffix = file_path.suffix.lower() if suffix not in avatar_supported_extensions: continue stem = file_path.stem.lower() for status, aliases in avatar_status_aliases.items(): if stem in aliases: inventory[status.value].append(file_path.name) return inventory def log_avatar_inventory() -> None: avatar_dir = ensure_avatar_dir() inventory = get_avatar_inventory() logging.info("Avatar-Ordner: %s", avatar_dir) for status in AvatarStatus: files = inventory[status.value] if files: logging.info("Avatar-Dateien für %s: %s", status.value, ", ".join(files)) else: logging.warning( "Keine Avatar-Datei für %s gefunden. Erwartete Basisnamen: %s", status.value, ", ".join(avatar_status_aliases[status]), ) def calculate_avatar_signature( status: AvatarStatus, avatar_path: Path, avatar_bytes: bytes, ) -> tuple[AvatarStatus, str, str]: digest = hashlib.sha256(avatar_bytes).hexdigest() return status, str(avatar_path.resolve()), digest def get_global_avatar_status() -> AvatarStatus: active_states = tuple( state for state in guild_states.values() if not state.suspended ) if any(state.mode == PlaybackMode.YT and state.paused for state in active_states): return AvatarStatus.YOUTUBE if any(state.mode == PlaybackMode.YT for state in active_states): return AvatarStatus.YOUTUBE if any(state.mode == PlaybackMode.RADIO and state.paused for state in active_states): return AvatarStatus.RADIO if any(state.mode == PlaybackMode.RADIO for state in active_states): return AvatarStatus.RADIO return AvatarStatus.IDLE async def refresh_bot_avatar(*, override_status: Optional[AvatarStatus] = None) -> None: global last_avatar_signature if bot.user is None: return async with get_avatar_lock(): requested_status = override_status or get_global_avatar_status() avatar_path = resolve_avatar_path(requested_status) if avatar_path is None: logging.warning( "Kein Avatar im Ordner %s gefunden. Erwartete Namen: idle.*, radio.*, youtube|yt.*, leaving|leave.*, default|fallback.*", ensure_avatar_dir(), ) return resolved_status = requested_status for status in (requested_status, AvatarStatus.IDLE, AvatarStatus.DEFAULT): if avatar_path in set(iter_avatar_candidates(status)): resolved_status = status break avatar_bytes = avatar_path.read_bytes() avatar_signature = calculate_avatar_signature( resolved_status, avatar_path, avatar_bytes, ) if avatar_signature == last_avatar_signature: return try: await bot.user.edit(avatar=avatar_bytes) except discord.HTTPException: logging.exception( "Konnte Avatar für Status '%s' nicht setzen: %s", resolved_status.value, avatar_path, ) return last_avatar_signature = avatar_signature logging.info( "Bot-Avatar aktualisiert: status=%s angefragt=%s datei=%s", resolved_status.value, requested_status.value, avatar_path, ) 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: logging.info( "Bot wird verschoben: Guild=%s von '%s' nach '%s'", ctx.guild.id, voice_client.channel, target_channel, ) await voice_client.move_to(target_channel) else: logging.info( "Bot verbindet sich mit Voice-Channel '%s' in Guild %s", target_channel, ctx.guild.id, ) 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 logging.info( "stop_playback: guild=%s clear_queue=%s disconnect=%s reset_mode=%s", guild.id, clear_queue, disconnect, reset_mode, ) 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 state.auto_paused = False state.suspended = 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: logging.exception("Fehler im after-Callback für Guild %s", guild_id) 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.") logging.info("Starte Radio in Guild %s: %s", guild.id, url) 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 state.auto_paused = False state.suspended = False voice_client.play(source, after=make_after_callback(guild.id)) await refresh_bot_avatar() 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(): return False while state.queue: entry = state.queue.popleft() logging.info( "Starte nächsten YT-Track in Guild %s: %s (%s)", guild.id, entry.title, entry.webpage_url, ) try: stream_url, resolved_title = await resolve_stream(entry.webpage_url) except Exception as exc: logging.exception("Konnte YT-Stream nicht auflösen: %s", entry.webpage_url) await send_status( guild, f"⚠️ Konnte Titel nicht starten: **{discord.utils.escape_markdown(entry.title)}**\n`{exc}`", ) continue voice_client = guild.voice_client if voice_client is None or not voice_client.is_connected(): state.queue.appendleft(entry) state.suspended = True logging.info( "YT-Titel nach Disconnect wieder vorne eingereiht: guild=%s title=%s", guild.id, entry.title, ) return False 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, requested_by=entry.requested_by, duration=entry.duration, ) state.mode = PlaybackMode.YT state.paused = False state.auto_paused = False state.suspended = False voice_client.play(source, after=make_after_callback(guild.id)) await refresh_bot_avatar() await send_status( guild, f"▶ Jetzt spielt: **{discord.utils.escape_markdown(resolved_title)}**", ) return True state.current = None state.paused = False state.auto_paused = False state.suspended = False state.mode = PlaybackMode.IDLE await refresh_bot_avatar() return False async def pause_when_channel_empty(guild: discord.Guild) -> None: state = get_state(guild.id) voice_client = guild.voice_client if voice_client and voice_client.is_connected() and voice_client.is_playing(): voice_client.pause() state.paused = True state.auto_paused = True logging.info("Wiedergabe automatisch pausiert: Guild %s ist leer", guild.id) async def resume_after_member_join(guild: discord.Guild) -> None: state = get_state(guild.id) voice_client = guild.voice_client if ( voice_client and voice_client.is_connected() and voice_client.is_paused() and state.auto_paused ): voice_client.resume() state.paused = False state.auto_paused = False logging.info("Automatisch pausierte Wiedergabe fortgesetzt: Guild %s", guild.id) async def suspend_playback_for_disconnect(guild: discord.Guild) -> None: state = get_state(guild.id) voice_client = guild.voice_client if state.suspended: return if state.mode == PlaybackMode.YT and state.current is not None: state.queue.appendleft( QueueEntry( title=state.current.title, webpage_url=state.current.source_url, requested_by=state.current.requested_by, duration=state.current.duration, ) ) state.current = None if voice_client and (voice_client.is_playing() or voice_client.is_paused()): state.skip_after_once = True voice_client.stop() state.paused = False state.auto_paused = False state.suspended = state.mode != PlaybackMode.IDLE logging.info( "Wiedergabe für Disconnect gespeichert: guild=%s mode=%s queue=%s", guild.id, state.mode.value, len(state.queue), ) async def resume_suspended_playback(guild: discord.Guild) -> bool: state = get_state(guild.id) if not state.suspended: return False state.suspended = False state.skip_after_once = False if state.mode == PlaybackMode.YT and state.queue: return await play_next_yt(guild) if state.mode == PlaybackMode.RADIO and state.current is not None: await play_radio(guild, state.current.source_url) return True state.mode = PlaybackMode.IDLE state.current = None await refresh_bot_avatar() 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 logging.debug("after-Callback übersprungen wegen internem Stop in Guild %s", guild_id) return voice_client = guild.voice_client if voice_client is None or not voice_client.is_connected(): await suspend_playback_for_disconnect(guild) await refresh_bot_avatar() return state.current = None state.paused = False state.auto_paused = False if error: logging.exception("Fehler bei der Wiedergabe in Guild %s: %s", guild_id, 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 refresh_bot_avatar() 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 logging.info( "Auto-Disconnect-Timer gestartet: guild=%s timeout=%s", guild.id, state.auto_disconnect_seconds, ) 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): logging.info("Auto-Disconnect greift jetzt in Guild %s", guild.id) await refresh_bot_avatar(override_status=AvatarStatus.LEAVING) await suspend_playback_for_disconnect(guild) await voice_client.disconnect(force=False) await send_status(guild, "👋 Kanal wegen Inaktivität verlassen.") except asyncio.CancelledError: logging.info("Auto-Disconnect-Timer abgebrochen in Guild %s", guild.id) 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(): if state.auto_disconnect_task is not asyncio.current_task(): 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." # ---------------------------- # Events # ---------------------------- @bot.event async def on_ready(): logging.info("Eingeloggt als %s (ID: %s)", bot.user, bot.user.id if bot.user else "unknown") await refresh_bot_avatar() @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 if member.id == bot.user.id and after.channel is None: logging.info("Bot wurde aus Voice getrennt in Guild %s", guild.id) async with state.lock: await cancel_disconnect_timer(guild, announce=False) await suspend_playback_for_disconnect(guild) await refresh_bot_avatar() return voice_client = guild.voice_client if voice_client is None or voice_client.channel is None: return bot_channel = voice_client.channel affected = ( before.channel == bot_channel or after.channel == bot_channel or member.id == bot.user.id ) if not affected: return async with state.lock: if bot_is_alone(voice_client): await pause_when_channel_empty(guild) await start_disconnect_timer(guild) else: await cancel_disconnect_timer(guild, announce=True) await resume_after_member_join(guild) @bot.event async def on_command_error(ctx: commands.Context, error: Exception): if isinstance(error, commands.CommandNotFound): return if isinstance(error, commands.CommandError): logging.warning("CommandError bei '%s': %s", ctx.message.content, error) await ctx.send(f"❌ {error}") return logging.exception("Unerwarteter Fehler bei Command '%s'", ctx.message.content) await ctx.send(f"❌ Unerwarteter Fehler: `{error}`") def is_youtube_url(url: str) -> bool: url = url.strip().lower() return ( url.startswith("https://youtu") or url.startswith("http://youtu") or url.startswith("https://www.youtube.com") or url.startswith("http://www.youtube.com") or url.startswith("https://youtube.com") or url.startswith("http://youtube.com") or url.startswith("https://m.youtube.com") or url.startswith("http://m.youtube.com") ) def extract_prefixed_youtube_command(content: str) -> Optional[str]: content = content.strip() if not content.startswith("!"): return None url = content[1:].strip() if not url: return None if is_youtube_url(url): return url return None async def enqueue_youtube_url(ctx: commands.Context, url: str) -> None: state = get_state(ctx.guild.id) logging.info("YT enqueue von %s in Guild %s: %s", ctx.author, ctx.guild.id, url) 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: logging.exception("YT-Link konnte nicht gelesen werden: %s", url) 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 # ---------------------------- @bot.event async def on_message(message: discord.Message): if message.author.bot: return if message.guild is None: await bot.process_commands(message) return inline_url = extract_prefixed_youtube_command(message.content) if inline_url is not None: logging.info( "Direkter !URL-YT-Befehl von %s in Guild %s: %s", message.author, message.guild.id, inline_url, ) ctx = await bot.get_context(message) try: await enqueue_youtube_url(ctx, inline_url) except commands.CommandError as exc: await message.channel.send(f"❌ {exc}") except Exception: logging.exception("Fehler beim direkten !URL-YT-Befehl: %s", inline_url) await message.channel.send("❌ Unerwarteter Fehler beim Verarbeiten der URL.") return await bot.process_commands(message) @commands.guild_only() @bot.command(name="call") async def call_command(ctx: commands.Context): state = get_state(ctx.guild.id) logging.info("!call von %s in Guild %s", ctx.author, ctx.guild.id) async with state.lock: voice_client = await ensure_connected(ctx) resumed = await resume_suspended_playback(ctx.guild) await refresh_bot_avatar() message = f"📞 Verbunden mit **{voice_client.channel.name}**." if resumed: message += " Gespeicherte Wiedergabe wird fortgesetzt." await ctx.send(message) @commands.guild_only() @bot.command(name="radio") async def radio_command(ctx: commands.Context, *, url: str): state = get_state(ctx.guild.id) logging.info("!radio von %s in Guild %s: %s", ctx.author, ctx.guild.id, url) 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): await enqueue_youtube_url(ctx, url) @commands.guild_only() @bot.command(name="pause") async def pause_command(ctx: commands.Context): state = get_state(ctx.guild.id) logging.info("!pause von %s in Guild %s", ctx.author, 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 state.auto_paused = False 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) logging.info("!play von %s in Guild %s", ctx.author, 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 state.auto_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) logging.info("!stop von %s in Guild %s", ctx.author, 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 refresh_bot_avatar() 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) logging.info("!skip von %s in Guild %s", ctx.author, 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) logging.info("!leave von %s in Guild %s", ctx.author, ctx.guild.id) async with state.lock: await ensure_same_voice_channel(ctx) await cancel_disconnect_timer(ctx.guild, announce=False) await refresh_bot_avatar(override_status=AvatarStatus.LEAVING) voice_client = ctx.guild.voice_client await suspend_playback_for_disconnect(ctx.guild) if voice_client and voice_client.is_connected(): await voice_client.disconnect(force=False) await ctx.send("👋 Voice-Channel verlassen. Wiedergabe wurde gespeichert.") @commands.guild_only() @bot.command(name="now") async def now_command(ctx: commands.Context): state = get_state(ctx.guild.id) logging.info("!now von %s in Guild %s", ctx.author, 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) logging.info("!list von %s in Guild %s", ctx.author, ctx.guild.id) async with state.lock: await ctx.send(build_list_output(ctx.guild)) RADIO_BOB_URL = "https://streams.radiobob.de/bob-national/mp3-192/streams.radiobob.de/" @commands.guild_only() @bot.command(name="bob") async def bob_command(ctx: commands.Context): state = get_state(ctx.guild.id) logging.info("!bob von %s in Guild %s", ctx.author, 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, RADIO_BOB_URL) await ctx.send("📻 Radio BOB gestartet.") @commands.guild_only() @bot.command(name="helpme", aliases=["help"]) async def helpme_command(ctx: commands.Context): logging.info("!%s von %s in Guild %s", ctx.invoked_with, ctx.author, ctx.guild.id) await ctx.send( "**Verfügbare Befehle:**\n" "`!call` – Bot in deinen Voice-Channel holen\n" "`!radio ` – Radio-Stream starten\n" "`!bob` – Radio BOB live abspielen\n" "`!yt ` – YouTube-Link sofort starten oder in Queue einreihen\n" "`!https://...` – YouTube-Link direkt ohne !yt 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\n" "`!help` / `!helpme` – diese Befehlsübersicht anzeigen" ) # ---------------------------- # Start # ---------------------------- def main() -> None: setup_logging() log_avatar_inventory() sys.excepthook = log_uncaught_exception threading.excepthook = log_thread_exception try: token = load_token() logging.info("Bot startet jetzt.") bot.run(token, log_handler=None) except Exception: logging.critical("Fataler Fehler beim Start:\n%s", traceback.format_exc()) raise if __name__ == "__main__": main()