command fixes and youtube fixes

This commit is contained in:
2026-10-11 21:30:57 +02:00
parent 9ace3454e0
commit b5d8351668
6 changed files with 306 additions and 62 deletions
+199 -50
View File
@@ -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 <url>` – Radio-Stream starten\n"
"`!bob - Spiel Radio Bob Live Nation ab \n"
"`!bob` – Radio BOB live abspielen\n"
"`!yt <url>` – 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"
)
# ----------------------------