980 lines
28 KiB
Python
980 lines
28 KiB
Python
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
|
||
|
||
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"
|
||
|
||
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] = {}
|
||
|
||
|
||
# ----------------------------
|
||
# 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 = 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 = 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:
|
||
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 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
|
||
|
||
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
|
||
|
||
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()
|
||
|
||
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
|
||
|
||
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
|
||
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:
|
||
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
|
||
|
||
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 stop_playback(
|
||
guild,
|
||
clear_queue=True,
|
||
disconnect=True,
|
||
reset_mode=True,
|
||
)
|
||
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():
|
||
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")
|
||
|
||
|
||
@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:
|
||
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
|
||
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):
|
||
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}`")
|
||
|
||
|
||
# ----------------------------
|
||
# Commands
|
||
# ----------------------------
|
||
|
||
@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)
|
||
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)
|
||
|
||
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):
|
||
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
|
||
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)
|
||
|
||
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
|
||
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
|
||
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 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 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)
|
||
|
||
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))
|
||
|
||
|
||
@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"
|
||
"`!radio <url>` – Radio-Stream starten\n"
|
||
"`!yt <url>` – 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:
|
||
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__":
|
||
main() |