Build fixes and Release Build
This commit is contained in:
@@ -1,16 +1,18 @@
|
||||
import asyncio
|
||||
import logging
|
||||
import os
|
||||
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
|
||||
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
import discord
|
||||
from discord.ext import commands
|
||||
import yt_dlp
|
||||
from discord.ext import commands
|
||||
|
||||
|
||||
# ----------------------------
|
||||
@@ -97,20 +99,130 @@ class GuildAudioState:
|
||||
guild_states: dict[int, GuildAudioState] = {}
|
||||
|
||||
|
||||
# ----------------------------
|
||||
# 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_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("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 = Path(__file__).resolve().parent / "bot_token.txt"
|
||||
token_file = get_runtime_dir() / "bot_token.txt"
|
||||
if token_file.exists():
|
||||
return token_file.read_text(encoding="utf-8").strip()
|
||||
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 = get_resource_dir() / "plugins" / "ffmpeg-8.0.1" / "bin" / "ffmpeg.exe"
|
||||
|
||||
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:
|
||||
@@ -131,11 +243,13 @@ 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:
|
||||
pass
|
||||
logging.exception("Konnte Statusmeldung nicht senden: %s", message)
|
||||
|
||||
|
||||
def human_members_in_channel(channel: Optional[discord.abc.GuildChannel]) -> int:
|
||||
@@ -207,6 +321,7 @@ def _resolve_stream(url: str) -> tuple[str, str]:
|
||||
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]:
|
||||
@@ -225,8 +340,19 @@ async def ensure_connected(ctx: commands.Context) -> discord.VoiceClient:
|
||||
|
||||
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)
|
||||
@@ -271,6 +397,14 @@ async def stop_playback(
|
||||
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()
|
||||
@@ -295,7 +429,8 @@ def make_after_callback(guild_id: int):
|
||||
try:
|
||||
future.result()
|
||||
except Exception:
|
||||
pass
|
||||
logging.exception("Fehler im after-Callback für Guild %s", guild_id)
|
||||
|
||||
return _after
|
||||
|
||||
|
||||
@@ -306,6 +441,8 @@ async def play_radio(guild: discord.Guild, url: str) -> None:
|
||||
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(),
|
||||
@@ -333,9 +470,17 @@ async def play_next_yt(guild: discord.Guild) -> bool:
|
||||
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}`",
|
||||
@@ -347,7 +492,7 @@ async def play_next_yt(guild: discord.Guild) -> bool:
|
||||
executable=get_ffmpeg_path(),
|
||||
before_options=FFMPEG_BEFORE_OPTIONS,
|
||||
options=FFMPEG_OPTIONS,
|
||||
)
|
||||
)
|
||||
|
||||
state.current = CurrentItem(
|
||||
title=resolved_title,
|
||||
@@ -381,12 +526,14 @@ async def on_track_finished(guild_id: int, error: Optional[Exception]) -> None:
|
||||
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
|
||||
|
||||
state.current = None
|
||||
state.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:
|
||||
@@ -404,6 +551,12 @@ async def start_disconnect_timer(guild: discord.Guild) -> None:
|
||||
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(
|
||||
@@ -415,6 +568,7 @@ async def start_disconnect_timer(guild: discord.Guild) -> None:
|
||||
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 stop_playback(
|
||||
guild,
|
||||
clear_queue=True,
|
||||
@@ -423,7 +577,7 @@ async def start_disconnect_timer(guild: discord.Guild) -> None:
|
||||
)
|
||||
await send_status(guild, "👋 Kanal wegen Inaktivität verlassen.")
|
||||
except asyncio.CancelledError:
|
||||
pass
|
||||
logging.info("Auto-Disconnect-Timer abgebrochen in Guild %s", guild.id)
|
||||
finally:
|
||||
state.auto_disconnect_task = None
|
||||
|
||||
@@ -506,20 +660,6 @@ def build_now_output(guild: discord.Guild) -> str:
|
||||
|
||||
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
|
||||
@@ -527,7 +667,7 @@ def get_ffmpeg_path() -> str:
|
||||
|
||||
@bot.event
|
||||
async def on_ready():
|
||||
print(f"Eingeloggt als {bot.user} (ID: {bot.user.id})")
|
||||
logging.info("Eingeloggt als %s (ID: %s)", bot.user, bot.user.id if bot.user else "unknown")
|
||||
|
||||
|
||||
@bot.event
|
||||
@@ -550,6 +690,7 @@ async def on_voice_state_update(
|
||||
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
|
||||
@@ -578,9 +719,11 @@ async def on_command_error(ctx: commands.Context, error: Exception):
|
||||
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}`")
|
||||
|
||||
|
||||
@@ -593,6 +736,8 @@ async def on_command_error(ctx: commands.Context, error: Exception):
|
||||
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)
|
||||
await ctx.send(f"📞 Verbunden mit **{voice_client.channel.name}**.")
|
||||
@@ -603,6 +748,8 @@ async def call_command(ctx: commands.Context):
|
||||
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)
|
||||
|
||||
@@ -622,12 +769,15 @@ async def radio_command(ctx: commands.Context, *, url: str):
|
||||
async def yt_command(ctx: commands.Context, *, url: str):
|
||||
state = get_state(ctx.guild.id)
|
||||
|
||||
logging.info("!yt 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
|
||||
@@ -660,6 +810,8 @@ async def yt_command(ctx: commands.Context, *, url: str):
|
||||
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)
|
||||
|
||||
@@ -677,6 +829,8 @@ async def pause_command(ctx: commands.Context):
|
||||
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)
|
||||
|
||||
@@ -699,6 +853,8 @@ async def play_command(ctx: commands.Context):
|
||||
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)
|
||||
|
||||
@@ -716,6 +872,8 @@ async def stop_command(ctx: commands.Context):
|
||||
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)
|
||||
|
||||
@@ -740,6 +898,8 @@ async def skip_command(ctx: commands.Context):
|
||||
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)
|
||||
|
||||
@@ -760,6 +920,8 @@ async def leave_command(ctx: commands.Context):
|
||||
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))
|
||||
|
||||
@@ -769,6 +931,8 @@ async def now_command(ctx: commands.Context):
|
||||
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))
|
||||
|
||||
@@ -776,6 +940,8 @@ async def list_command(ctx: commands.Context):
|
||||
@commands.guild_only()
|
||||
@bot.command(name="helpme")
|
||||
async def helpme_command(ctx: commands.Context):
|
||||
logging.info("!helpme von %s in Guild %s", ctx.author, ctx.guild.id)
|
||||
|
||||
await ctx.send(
|
||||
"**Verfügbare Befehle:**\n"
|
||||
"`!call` – Bot in deinen Voice-Channel holen\n"
|
||||
@@ -796,8 +962,18 @@ async def helpme_command(ctx: commands.Context):
|
||||
# ----------------------------
|
||||
|
||||
def main() -> None:
|
||||
token = load_token()
|
||||
bot.run(token)
|
||||
setup_logging()
|
||||
|
||||
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__":
|
||||
|
||||
Reference in New Issue
Block a user