diff --git a/.gitignore b/.gitignore index 205bd71..12bf5f5 100644 --- a/.gitignore +++ b/.gitignore @@ -32,6 +32,7 @@ MANIFEST # before PyInstaller builds the exe, so as to inject date/other infos into it. *.manifest *.spec +!Radio-Bot.spec # Installer logs pip-log.txt diff --git a/README.md b/README.md index ad473ca..6b74232 100644 --- a/README.md +++ b/README.md @@ -16,10 +16,14 @@ Discord-Radio- und YouTube-Bot mit Voice-Support für normale Voice-Channels. ## Benötigte Python-Packages - `discord.py==2.7.1` -- `davey==0.1.3` +- `davey==0.1.6` - `PyNaCl==1.6.2` -- `yt-dlp` -- `pyinstaller` +- `yt-dlp[default,deno]==2026.8.19` +- `PyInstaller==6.22.0` + +Die Abhängigkeiten sind in `requirements.txt` festgeschrieben. Das `deno`-Extra +installiert die für vollständige YouTube-Unterstützung benötigte +JavaScript-Laufzeit; das `default`-Extra bringt unter anderem `yt-dlp-ejs` mit. ## Virtuelle Umgebung anlegen @@ -32,7 +36,7 @@ py -3.14 -m venv .venv ```powershell python -m pip install -U pip setuptools wheel -python -m pip install --only-binary=:all: "discord.py==2.7.1" "davey==0.1.3" "PyNaCl==1.6.2" "yt-dlp" "pyinstaller" +python -m pip install --only-binary=:all: -r requirements.txt ``` ## Projekt starten @@ -43,10 +47,11 @@ python main.py ## EXE Build -Build immer aus dem aktivierten `.venv` ausführen. +Build immer aus dem aktivierten `.venv` ausführen. Die Spec-Datei nimmt FFmpeg, +Deno, die Avatare und die benötigten Paket-Metadaten in den Build auf. ```powershell -python -m PyInstaller --noconfirm --clean --onedir --name Radio-Bot --hidden-import discord --hidden-import discord.ext.commands --hidden-import yt_dlp --collect-all discord --collect-all yt_dlp --collect-all nacl --collect-all davey --copy-metadata discord.py --copy-metadata yt-dlp --copy-metadata PyNaCl --copy-metadata davey --add-binary "D:\Git\Radio-Bot\plugins\ffmpeg-8.0.1\bin\ffmpeg.exe;plugins\ffmpeg-8.0.1\bin" --add-data "D:\Git\Radio-Bot\avatars;avatars" main.py +python -m PyInstaller --noconfirm --clean Radio-Bot.spec ``` ## FFmpeg @@ -136,9 +141,14 @@ Radio-Bot/ - `!now` – aktuell laufenden Titel oder Stream anzeigen - `!list` – aktuelle Wiedergabe und Queue anzeigen - `!helpme` – Befehlsübersicht anzeigen +- `!help` – gleiche Befehlsübersicht wie `!helpme` anzeigen ## Hinweise - Der Bot nutzt pro Server genau eine Audio-Instanz. +- Wenn der letzte Nutzer den Voice-Channel verlässt, pausiert der Bot die Wiedergabe automatisch. +- Kehrt vor dem Auto-Disconnect jemand zurück, wird nur eine automatisch pausierte Wiedergabe fortgesetzt. +- Bei einem Disconnect bleiben Radiostream und YouTube-Queue im Arbeitsspeicher erhalten. Nach `!call` wird die Wiedergabe fortgesetzt; der unterbrochene YouTube-Titel beginnt dabei von vorn. +- `!stop` beendet die Wiedergabe weiterhin bewusst und leert die gespeicherte Queue. - Für Voice-Funktionen müssen `PyNaCl` und `davey` korrekt installiert sein. - Beim EXE-Build hilft `debu.log.txt` beim Debugging, falls sich die EXE direkt wieder schließt. diff --git a/Radio-Bot.pyproj b/Radio-Bot.pyproj index ff2b231..dbb60c6 100644 --- a/Radio-Bot.pyproj +++ b/Radio-Bot.pyproj @@ -4,14 +4,14 @@ 2.0 52e4105c-0beb-4240-b1d7-33661a745e06 . - Radio_Bot.py + main.py . . Radio-Bot Radio-Bot - MSBuild|env|$(MSBuildProjectFullPath) + MSBuild|.venv|$(MSBuildProjectFullPath) true @@ -25,10 +25,10 @@ - - env + + .venv 3.14 - env (Python 3.14.3) + .venv (Python 3.14.3) Scripts\python.exe Scripts\pythonw.exe PYTHONPATH @@ -44,4 +44,4 @@ - \ No newline at end of file + diff --git a/Radio-Bot.spec b/Radio-Bot.spec new file mode 100644 index 0000000..01a0bc7 --- /dev/null +++ b/Radio-Bot.spec @@ -0,0 +1,79 @@ +# -*- mode: python ; coding: utf-8 -*- +import sys +from pathlib import Path +from PyInstaller.utils.hooks import collect_all +from PyInstaller.utils.hooks import copy_metadata + +project_root = Path(SPECPATH).resolve() +datas = [] +ffmpeg_path = project_root / 'plugins' / 'ffmpeg-8.0.1' / 'bin' / 'ffmpeg.exe' +deno_path = Path(sys.executable).resolve().parent / 'deno.exe' +for required_file in (ffmpeg_path, deno_path): + if not required_file.is_file(): + raise FileNotFoundError(f'Erforderliche Build-Datei fehlt: {required_file}') +binaries = [ + (str(ffmpeg_path), 'plugins\\ffmpeg-8.0.1\\bin'), + (str(deno_path), '.'), +] +hiddenimports = ['discord', 'discord.ext.commands', 'yt_dlp'] +avatar_dir = project_root / 'avatars' +if avatar_dir.exists(): + datas.append((str(avatar_dir), 'avatars')) +datas += copy_metadata('discord.py') +datas += copy_metadata('yt-dlp') +datas += copy_metadata('yt-dlp-ejs') +datas += copy_metadata('PyNaCl') +datas += copy_metadata('davey') +tmp_ret = collect_all('discord') +datas += tmp_ret[0]; binaries += tmp_ret[1]; hiddenimports += tmp_ret[2] +tmp_ret = collect_all('yt_dlp') +datas += tmp_ret[0]; binaries += tmp_ret[1]; hiddenimports += tmp_ret[2] +tmp_ret = collect_all('yt_dlp_ejs') +datas += tmp_ret[0]; binaries += tmp_ret[1]; hiddenimports += tmp_ret[2] +tmp_ret = collect_all('nacl') +datas += tmp_ret[0]; binaries += tmp_ret[1]; hiddenimports += tmp_ret[2] +tmp_ret = collect_all('davey') +datas += tmp_ret[0]; binaries += tmp_ret[1]; hiddenimports += tmp_ret[2] + + +a = Analysis( + ['main.py'], + pathex=[], + binaries=binaries, + datas=datas, + hiddenimports=hiddenimports, + hookspath=[], + hooksconfig={}, + runtime_hooks=[], + excludes=[], + noarchive=False, + optimize=0, +) +pyz = PYZ(a.pure) + +exe = EXE( + pyz, + a.scripts, + [], + exclude_binaries=True, + name='Radio-Bot', + debug=False, + bootloader_ignore_signals=False, + strip=False, + upx=True, + console=True, + disable_windowed_traceback=False, + argv_emulation=False, + target_arch=None, + codesign_identity=None, + entitlements_file=None, +) +coll = COLLECT( + exe, + a.binaries, + a.datas, + strip=False, + upx=True, + upx_exclude=[], + name='Radio-Bot', +) diff --git a/main.py b/main.py index 8c0620e..b0292dd 100644 --- a/main.py +++ b/main.py @@ -2,6 +2,7 @@ import asyncio import hashlib import logging import os +import shutil import sys import threading import traceback @@ -25,25 +26,46 @@ 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" -YTDLP_METADATA_OPTIONS = { + +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": True, + "no_warnings": False, "noplaylist": True, "skip_download": True, - "extract_flat": False, "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 = { - "quiet": True, - "no_warnings": True, - "noplaylist": True, - "skip_download": True, + **YTDLP_COMMON_OPTIONS, "format": "bestaudio/best", - "default_search": "auto", - "source_address": "0.0.0.0", } @@ -90,6 +112,8 @@ class CurrentItem: title: str source_url: str kind: PlaybackMode + requested_by: str = "unknown" + duration: Optional[int] = None @dataclass @@ -98,6 +122,8 @@ class GuildAudioState: 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 @@ -149,6 +175,17 @@ def get_avatar_dir() -> Path: 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 @@ -174,6 +211,9 @@ def setup_logging() -> None: 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: @@ -241,7 +281,7 @@ def load_token() -> str: raise RuntimeError("Kein Discord-Token gefunden. DISCORD_TOKEN oder bot_token.txt setzen.") def get_ffmpeg_path() -> str: - ffmpeg_path = get_resource_dir() / "plugins" / "ffmpeg-8.0.1" / "bin" / "ffmpeg.exe" + ffmpeg_path = FFMPEG_EXECUTABLE logging.info("Suche FFmpeg unter: %s", ffmpeg_path) @@ -371,7 +411,9 @@ def calculate_avatar_signature( def get_global_avatar_status() -> AvatarStatus: - active_states = tuple(guild_states.values()) + 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 @@ -597,6 +639,9 @@ async def stop_playback( state.current = None state.paused = False + state.auto_paused = False + state.suspended = False + if reset_mode: state.mode = PlaybackMode.IDLE @@ -635,6 +680,8 @@ async def play_radio(guild: discord.Guild, url: str) -> None: 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() @@ -645,10 +692,6 @@ async def play_next_yt(guild: discord.Guild) -> bool: 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 - await refresh_bot_avatar() return False while state.queue: @@ -671,6 +714,17 @@ async def play_next_yt(guild: discord.Guild) -> bool: ) 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(), @@ -682,9 +736,13 @@ async def play_next_yt(guild: discord.Guild) -> bool: 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() @@ -697,11 +755,95 @@ async def play_next_yt(guild: discord.Guild) -> bool: 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: @@ -715,8 +857,15 @@ async def on_track_finished(guild_id: int, error: Optional[Exception]) -> None: 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) @@ -757,12 +906,8 @@ async def start_disconnect_timer(guild: discord.Guild) -> None: 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 stop_playback( - guild, - clear_queue=True, - disconnect=True, - reset_mode=True, - ) + 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) @@ -776,7 +921,8 @@ async def cancel_disconnect_timer(guild: discord.Guild, *, announce: bool) -> No state = get_state(guild.id) if state.auto_disconnect_task and not state.auto_disconnect_task.done(): - state.auto_disconnect_task.cancel() + 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.") @@ -870,25 +1016,20 @@ async def on_voice_state_update( 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: logging.info("Bot wurde aus Voice getrennt in Guild %s", guild.id) async with state.lock: await cancel_disconnect_timer(guild, announce=False) - state.current = None - state.queue.clear() - state.paused = False - state.mode = PlaybackMode.IDLE + 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 @@ -897,10 +1038,13 @@ async def on_voice_state_update( if not affected: return - if bot_is_alone(voice_client): - await start_disconnect_timer(guild) - else: - await cancel_disconnect_timer(guild, announce=True) + 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 @@ -1027,8 +1171,12 @@ async def call_command(ctx: commands.Context): async with state.lock: voice_client = await ensure_connected(ctx) + resumed = await resume_suspended_playback(ctx.guild) await refresh_bot_avatar() - await ctx.send(f"📞 Verbunden mit **{voice_client.channel.name}**.") + message = f"📞 Verbunden mit **{voice_client.channel.name}**." + if resumed: + message += " Gespeicherte Wiedergabe wird fortgesetzt." + await ctx.send(message) @commands.guild_only() @@ -1068,6 +1216,7 @@ async def pause_command(ctx: commands.Context): if voice_client.is_playing(): voice_client.pause() state.paused = True + state.auto_paused = False await ctx.send("⏸ Wiedergabe pausiert.") return @@ -1087,6 +1236,7 @@ async def play_command(ctx: commands.Context): if voice_client.is_paused(): voice_client.resume() state.paused = False + state.auto_paused = False await ctx.send("▶ Wiedergabe fortgesetzt.") return @@ -1157,14 +1307,12 @@ async def leave_command(ctx: commands.Context): await cancel_disconnect_timer(ctx.guild, announce=False) await refresh_bot_avatar(override_status=AvatarStatus.LEAVING) - await stop_playback( - ctx.guild, - clear_queue=True, - disconnect=True, - reset_mode=True, - ) + 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.") + await ctx.send("👋 Voice-Channel verlassen. Wiedergabe wurde gespeichert.") @commands.guild_only() @@ -1211,15 +1359,15 @@ async def bob_command(ctx: commands.Context): await ctx.send("📻 Radio BOB gestartet.") @commands.guild_only() -@bot.command(name="helpme") +@bot.command(name="helpme", aliases=["help"]) async def helpme_command(ctx: commands.Context): - logging.info("!helpme von %s in Guild %s", ctx.author, ctx.guild.id) + 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 - Spiel Radio Bob Live Nation ab \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" @@ -1228,7 +1376,8 @@ async def helpme_command(ctx: commands.Context): "`!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" + "`!list` – aktuelle Wiedergabe und Queue anzeigen\n" + "`!help` / `!helpme` – diese Befehlsübersicht anzeigen" ) # ---------------------------- diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..e5327fc --- /dev/null +++ b/requirements.txt @@ -0,0 +1,5 @@ +discord.py==2.7.1 +davey==0.1.6 +PyNaCl==1.6.2 +yt-dlp[default,deno]==2026.8.19 +PyInstaller==6.22.0