Files
zyrarbot/zyrarbot/ui/api/routers/voice_router.py
T
mmacierzanka d3a5058fde
Backend / Lint i formatowanie (pull_request) Successful in 3s
Backend / Testy i kontrakt API (pull_request) Failing after 2m19s
Backend / Testowy build obrazu (pull_request) Skipped
Formatting, README and other friends
2026-08-21 13:41:38 +02:00

68 lines
2.2 KiB
Python

from __future__ import annotations
import discord
from fastapi import APIRouter, Depends, HTTPException
from zyrarbot.music.music_player import MusicPlayer
from zyrarbot.music.notification_channel_resolver import NotificationChannelResolver
from zyrarbot.ui.api.dependencies import (
get_active_guild,
get_broadcaster,
get_guilds,
get_player,
)
from zyrarbot.ui.api.requests.connect_request import ConnectRequest
from zyrarbot.ui.api.status_broadcaster import StatusBroadcaster
from zyrarbot.ui.bot.guild_resolver import GuildResolver
router = APIRouter(prefix="/api", tags=["voice"])
@router.post("/connect")
async def connect(
request: ConnectRequest,
guilds: GuildResolver = Depends(get_guilds),
player: MusicPlayer = Depends(get_player),
broadcaster: StatusBroadcaster = Depends(get_broadcaster),
) -> dict[str, str]:
try:
channel_id = int(request.channel_id)
except ValueError as error:
raise HTTPException(status_code=400, detail="Invalid channel ID") from error
channel = guilds.channel(channel_id)
if not isinstance(channel, discord.VoiceChannel):
raise HTTPException(status_code=404, detail="Voice channel not found")
guild_id = channel.guild.id
# Rozłączamy wyłącznie na tym samym serwerze - inne serwery grają dalej.
existing = guilds.voice_client(guild_id)
if existing:
await existing.disconnect()
await channel.connect()
if not player.notification_channel(guild_id):
player.set_notification_channel(
guild_id, NotificationChannelResolver.first_writable(channel.guild)
)
await broadcaster.broadcast()
return {"status": "connected", "channel": channel.name}
@router.post("/disconnect")
async def disconnect(
guild: discord.Guild = Depends(get_active_guild),
player: MusicPlayer = Depends(get_player),
broadcaster: StatusBroadcaster = Depends(get_broadcaster),
) -> dict[str, str]:
voice_client = player.voice_client(guild.id)
if not voice_client:
raise HTTPException(status_code=400, detail="Bot not connected to voice on this server")
await voice_client.disconnect()
player.clear(guild.id)
await broadcaster.broadcast()
return {"status": "disconnected"}