added avatar image system
This commit is contained in:
@@ -1,4 +1,5 @@
|
||||
import asyncio
|
||||
import hashlib
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
@@ -68,6 +69,14 @@ class PlaybackMode(str, Enum):
|
||||
YT = "yt"
|
||||
|
||||
|
||||
class AvatarStatus(str, Enum):
|
||||
IDLE = "idle"
|
||||
RADIO = "radio"
|
||||
YOUTUBE = "youtube"
|
||||
LEAVING = "leaving"
|
||||
DEFAULT = "default"
|
||||
|
||||
|
||||
@dataclass
|
||||
class QueueEntry:
|
||||
title: str
|
||||
@@ -97,6 +106,16 @@ class GuildAudioState:
|
||||
|
||||
|
||||
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
|
||||
|
||||
|
||||
# ----------------------------
|
||||
@@ -123,6 +142,16 @@ def get_runtime_dir() -> Path:
|
||||
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)
|
||||
return avatar_dir
|
||||
|
||||
|
||||
def get_log_path() -> Path:
|
||||
return get_runtime_dir() / "debu.log.txt"
|
||||
|
||||
@@ -258,6 +287,159 @@ def human_members_in_channel(channel: Optional[discord.abc.GuildChannel]) -> int
|
||||
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(guild_states.values())
|
||||
|
||||
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
|
||||
@@ -455,6 +637,7 @@ async def play_radio(guild: discord.Guild, url: str) -> None:
|
||||
state.paused = False
|
||||
|
||||
voice_client.play(source, after=make_after_callback(guild.id))
|
||||
await refresh_bot_avatar()
|
||||
|
||||
|
||||
async def play_next_yt(guild: discord.Guild) -> bool:
|
||||
@@ -465,6 +648,7 @@ async def play_next_yt(guild: discord.Guild) -> bool:
|
||||
state.mode = PlaybackMode.IDLE
|
||||
state.current = None
|
||||
state.paused = False
|
||||
await refresh_bot_avatar()
|
||||
return False
|
||||
|
||||
while state.queue:
|
||||
@@ -503,6 +687,7 @@ async def play_next_yt(guild: discord.Guild) -> bool:
|
||||
state.paused = False
|
||||
|
||||
voice_client.play(source, after=make_after_callback(guild.id))
|
||||
await refresh_bot_avatar()
|
||||
|
||||
await send_status(
|
||||
guild,
|
||||
@@ -513,6 +698,7 @@ async def play_next_yt(guild: discord.Guild) -> bool:
|
||||
state.current = None
|
||||
state.paused = False
|
||||
state.mode = PlaybackMode.IDLE
|
||||
await refresh_bot_avatar()
|
||||
return False
|
||||
|
||||
|
||||
@@ -542,6 +728,7 @@ async def on_track_finished(guild_id: int, error: Optional[Exception]) -> None:
|
||||
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.")
|
||||
|
||||
|
||||
@@ -569,6 +756,7 @@ async def start_disconnect_timer(guild: discord.Guild) -> None:
|
||||
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 stop_playback(
|
||||
guild,
|
||||
clear_queue=True,
|
||||
@@ -668,6 +856,7 @@ def build_now_output(guild: discord.Guild) -> str:
|
||||
@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
|
||||
@@ -697,6 +886,7 @@ async def on_voice_state_update(
|
||||
state.queue.clear()
|
||||
state.paused = False
|
||||
state.mode = PlaybackMode.IDLE
|
||||
await refresh_bot_avatar()
|
||||
return
|
||||
|
||||
affected = (
|
||||
@@ -837,6 +1027,7 @@ async def call_command(ctx: commands.Context):
|
||||
|
||||
async with state.lock:
|
||||
voice_client = await ensure_connected(ctx)
|
||||
await refresh_bot_avatar()
|
||||
await ctx.send(f"📞 Verbunden mit **{voice_client.channel.name}**.")
|
||||
|
||||
|
||||
@@ -856,7 +1047,6 @@ async def radio_command(ctx: commands.Context, *, url: str):
|
||||
disconnect=False,
|
||||
reset_mode=True,
|
||||
)
|
||||
|
||||
await play_radio(ctx.guild, url)
|
||||
await ctx.send(f"📻 Radio gestartet: `{url}`")
|
||||
|
||||
@@ -924,6 +1114,7 @@ async def stop_command(ctx: commands.Context):
|
||||
disconnect=False,
|
||||
reset_mode=True,
|
||||
)
|
||||
await refresh_bot_avatar()
|
||||
await ctx.send("⏹ Wiedergabe gestoppt, Playlist geleert.")
|
||||
|
||||
|
||||
@@ -964,6 +1155,7 @@ async def leave_command(ctx: commands.Context):
|
||||
await ensure_same_voice_channel(ctx)
|
||||
|
||||
await cancel_disconnect_timer(ctx.guild, announce=False)
|
||||
await refresh_bot_avatar(override_status=AvatarStatus.LEAVING)
|
||||
|
||||
await stop_playback(
|
||||
ctx.guild,
|
||||
@@ -1045,6 +1237,7 @@ async def helpme_command(ctx: commands.Context):
|
||||
|
||||
def main() -> None:
|
||||
setup_logging()
|
||||
log_avatar_inventory()
|
||||
|
||||
sys.excepthook = log_uncaught_exception
|
||||
threading.excepthook = log_thread_exception
|
||||
@@ -1059,4 +1252,4 @@ def main() -> None:
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
main()
|
||||
|
||||
Reference in New Issue
Block a user