refactor: korzeń kompozycji i usunięcie starych modułów

- Application składa wszystkie zależności w jednym miejscu i prowadzi bota
  równolegle z serwerem web. Panel przeżywa awarię logowania do Discorda,
  tak jak dotąd, ale komunikat idzie przez logging zamiast print.
- zyrarbot/__main__.py pozwala uruchomić pakiet przez python -m zyrarbot
  i konfiguruje logowanie; main.py zostaje cienkim punktem wejścia.
- Usunięte bot.py, web.py i ytdl.py - ich zawartość rozeszła się po
  pakiecie. Zniknął przy tym globalny obiekt bota tworzony przy imporcie
  modułu, który wymuszał kolejność importów między bot.py a web.py.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
lgooseandClaude Bot committed 2026-08-21 01:10:59 +02:00
1 parent 3fb1e26fb4
commit 526e9ab644
6 files changed
+113 -1662

No files matched your search

-800
View File
@@ -1,800 +0,0 @@
import discord
from discord import app_commands
from discord.ext import commands
import asyncio
import os
from typing import Optional
from dotenv import load_dotenv
from ytdl import YTDLSource
# Load environment variables
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
GUILD_ID = os.getenv('GUILD_ID')
class MusicBot(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.queues = {} # guild_id -> list
self.currents = {} # guild_id -> player
self.volumes = {} # guild_id -> volume float
self.loop_currents = {} # guild_id -> bool
self.loop_playlists = {} # guild_id -> bool
self.last_channels = {} # guild_id -> text channel
self.history = {} # guild_id -> list of dicts
self.queue_indices = {} # guild_id -> int
self.jump_flag = {} # guild_id -> bool
self.default_plays = self.get_default_plays()
self.on_state_change_callback = None
def load_history(self, guild_id: int):
if guild_id in self.history:
return self.history[guild_id]
config_path = "config/history.json"
if os.path.exists(config_path):
try:
import json
with open(config_path, "r") as f:
data = json.load(f)
raw_history = data.get(str(guild_id), [])
unique_history = []
seen = set()
for item in raw_history:
key = (item.get("title", ""), item.get("url", ""))
if key not in seen:
seen.add(key)
unique_history.append(item)
self.history[guild_id] = unique_history
except Exception as e:
print(f"Error loading history: {e}")
self.history[guild_id] = []
else:
self.history[guild_id] = []
return self.history[guild_id]
def save_history(self, guild_id: int):
config_path = "config/history.json"
try:
import json
os.makedirs(os.path.dirname(config_path), exist_ok=True)
data = {}
if os.path.exists(config_path):
with open(config_path, "r") as f:
data = json.load(f)
data[str(guild_id)] = self.history.get(guild_id, [])
with open(config_path, "w") as f:
json.dump(data, f, indent=4)
except Exception as e:
print(f"Error saving history: {e}")
def add_to_history(self, guild_id: int, player):
if not player or not player.title:
return
history = self.load_history(guild_id)
entry = {
"id": player.id,
"title": player.title,
"url": player.data.get("webpage_url") or player.url,
"duration": player.duration,
"is_local": player.data.get("is_local", False),
"filepath": player.data.get("filepath")
}
history = [h for h in history if h.get("title") != entry["title"] and (not entry.get("url") or h.get("url") != entry["url"])]
history.insert(0, entry)
self.history[guild_id] = history[:50]
self.save_history(guild_id)
def get_queue(self, guild_id: int):
if guild_id not in self.queues:
self.queues[guild_id] = []
return self.queues[guild_id]
def get_current(self, guild_id: int):
return self.currents.get(guild_id)
def set_current(self, guild_id: int, player):
self.currents[guild_id] = player
def get_volume(self, guild_id: int):
return self.volumes.get(guild_id, 1.0)
def set_volume(self, guild_id: int, volume: float):
self.volumes[guild_id] = volume
def get_loop_current(self, guild_id: int):
return self.loop_currents.get(guild_id, False)
def set_loop_current(self, guild_id: int, loop: bool):
self.loop_currents[guild_id] = loop
def get_loop_playlist(self, guild_id: int):
return self.loop_playlists.get(guild_id, False)
def set_loop_playlist(self, guild_id: int, loop: bool):
self.loop_playlists[guild_id] = loop
def get_queue_index(self, guild_id: int):
return self.queue_indices.get(guild_id, -1)
def set_queue_index(self, guild_id: int, index: int):
self.queue_indices[guild_id] = index
def clear_queue(self, guild_id: int):
self.get_queue(guild_id).clear()
self.set_current(guild_id, None)
self.set_queue_index(guild_id, -1)
async def get_fresh_player(self, track):
if track.data.get('is_local'):
new_player = await YTDLSource.from_file(track.data['filepath'], loop=self.bot.loop, title=track.title)
else:
url = track.data.get('webpage_url') or track.url
new_player = await YTDLSource.from_url(url, loop=self.bot.loop, stream=True)
new_player.id = track.id
new_player.plays_left = getattr(track, 'plays_left', self.get_default_plays())
return new_player
async def enqueue_track(self, guild_id: int, player, channel=None, from_web=False):
if channel:
self.last_channels[guild_id] = channel
if getattr(player, 'plays_left', None) is None:
player.plays_left = self.get_default_plays()
queue = self.get_queue(guild_id)
queue.append(player)
voice_client = discord.utils.get(self.bot.voice_clients, guild__id=guild_id)
is_playing = voice_client and (voice_client.is_playing() or voice_client.is_paused())
url = player.data.get('webpage_url') or player.url
title_clean = discord.utils.escape_markdown(player.title or "Nieznany tytuł")
is_http = url and str(url).startswith("http")
if is_playing:
embed = discord.Embed(
title=f"🎵 {title_clean}" if not player.data.get('is_local') else f"📁 {title_clean}",
url=url if is_http else None,
description=f"[Kliknij tutaj, aby otworzyć link]({url})" if is_http else "Plik lokalny / brak linku",
color=discord.Color.blue()
)
if from_web:
embed.set_author(name="Dodano do kolejki z panelu Web", icon_url="https://cdn-icons-png.flaticon.com/512/3844/3844724.png")
else:
embed.set_author(name="Dodano do kolejki", icon_url="https://cdn-icons-png.flaticon.com/512/3844/3844724.png")
if player.duration:
mins, secs = divmod(int(player.duration), 60)
embed.add_field(name="Czas trwania", value=f"{mins}:{secs:02d}", inline=True)
embed.set_footer(text=f"Pozycja w kolejce: {len(queue)}")
await self.send_to_last_channel(guild_id, embed=embed)
await self.trigger_state_change()
return {"status": "queued", "title": player.title}
else:
await self.play_next(guild_id, advance=False)
return {"status": "playing", "title": player.title}
@commands.Cog.listener()
async def on_voice_state_update(self, member, before, after):
if member.id == self.bot.user.id and before.channel is not None and after.channel is None:
guild_id = before.channel.guild.id
self.clear_queue(guild_id)
await self.trigger_state_change()
async def trigger_state_change(self):
if self.on_state_change_callback:
try:
if asyncio.iscoroutinefunction(self.on_state_change_callback):
await self.on_state_change_callback()
else:
self.on_state_change_callback()
except Exception as e:
print(f"Error executing on_state_change_callback: {e}")
def load_saved_channel_id(self, guild_id: int):
config_path = "config/config.json"
if os.path.exists(config_path):
try:
import json
with open(config_path, "r") as f:
data = json.load(f)
val = data.get(str(guild_id))
return int(val) if val is not None else None
except Exception as e:
print(f"Error loading config: {e}")
return None
def save_channel_id(self, guild_id: int, channel_id: Optional[int]):
config_path = "config/config.json"
try:
import json
os.makedirs(os.path.dirname(config_path), exist_ok=True)
data = {}
if os.path.exists(config_path):
with open(config_path, "r") as f:
data = json.load(f)
if channel_id is None:
if str(guild_id) in data:
del data[str(guild_id)]
else:
data[str(guild_id)] = channel_id
with open(config_path, "w") as f:
json.dump(data, f, indent=4)
except Exception as e:
print(f"Error saving config: {e}")
def get_default_plays(self) -> int:
config_path = "config/config.json"
if os.path.exists(config_path):
try:
import json
with open(config_path, "r") as f:
data = json.load(f)
val = data.get("default_plays")
if val is not None:
return int(val)
except Exception as e:
print(f"Error loading default_plays: {e}")
return 5
def set_default_plays(self, val: int):
config_path = "config/config.json"
try:
import json
os.makedirs(os.path.dirname(config_path), exist_ok=True)
data = {}
if os.path.exists(config_path):
with open(config_path, "r") as f:
data = json.load(f)
data["default_plays"] = int(val)
with open(config_path, "w") as f:
json.dump(data, f, indent=4)
self.default_plays = int(val)
except Exception as e:
print(f"Error saving default_plays: {e}")
def get_notification_channel(self, guild_id: int):
if self.last_channels.get(guild_id):
return self.last_channels[guild_id]
saved_id = self.load_saved_channel_id(guild_id)
if saved_id:
channel = self.bot.get_channel(int(saved_id))
if channel:
self.last_channels[guild_id] = channel
return channel
# Fallback to the first accessible channel in the guild
guild = self.bot.get_guild(guild_id)
if guild:
for tc in guild.text_channels:
if tc.permissions_for(guild.me).send_messages:
self.last_channels[guild_id] = tc
return tc
return None
async def ensure_voice(self, interaction):
if not interaction.user.voice:
await interaction.response.send_message(
"Nie jesteś połączony z kanałem głosowym.",
ephemeral=True
)
return False
if interaction.guild.voice_client is None:
await interaction.user.voice.channel.connect()
elif interaction.guild.voice_client.channel != interaction.user.voice.channel:
await interaction.response.send_message(
"Jestem już połączony z innym kanałem głosowym.",
ephemeral=True
)
return False
return True
@app_commands.command(name="play", description="Odtwórz utwór z YouTube")
@app_commands.describe(query="Link YouTube lub zapytanie wyszukiwania")
async def play(self, interaction: discord.Interaction, query: str):
"""Odtwórz utwór z YouTube"""
if not await self.ensure_voice(interaction):
return
await interaction.response.defer()
guild_id = interaction.guild.id
self.last_channels[guild_id] = interaction.channel
try:
filepath = os.path.join("uploads", os.path.basename(query))
if os.path.exists(filepath) and not query.startswith("http"):
player = await YTDLSource.from_file(filepath, loop=self.bot.loop)
else:
player = await YTDLSource.from_url(query, loop=self.bot.loop, stream=True)
res = await self.enqueue_track(guild_id, player, channel=interaction.channel, from_web=False)
if res["status"] == "queued":
await interaction.followup.send(
f"Dodano do kolejki: {discord.utils.escape_markdown(player.title)}",
ephemeral=False
)
else:
await interaction.followup.send(
f"Teraz odtwarzane: {discord.utils.escape_markdown(player.title)}",
ephemeral=False
)
except Exception as e:
await interaction.followup.send(
f"Wystąpił błąd: {e}",
ephemeral=True
)
async def uploads_autocomplete(
self,
interaction: discord.Interaction,
current: str,
) -> list[app_commands.Choice[str]]:
uploads_dir = "uploads"
if not os.path.exists(uploads_dir):
return []
files = [f for f in os.listdir(uploads_dir) if os.path.isfile(os.path.join(uploads_dir, f)) and not f.startswith(".")]
filtered = [f for f in files if current.lower() in f.lower()][:25]
return [app_commands.Choice(name=f, value=f) for f in filtered]
@app_commands.command(name="playfile", description="Odtwórz plik przesłany na serwer")
@app_commands.describe(filename="Wybierz plik z listy przesłanych")
@app_commands.autocomplete(filename=uploads_autocomplete)
async def playfile(self, interaction: discord.Interaction, filename: str):
"""Odtwórz plik przesłany na serwer"""
if not await self.ensure_voice(interaction):
return
await interaction.response.defer()
guild_id = interaction.guild.id
self.last_channels[guild_id] = interaction.channel
filepath = os.path.join("uploads", os.path.basename(filename))
if not os.path.exists(filepath):
await interaction.followup.send("Nie znaleziono pliku na serwerze.", ephemeral=True)
return
try:
player = await YTDLSource.from_file(filepath, loop=self.bot.loop)
res = await self.enqueue_track(guild_id, player, channel=interaction.channel, from_web=False)
if res["status"] == "queued":
await interaction.followup.send(
f"Dodano do kolejki: {discord.utils.escape_markdown(player.title)}",
ephemeral=False
)
else:
await interaction.followup.send(
f"Teraz odtwarzane: {discord.utils.escape_markdown(player.title)}",
ephemeral=False
)
except Exception as e:
await interaction.followup.send(
f"Wystąpił błąd: {e}",
ephemeral=True
)
async def play_next(self, guild_id: int, advance: bool = True):
voice_client = discord.utils.get(self.bot.voice_clients, guild__id=guild_id)
if not voice_client:
self.set_current(guild_id, None)
return
if self.jump_flag.get(guild_id, False):
self.jump_flag[guild_id] = False
advance = False
queue = self.get_queue(guild_id)
if len(queue) == 0:
self.set_queue_index(guild_id, -1)
self.set_current(guild_id, None)
return
idx = self.get_queue_index(guild_id)
if idx == -1 and len(queue) > 0:
idx = 0
if not advance:
if 0 <= idx < len(queue) and self.get_current(guild_id) is not None:
next_idx = idx
else:
next_idx = len(queue) - 1
else:
if self.get_loop_current(guild_id):
next_idx = idx
elif self.get_loop_playlist(guild_id):
next_idx = (idx + 1) % len(queue)
else:
next_idx = idx + 1
if next_idx >= len(queue):
self.set_queue_index(guild_id, next_idx)
self.set_current(guild_id, None)
await self.trigger_state_change()
await self.send_to_last_channel(guild_id, "Kolejka zakończona.")
return
self.set_queue_index(guild_id, next_idx)
track = queue[next_idx]
if getattr(track, 'played', False):
try:
player = await self.get_fresh_player(track)
except Exception as e:
print(f"Error getting fresh player for track {track.title}: {e}")
await self.send_to_last_channel(guild_id, f"⚠️ Nie udało się odtworzyć: {track.title} ({e}). Pomijam.")
return await self.play_next(guild_id, advance=True)
else:
player = track
player.played = True
current_plays = getattr(player, 'plays_left', self.get_default_plays())
player.plays_left = current_plays - 1
if player.plays_left <= 0:
queue.pop(next_idx)
self.set_queue_index(guild_id, next_idx - 1)
if self.get_loop_current(guild_id):
self.set_loop_current(guild_id, False)
else:
queue[next_idx] = player
self.set_current(guild_id, player)
self.add_to_history(guild_id, player)
await self.trigger_state_change()
voice_client.play(
player,
after=lambda e: asyncio.run_coroutine_threadsafe(
self.play_next(guild_id, advance=True),
self.bot.loop
)
)
url = player.data.get('webpage_url') or player.url
title_clean = discord.utils.escape_markdown(player.title or "Nieznany tytuł")
is_http = url and str(url).startswith("http")
embed = discord.Embed(
title=f"▶️ {title_clean}" if not player.data.get('is_local') else f"📁 {title_clean}",
url=url if is_http else None,
description=f"[Kliknij tutaj, aby otworzyć link]({url})" if is_http else "Plik lokalny / brak linku",
color=discord.Color.green()
)
if player.duration:
mins, secs = divmod(int(player.duration), 60)
embed.add_field(name="Czas trwania", value=f"{mins}:{secs:02d}", inline=True)
embed.set_footer(text=f"Pozycja w kolejce: {next_idx + 1} / {len(queue)}")
await self.send_to_last_channel(guild_id, embed=embed)
async def send_to_last_channel(self, guild_id: int, text: str = None, embed: discord.Embed = None):
channel = self.get_notification_channel(guild_id)
if channel:
try:
await channel.send(content=text if text else None, embed=embed)
except Exception as e:
print(f"Failed to send message: {e}")
@app_commands.command(name="queue", description="Pokaż aktualną kolejkę")
async def show_queue(self, interaction: discord.Interaction):
"""Pokaż aktualną kolejkę"""
guild_id = interaction.guild.id
queue = self.get_queue(guild_id)
if not queue:
await interaction.response.send_message(
"Kolejka jest pusta.",
ephemeral=True
)
return
lines = []
current_idx = self.get_queue_index(guild_id)
current_playing = self.get_current(guild_id)
if current_playing and (current_idx < 0 or current_idx >= len(queue)):
plays = getattr(current_playing, 'plays_left', 0)
lines.append(f"▶️ **{discord.utils.escape_markdown(current_playing.title)}** (obecnie odtwarzane - ostatnie odtworzenie) [🔁 {plays}]\n---")
for i, item in enumerate(queue):
prefix = "▶️ **" if i == current_idx else f"{i + 1}. "
suffix = "** (obecnie odtwarzane)" if i == current_idx else ""
plays = getattr(item, 'plays_left', self.get_default_plays())
lines.append(f"{prefix}{discord.utils.escape_markdown(item.title)}{suffix} [🔁 {plays}]")
queue_list = "\n".join(lines[:30])
if len(lines) > 30:
queue_list += f"\n... i {len(lines) - 30} więcej."
await interaction.response.send_message(
f"Aktualna kolejka:\n{queue_list}",
ephemeral=False
)
async def history_autocomplete(
self,
interaction: discord.Interaction,
current: str,
) -> list[app_commands.Choice[str]]:
guild_id = interaction.guild.id
history = self.load_history(guild_id)
filtered = [h for h in history if current.lower() in h["title"].lower()][:25]
return [app_commands.Choice(name=h["title"][:100], value=str(h["id"])) for h in filtered]
@app_commands.command(name="history", description="Pokaż historię ostatnio odtwarzanych utworów")
async def show_history(self, interaction: discord.Interaction):
"""Pokaż historię odtwarzania"""
guild_id = interaction.guild.id
history = self.load_history(guild_id)
if not history:
await interaction.response.send_message(
"Historia odtwarzania jest pusta.",
ephemeral=True
)
return
history_list = "\n".join([f"{i + 1}. {discord.utils.escape_markdown(item['title'])}" for i, item in enumerate(history[:15])])
await interaction.response.send_message(
f"📜 Historia odtwarzania (ostatnie 15):\n{history_list}",
ephemeral=False
)
@app_commands.command(name="replay", description="Odtwórz ponownie utwór z historii")
@app_commands.describe(track_id="Wybierz utwór z historii odtwarzania")
@app_commands.autocomplete(track_id=history_autocomplete)
async def replay(self, interaction: discord.Interaction, track_id: str):
"""Odtwórz z historii"""
if not await self.ensure_voice(interaction):
return
await interaction.response.defer()
guild_id = interaction.guild.id
self.last_channels[guild_id] = interaction.channel
history = self.load_history(guild_id)
entry = next((item for item in history if str(item["id"]) == track_id), None)
# If not found by ID, maybe user typed an index number 1..15
if not entry and track_id.isdigit():
idx = int(track_id) - 1
if 0 <= idx < len(history):
entry = history[idx]
if not entry:
await interaction.followup.send("Nie znaleziono utworu w historii.", ephemeral=True)
return
try:
if entry.get("is_local"):
filepath = entry.get("filepath") or entry.get("url")
if not os.path.exists(filepath):
await interaction.followup.send("Plik lokalny z historii już nie istnieje na serwerze.", ephemeral=True)
return
player = await YTDLSource.from_file(filepath, loop=self.bot.loop, title=entry["title"])
else:
player = await YTDLSource.from_url(entry["url"], loop=self.bot.loop, stream=True)
res = await self.enqueue_track(guild_id, player, channel=interaction.channel, from_web=False)
if res["status"] == "queued":
await interaction.followup.send(
f"Dodano do kolejki z historii: {discord.utils.escape_markdown(player.title)}",
ephemeral=False
)
else:
await interaction.followup.send(
f"Teraz odtwarzane z historii: {discord.utils.escape_markdown(player.title)}",
ephemeral=False
)
except Exception as e:
await interaction.followup.send(f"Wystąpił błąd: {e}", ephemeral=True)
@app_commands.command(name="skip", description="Pomiń aktualny utwór")
async def skip(self, interaction: discord.Interaction):
"""Pomiń aktualny utwór"""
guild_id = interaction.guild.id
if self.get_loop_current(guild_id):
self.set_loop_current(guild_id, False)
if interaction.guild.voice_client and (interaction.guild.voice_client.is_playing() or interaction.guild.voice_client.is_paused()):
interaction.guild.voice_client.stop()
await self.trigger_state_change()
await interaction.response.send_message(
"Pominięto aktualny utwór.",
ephemeral=False
)
else:
await interaction.response.send_message(
"Nic nie jest odtwarzane.",
ephemeral=True
)
@app_commands.command(name="pause", description="Wstrzymaj odtwarzanie")
async def pause(self, interaction: discord.Interaction):
"""Wstrzymaj odtwarzanie"""
if interaction.guild.voice_client.is_playing():
interaction.guild.voice_client.pause()
await self.trigger_state_change()
await interaction.response.send_message(
"Odtwarzanie wstrzymane.",
ephemeral=False
)
else:
await interaction.response.send_message(
"Nic nie jest odtwarzane.",
ephemeral=True
)
@app_commands.command(name="resume", description="Wznów odtwarzanie")
async def resume(self, interaction: discord.Interaction):
"""Wznów odtwarzanie"""
if interaction.guild.voice_client.is_paused():
interaction.guild.voice_client.resume()
await self.trigger_state_change()
await interaction.response.send_message(
"Odtwarzanie wznowione.",
ephemeral=False
)
else:
await interaction.response.send_message(
"Odtwarzanie nie jest wstrzymane.",
ephemeral=True
)
@app_commands.command(name="stop", description="Zatrzymaj odtwarzanie i wyczyść kolejkę")
async def stop(self, interaction: discord.Interaction):
"""Zatrzymaj odtwarzanie i wyczyść kolejkę"""
guild_id = interaction.guild.id
if interaction.guild.voice_client.is_playing():
interaction.guild.voice_client.stop()
self.clear_queue(guild_id)
await self.trigger_state_change()
await interaction.response.send_message(
"Zatrzymano odtwarzanie i wyczyszczono kolejkę.",
ephemeral=False
)
@app_commands.command(name="volume", description="Zmień głośność odtwarzacza")
@app_commands.describe(volume="Poziom głośności (1-100)")
async def volume(self, interaction: discord.Interaction, volume: int):
"""Zmień głośność odtwarzacza"""
guild_id = interaction.guild.id
if interaction.guild.voice_client is None:
return await interaction.response.send_message(
"Nie połączono z kanałem głosowym.",
ephemeral=True
)
if 0 < volume <= 100:
self.set_volume(guild_id, volume / 100)
interaction.guild.voice_client.source.volume = self.get_volume(guild_id)
await self.trigger_state_change()
await interaction.response.send_message(
f"Zmieniono głośność na {volume}%",
ephemeral=False
)
return None
else:
await interaction.response.send_message(
"Wprowadź wartość z przedziału od 1 do 100.",
ephemeral=True
)
return None
@app_commands.command(name="nowplaying", description="Pokaż aktualnie odtwarzany utwór")
async def now_playing(self, interaction: discord.Interaction):
"""Pokaż aktualnie odtwarzany utwór"""
guild_id = interaction.guild.id
current = self.get_current(guild_id)
if current:
await interaction.response.send_message(
f"Teraz odtwarzane: {discord.utils.escape_markdown(current.title)}",
ephemeral=False
)
else:
await interaction.response.send_message(
"Nic nie jest obecnie odtwarzane.",
ephemeral=True
)
@app_commands.command(name="leave", description="Odłącz bota od kanału głosowego")
async def leave(self, interaction: discord.Interaction):
"""Odłącz bota od kanału głosowego"""
guild_id = interaction.guild.id
if interaction.guild.voice_client is not None:
await interaction.guild.voice_client.disconnect()
self.clear_queue(guild_id)
await interaction.response.send_message(
"Rozłączono z kanału głosowego.",
ephemeral=False
)
else:
await interaction.response.send_message(
"Nie jestem na kanale głosowym.",
ephemeral=True
)
@app_commands.command(name="loop", description="Zmień tryb zapętlania (Wyłączone -> Cała kolejka -> Jeden utwór)")
async def loop_command(self, interaction: discord.Interaction):
"""Zmień tryb zapętlania jak w YT Music/Spotify"""
guild_id = interaction.guild.id
loop_current = self.get_loop_current(guild_id)
loop_pl = self.get_loop_playlist(guild_id)
if not loop_current and not loop_pl:
self.set_loop_playlist(guild_id, True)
self.set_loop_current(guild_id, False)
msg = "🔁 Tryb zapętlania: **Cała kolejka (playlista)**"
elif loop_pl and not loop_current:
self.set_loop_playlist(guild_id, False)
self.set_loop_current(guild_id, True)
msg = "🔂 Tryb zapętlania: **Jeden utwór**"
else:
self.set_loop_playlist(guild_id, False)
self.set_loop_current(guild_id, False)
msg = "➡️ Tryb zapętlania: **Wyłączone**"
await interaction.response.send_message(msg, ephemeral=False)
@app_commands.command(name="loopplaylist", description="Włącz/wyłącz zapętlanie całej kolejki (tryb playlisty)")
async def loopplaylist_command(self, interaction: discord.Interaction):
"""Włącz/wyłącz zapętlanie całej kolejki"""
guild_id = interaction.guild.id
loop_pl = not self.get_loop_playlist(guild_id)
self.set_loop_playlist(guild_id, loop_pl)
if loop_pl:
self.set_loop_current(guild_id, False)
state = "włączone (utwory po zakończeniu wracają na koniec kolejki)" if loop_pl else "wyłączone"
await interaction.response.send_message(
f"🔁 Zapętlanie całej kolejki: **{state}**.",
ephemeral=False
)
@app_commands.command(name="defaultplays", description="Ustaw domyślną liczbę odtworzeń dla nowych utworów w kolejce")
@app_commands.describe(count="Domyślna liczba odtworzeń (1-999)")
async def default_plays_cmd(self, interaction: discord.Interaction, count: int):
if count < 1 or count > 999:
await interaction.response.send_message("❌ Liczba odtworzeń musi być z przedziału 1-999.", ephemeral=True)
return
self.set_default_plays(count)
await self.trigger_state_change()
await interaction.response.send_message(f"✅ Domyślna liczba odtworzeń dla nowych utworów została ustawiona na: **{count}**.")
@app_commands.command(name="trackplays", description="Zmień liczbę odtworzeń dla utworu w kolejce")
@app_commands.describe(index="Pozycja w kolejce (od 1)", count="Nowa liczba odtworzeń (1-999)")
async def track_plays_cmd(self, interaction: discord.Interaction, index: int, count: int):
guild_id = interaction.guild.id
queue = self.get_queue(guild_id)
if index < 1 or index > len(queue):
await interaction.response.send_message("❌ Nieprawidłowy numer utworu w kolejce.", ephemeral=True)
return
if count < 1 or count > 999:
await interaction.response.send_message("❌ Liczba odtworzeń musi być z przedziału 1-999.", ephemeral=True)
return
track = queue[index - 1]
track.plays_left = count
await self.trigger_state_change()
await interaction.response.send_message(f"✅ Ustawiono liczbę odtworzeń dla utworu **{discord.utils.escape_markdown(track.title)}** na **{count}**.")
class MyBot(commands.Bot):
def __init__(self):
intents = discord.Intents.default()
intents.message_content = True
intents.voice_states = True
super().__init__(command_prefix="!", intents=intents)
async def setup_hook(self):
await self.add_cog(MusicBot(self))
if GUILD_ID:
guild = discord.Object(id=int(GUILD_ID))
self.tree.copy_global_to(guild=guild)
await self.tree.sync(guild=guild)
print(f"Synced commands to guild {GUILD_ID}")
else:
await self.tree.sync()
print("Synced commands globally")
async def on_ready(self):
print(f'Logged in as {self.user.name} ({self.user.id})')
print('------')
bot = MyBot()
+3 -25
View File
@@ -1,28 +1,6 @@
import asyncio
import uvicorn
from bot import bot, TOKEN
from web import app
async def main():
async with bot:
config = uvicorn.Config(app, host="0.0.0.0", port=8000, log_level="info")
server = uvicorn.Server(config)
server_task = asyncio.create_task(server.serve())
try:
await bot.start(TOKEN)
except Exception as e:
print(f"Error starting Discord bot: {e}")
print("Keep running FastAPI web server...")
while not server.should_exit:
try:
await asyncio.sleep(1)
except asyncio.CancelledError:
break
finally:
server.should_exit = True
await server_task
"""Punkt wejścia aplikacji - cała logika mieszka w pakiecie ``zyrarbot``."""
from zyrarbot.__main__ import main
if __name__ == "__main__":
asyncio.run(main())
main()
-745
View File
@@ -1,745 +0,0 @@
from fastapi import FastAPI, HTTPException, WebSocket, WebSocketDisconnect, UploadFile, File
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel
from typing import List, Optional
import asyncio
import discord
import os
import shutil
# Import bot instance and YTDL class
from bot import bot
from ytdl import YTDLSource
# Initialize FastAPI application
app = FastAPI(title="ŻyrarBOT Queue Controller")
# FastAPI Request Models
class PlayRequest(BaseModel):
query: str
class VolumeRequest(BaseModel):
volume: int
class LoopRequest(BaseModel):
loop: bool
class RemoveRequest(BaseModel):
id: str
class ReorderRequest(BaseModel):
queue_ids: List[str]
class JumpRequest(BaseModel):
index: int
class ConnectRequest(BaseModel):
channel_id: str
class TextChannelRequest(BaseModel):
channel_id: str
guild_id: Optional[str] = None
class PlayFileRequest(BaseModel):
filename: str
class DefaultPlaysRequest(BaseModel):
default_plays: int
class TrackPlaysRequest(BaseModel):
id: str
plays: int
# Connection Manager for WebSockets
class ConnectionManager:
def __init__(self):
self.active_connections: List[WebSocket] = []
async def connect(self, websocket: WebSocket):
await websocket.accept()
self.active_connections.append(websocket)
def disconnect(self, websocket: WebSocket):
if websocket in self.active_connections:
self.active_connections.remove(websocket)
async def broadcast(self, message: dict):
for connection in list(self.active_connections):
try:
await connection.send_json(message)
except Exception:
self.disconnect(connection)
manager = ConnectionManager()
# Helper to determine active guild
def get_active_guild():
voice_client = bot.voice_clients[0] if bot.voice_clients else None
if voice_client:
return voice_client.guild
elif bot.guilds:
return bot.guilds[0]
return None
# FastAPI Endpoints
@app.get("/api/status")
async def get_status():
music_cog = bot.get_cog("MusicBot")
if not music_cog:
return {"error": "MusicBot cog not loaded"}
all_guilds = []
for g in bot.guilds:
g_tc = []
for tc in g.text_channels:
if tc.permissions_for(g.me).send_messages:
g_tc.append({
"channel_id": str(tc.id),
"channel_name": tc.name
})
active_notif = music_cog.get_notification_channel(g.id)
all_guilds.append({
"guild_id": str(g.id),
"guild_name": g.name,
"text_channels": g_tc,
"active_notification_channel_id": str(active_notif.id) if active_notif else None
})
all_voice_channels = []
for g in bot.guilds:
for vc in g.voice_channels:
all_voice_channels.append({
"guild_name": g.name,
"guild_id": str(g.id),
"channel_name": vc.name,
"channel_id": str(vc.id)
})
guild = get_active_guild()
if not guild:
return {
"playing": False,
"paused": False,
"loop_single": False,
"loop_playlist": False,
"volume": 100,
"current": None,
"queue": [],
"history": [],
"voice_channels": all_voice_channels,
"active_voice_channel": None,
"text_channels": [],
"active_text_channel_id": None,
"guilds": all_guilds,
"default_plays": music_cog.get_default_plays() if music_cog else 5
}
guild_id = guild.id
# Active voice channel
voice_client = discord.utils.get(bot.voice_clients, guild__id=guild_id)
active_vc = None
if voice_client and voice_client.channel:
active_vc = {
"channel_name": voice_client.channel.name,
"channel_id": str(voice_client.channel.id),
"guild_name": voice_client.channel.guild.name,
"guild_id": str(voice_client.channel.guild.id)
}
# Gather text channels available to the bot on this active guild where it can write
text_channels = []
for channel in guild.text_channels:
if channel.permissions_for(guild.me).send_messages:
text_channels.append({
"guild_name": guild.name,
"guild_id": str(guild.id),
"channel_name": channel.name,
"channel_id": str(channel.id)
})
active_tc_id = None
active_tc = music_cog.get_notification_channel(guild_id)
if active_tc:
active_tc_id = str(active_tc.id)
playing = voice_client.is_playing() if voice_client else False
paused = voice_client.is_paused() if voice_client else False
current_track = music_cog.get_current(guild_id)
queue = music_cog.get_queue(guild_id)
return {
"playing": playing,
"paused": paused,
"loop_single": music_cog.get_loop_current(guild_id),
"loop_playlist": music_cog.get_loop_playlist(guild_id),
"volume": int(music_cog.get_volume(guild_id) * 100),
"current": {
"title": current_track.title,
"url": current_track.data.get("webpage_url") or current_track.url,
"id": current_track.id,
"duration": current_track.duration,
"elapsed": round(current_track.elapsed, 1),
"plays_left": getattr(current_track, 'plays_left', music_cog.get_default_plays())
} if current_track else None,
"queue": [
{
"title": item.title,
"url": item.data.get("webpage_url") or item.url,
"id": item.id,
"plays_left": getattr(item, 'plays_left', music_cog.get_default_plays())
} for item in queue
],
"queue_index": music_cog.get_queue_index(guild_id),
"default_plays": music_cog.get_default_plays(),
"voice_channels": all_voice_channels,
"active_voice_channel": active_vc,
"text_channels": text_channels,
"active_text_channel_id": active_tc_id,
"guilds": all_guilds,
"history": [
{
"id": item["id"],
"title": item["title"],
"url": item["url"],
"duration": item.get("duration"),
"is_local": item.get("is_local", False),
"filepath": item.get("filepath")
} for item in music_cog.load_history(guild_id)[:20]
]
}
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
await manager.connect(websocket)
try:
# Immediately send status upon connection
status = await get_status()
await websocket.send_json(status)
while True:
# Maintain connection, listen for disconnect
await websocket.receive_text()
except WebSocketDisconnect:
manager.disconnect(websocket)
except Exception as e:
print(f"WS connection error: {e}")
manager.disconnect(websocket)
async def broadcast_status():
if not manager.active_connections:
return
try:
status = await get_status()
await manager.broadcast(status)
except Exception as e:
print(f"Error in broadcast_status: {e}")
@app.post("/api/play")
async def api_play(req: PlayRequest):
music_cog = bot.get_cog("MusicBot")
if not music_cog:
raise HTTPException(status_code=500, detail="MusicBot cog not loaded")
guild = get_active_guild()
if not guild:
raise HTTPException(status_code=400, detail="Bot has no active server context")
guild_id = guild.id
voice_client = discord.utils.get(bot.voice_clients, guild__id=guild_id)
if not voice_client:
raise HTTPException(status_code=400, detail="Bot is not connected to a voice channel on this server")
try:
filepath = os.path.join("uploads", os.path.basename(req.query))
if os.path.exists(filepath) and not req.query.startswith("http"):
player = await YTDLSource.from_file(filepath, loop=bot.loop)
else:
player = await YTDLSource.from_url(req.query, loop=bot.loop, stream=True)
res = await music_cog.enqueue_track(guild_id, player, from_web=True)
await broadcast_status()
return res
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/api/pause")
async def api_pause():
guild = get_active_guild()
if not guild:
raise HTTPException(status_code=400, detail="Bot has no active server context")
voice_client = discord.utils.get(bot.voice_clients, guild__id=guild.id)
if voice_client and voice_client.is_playing():
voice_client.pause()
await broadcast_status()
return {"status": "paused"}
raise HTTPException(status_code=400, detail="Bot is not playing on this server")
@app.post("/api/resume")
async def api_resume():
guild = get_active_guild()
if not guild:
raise HTTPException(status_code=400, detail="Bot has no active server context")
voice_client = discord.utils.get(bot.voice_clients, guild__id=guild.id)
if voice_client and voice_client.is_paused():
voice_client.resume()
await broadcast_status()
return {"status": "resumed"}
raise HTTPException(status_code=400, detail="Bot is not paused on this server")
@app.post("/api/skip")
async def api_skip():
music_cog = bot.get_cog("MusicBot")
guild = get_active_guild()
if not guild:
raise HTTPException(status_code=400, detail="Bot has no active server context")
if music_cog and music_cog.get_loop_current(guild.id):
music_cog.set_loop_current(guild.id, False)
voice_client = discord.utils.get(bot.voice_clients, guild__id=guild.id)
if voice_client and (voice_client.is_playing() or voice_client.is_paused()):
voice_client.stop()
await broadcast_status()
return {"status": "skipped"}
raise HTTPException(status_code=400, detail="Bot is not playing anything on this server")
@app.post("/api/jump")
async def api_jump(req: JumpRequest):
music_cog = bot.get_cog("MusicBot")
if not music_cog:
raise HTTPException(status_code=500, detail="MusicBot cog not loaded")
guild = get_active_guild()
if not guild:
raise HTTPException(status_code=400, detail="Bot has no active server context")
guild_id = guild.id
queue = music_cog.get_queue(guild_id)
if req.index < 0 or req.index >= len(queue):
raise HTTPException(status_code=400, detail="Invalid track index")
if music_cog.get_loop_current(guild_id):
music_cog.set_loop_current(guild_id, False)
music_cog.set_queue_index(guild_id, req.index)
music_cog.jump_flag[guild_id] = True
voice_client = discord.utils.get(bot.voice_clients, guild__id=guild_id)
if voice_client and (voice_client.is_playing() or voice_client.is_paused()):
voice_client.stop()
else:
await music_cog.play_next(guild_id, advance=False)
await broadcast_status()
return {"status": "jumped"}
@app.post("/api/stop")
async def api_stop():
music_cog = bot.get_cog("MusicBot")
if not music_cog:
raise HTTPException(status_code=500, detail="MusicBot cog not loaded")
guild = get_active_guild()
if not guild:
return {"status": "stopped"}
guild_id = guild.id
voice_client = discord.utils.get(bot.voice_clients, guild__id=guild_id)
if voice_client and (voice_client.is_playing() or voice_client.is_paused()):
voice_client.stop()
music_cog.clear_queue(guild_id)
await broadcast_status()
return {"status": "stopped"}
@app.post("/api/volume")
async def api_volume(req: VolumeRequest):
music_cog = bot.get_cog("MusicBot")
if not music_cog:
raise HTTPException(status_code=500, detail="MusicBot cog not loaded")
guild = get_active_guild()
if not guild:
raise HTTPException(status_code=400, detail="Bot has no active server context")
guild_id = guild.id
if 0 <= req.volume <= 100:
music_cog.set_volume(guild_id, req.volume / 100)
voice_client = discord.utils.get(bot.voice_clients, guild__id=guild_id)
if voice_client and voice_client.source:
voice_client.source.volume = music_cog.get_volume(guild_id)
await broadcast_status()
return {"status": "success", "volume": req.volume}
raise HTTPException(status_code=400, detail="Volume must be between 0 and 100")
@app.post("/api/loop")
async def api_loop(req: LoopRequest):
music_cog = bot.get_cog("MusicBot")
if not music_cog:
raise HTTPException(status_code=500, detail="MusicBot cog not loaded")
guild = get_active_guild()
if not guild:
raise HTTPException(status_code=400, detail="Bot has no active server context")
music_cog.set_loop_current(guild.id, req.loop)
if req.loop:
music_cog.set_loop_playlist(guild.id, False)
await broadcast_status()
return {"status": "success", "loop": req.loop}
@app.post("/api/loop_playlist")
async def api_loop_playlist():
music_cog = bot.get_cog("MusicBot")
if not music_cog:
raise HTTPException(status_code=500, detail="MusicBot cog not loaded")
guild = get_active_guild()
if not guild:
raise HTTPException(status_code=400, detail="Bot has no active server context")
current_state = music_cog.get_loop_playlist(guild.id)
new_state = not current_state
music_cog.set_loop_playlist(guild.id, new_state)
if new_state:
music_cog.set_loop_current(guild.id, False)
await broadcast_status()
return {"status": "success", "loop_playlist": new_state}
@app.post("/api/loop_cycle")
async def api_loop_cycle():
music_cog = bot.get_cog("MusicBot")
if not music_cog:
raise HTTPException(status_code=500, detail="MusicBot cog not loaded")
guild = get_active_guild()
if not guild:
raise HTTPException(status_code=400, detail="Bot has no active server context")
loop_current = music_cog.get_loop_current(guild.id)
loop_pl = music_cog.get_loop_playlist(guild.id)
if not loop_current and not loop_pl:
music_cog.set_loop_playlist(guild.id, True)
music_cog.set_loop_current(guild.id, False)
mode = "playlist"
elif loop_pl and not loop_current:
music_cog.set_loop_playlist(guild.id, False)
music_cog.set_loop_current(guild.id, True)
mode = "single"
else:
music_cog.set_loop_playlist(guild.id, False)
music_cog.set_loop_current(guild.id, False)
mode = "off"
await broadcast_status()
return {"status": "success", "mode": mode}
@app.post("/api/remove")
async def api_remove(req: RemoveRequest):
music_cog = bot.get_cog("MusicBot")
if not music_cog:
raise HTTPException(status_code=500, detail="MusicBot cog not loaded")
guild = get_active_guild()
if not guild:
raise HTTPException(status_code=400, detail="Bot has no active server context")
guild_id = guild.id
queue = music_cog.get_queue(guild_id)
current_idx = music_cog.get_queue_index(guild_id)
removed_idx = -1
for idx, item in enumerate(queue):
if item.id == req.id:
removed_idx = idx
break
if removed_idx == -1:
raise HTTPException(status_code=404, detail="Track not found in queue")
if removed_idx == current_idx:
new_queue = [item for idx, item in enumerate(queue) if idx != removed_idx]
music_cog.queues[guild_id] = new_queue
music_cog.set_queue_index(guild_id, current_idx)
music_cog.jump_flag[guild_id] = True
voice_client = discord.utils.get(bot.voice_clients, guild__id=guild_id)
if voice_client and (voice_client.is_playing() or voice_client.is_paused()):
voice_client.stop()
else:
await music_cog.play_next(guild_id, advance=False)
else:
new_queue = [item for idx, item in enumerate(queue) if idx != removed_idx]
music_cog.queues[guild_id] = new_queue
if removed_idx < current_idx:
music_cog.set_queue_index(guild_id, current_idx - 1)
await broadcast_status()
return {"status": "removed"}
@app.post("/api/reorder")
async def api_reorder(req: ReorderRequest):
music_cog = bot.get_cog("MusicBot")
if not music_cog:
raise HTTPException(status_code=500, detail="MusicBot cog not loaded")
guild = get_active_guild()
if not guild:
raise HTTPException(status_code=400, detail="Bot has no active server context")
guild_id = guild.id
queue = music_cog.get_queue(guild_id)
current_idx = music_cog.get_queue_index(guild_id)
curr_item = queue[current_idx] if 0 <= current_idx < len(queue) else None
queue_map = {item.id: item for item in queue}
new_queue = []
for track_id in req.queue_ids:
if track_id in queue_map:
new_queue.append(queue_map[track_id])
# Retain any items not present in the reordered IDs list
for item in queue:
if item.id not in req.queue_ids:
new_queue.append(item)
music_cog.queues[guild_id] = new_queue
if curr_item:
try:
music_cog.set_queue_index(guild_id, new_queue.index(curr_item))
except ValueError:
pass
await broadcast_status()
return {"status": "success"}
@app.get("/api/uploads")
async def get_uploads():
uploads_dir = "uploads"
os.makedirs(uploads_dir, exist_ok=True)
files = []
for f in os.listdir(uploads_dir):
filepath = os.path.join(uploads_dir, f)
if os.path.isfile(filepath) and not f.startswith("."):
size_mb = round(os.path.getsize(filepath) / (1024 * 1024), 2)
mtime = os.path.getmtime(filepath)
files.append({
"filename": f,
"size_mb": size_mb,
"mtime": mtime
})
files.sort(key=lambda x: x["mtime"], reverse=True)
return {"files": files}
@app.post("/api/upload")
async def api_upload_file(file: UploadFile = File(...)):
uploads_dir = "uploads"
os.makedirs(uploads_dir, exist_ok=True)
filename = os.path.basename(file.filename)
filepath = os.path.join(uploads_dir, filename)
try:
with open(filepath, "wb") as buffer:
shutil.copyfileobj(file.file, buffer)
return {"status": "success", "filename": filename}
except Exception as e:
raise HTTPException(status_code=500, detail=f"Błąd zapisu pliku: {e}")
@app.delete("/api/uploads/{filename}")
async def api_delete_file(filename: str):
uploads_dir = "uploads"
filepath = os.path.join(uploads_dir, os.path.basename(filename))
if os.path.exists(filepath):
try:
os.remove(filepath)
return {"status": "deleted"}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
raise HTTPException(status_code=404, detail="Plik nie istnieje")
@app.post("/api/play_file")
async def api_play_file(req: PlayFileRequest):
music_cog = bot.get_cog("MusicBot")
if not music_cog:
raise HTTPException(status_code=500, detail="MusicBot cog not loaded")
guild = get_active_guild()
if not guild:
raise HTTPException(status_code=400, detail="Bot has no active server context")
guild_id = guild.id
voice_client = discord.utils.get(bot.voice_clients, guild__id=guild_id)
if not voice_client:
raise HTTPException(status_code=400, detail="Bot is not connected to a voice channel on this server")
filepath = os.path.join("uploads", os.path.basename(req.filename))
if not os.path.exists(filepath):
raise HTTPException(status_code=404, detail="Plik nie istnieje na serwerze")
try:
os.utime(filepath, None)
player = await YTDLSource.from_file(filepath, loop=bot.loop)
res = await music_cog.enqueue_track(guild_id, player, from_web=True)
await broadcast_status()
return res
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/api/connect")
async def api_connect(req: ConnectRequest):
try:
channel_id = int(req.channel_id)
except ValueError:
raise HTTPException(status_code=400, detail="Invalid channel ID")
channel = bot.get_channel(channel_id)
if not channel:
raise HTTPException(status_code=404, detail="Voice channel not found")
guild_id = channel.guild.id
# Only disconnect voice clients from the SAME guild!
for vc in bot.voice_clients:
if vc.guild.id == guild_id:
await vc.disconnect()
await channel.connect()
music_cog = bot.get_cog("MusicBot")
if music_cog and not music_cog.get_notification_channel(guild_id):
# Save first accessible text channel to send updates
for tc in channel.guild.text_channels:
if tc.permissions_for(channel.guild.me).send_messages:
music_cog.last_channels[guild_id] = tc
break
await broadcast_status()
return {"status": "connected", "channel": channel.name}
@app.post("/api/disconnect")
async def api_disconnect():
guild = get_active_guild()
if not guild:
raise HTTPException(status_code=400, detail="Bot has no active server context")
guild_id = guild.id
voice_client = discord.utils.get(bot.voice_clients, guild__id=guild_id)
if voice_client:
await voice_client.disconnect()
music_cog = bot.get_cog("MusicBot")
if music_cog:
music_cog.clear_queue(guild_id)
await broadcast_status()
return {"status": "disconnected"}
raise HTTPException(status_code=400, detail="Bot not connected to voice on this server")
@app.post("/api/settings/text_channel")
async def api_set_text_channel(req: TextChannelRequest):
music_cog = bot.get_cog("MusicBot")
if not music_cog:
raise HTTPException(status_code=500, detail="MusicBot cog not loaded")
if not req.channel_id or req.channel_id == "0" or req.channel_id == "":
if not req.guild_id:
raise HTTPException(status_code=400, detail="guild_id required to reset channel")
guild_id = int(req.guild_id)
if guild_id in music_cog.last_channels:
del music_cog.last_channels[guild_id]
music_cog.save_channel_id(guild_id, None)
await broadcast_status()
return {"status": "success", "channel_id": None, "guild_id": str(guild_id)}
channel = bot.get_channel(int(req.channel_id))
if not channel:
raise HTTPException(status_code=404, detail="Text channel not found")
guild_id = channel.guild.id
if req.guild_id and int(req.guild_id) != guild_id:
raise HTTPException(status_code=400, detail="Channel does not belong to the specified guild")
music_cog.last_channels[guild_id] = channel
music_cog.save_channel_id(guild_id, int(req.channel_id))
# Send test message to confirm
try:
await channel.send(f"🔔 Ten kanał został ustawiony jako główny kanał powiadomień dla ŻyrarBOT na serwerze **{channel.guild.name}** z panelu webowego.")
except Exception as e:
print(f"Failed to send test message: {e}")
await broadcast_status()
return {"status": "success", "channel_id": req.channel_id, "guild_id": str(guild_id)}
@app.post("/api/settings/default_plays")
async def api_set_default_plays(req: DefaultPlaysRequest):
music_cog = bot.get_cog("MusicBot")
if not music_cog:
raise HTTPException(status_code=500, detail="MusicBot cog not loaded")
if req.default_plays < 1 or req.default_plays > 999:
raise HTTPException(status_code=400, detail="Invalid default plays value")
music_cog.set_default_plays(req.default_plays)
await broadcast_status()
return {"status": "success", "default_plays": req.default_plays}
@app.post("/api/queue/plays")
async def api_set_track_plays(req: TrackPlaysRequest):
music_cog = bot.get_cog("MusicBot")
if not music_cog:
raise HTTPException(status_code=500, detail="MusicBot cog not loaded")
guild = get_active_guild()
if not guild:
raise HTTPException(status_code=400, detail="Bot has no active server context")
guild_id = guild.id
queue = music_cog.get_queue(guild_id)
if req.plays < 1 or req.plays > 999:
raise HTTPException(status_code=400, detail="Invalid plays value")
found = False
for item in queue:
if item.id == req.id:
item.plays_left = req.plays
found = True
break
if not found:
raise HTTPException(status_code=404, detail="Track not found in queue")
await broadcast_status()
return {"status": "success", "id": req.id, "plays": req.plays}
# WebSocket Background Loop and Startup Hook
async def status_broadcast_loop():
while True:
try:
await asyncio.sleep(1)
if manager.active_connections:
await broadcast_status()
except asyncio.CancelledError:
break
except Exception as e:
print(f"Error in status_broadcast_loop: {e}")
async def wait_and_register_callback():
for _ in range(30): # Try for 30 seconds
await asyncio.sleep(1)
music_cog = bot.get_cog("MusicBot")
if music_cog:
music_cog.on_state_change_callback = broadcast_status
print("Registered WebSocket state change callback on MusicBot cog (delayed)")
break
@app.on_event("startup")
async def startup_event():
music_cog = bot.get_cog("MusicBot")
if music_cog:
music_cog.on_state_change_callback = broadcast_status
print("Registered WebSocket state change callback on MusicBot cog")
else:
asyncio.create_task(wait_and_register_callback())
asyncio.create_task(status_broadcast_loop())
# Serve UI Files (Must be registered after API routes)
app.mount("/", StaticFiles(directory="static", html=True), name="static")
-92
View File
@@ -1,92 +0,0 @@
import discord
import yt_dlp as youtube_dl
import asyncio
import uuid
import os
ytdl_format_options = {
'format': 'bestaudio/best',
'outtmpl': '%(extractor)s-%(id)s-%(title)s.%(ext)s',
'restrictfilenames': True,
'noplaylist': True,
'nocheckcertificate': True,
'ignoreerrors': False,
'logtostderr': False,
'quiet': True,
'no_warnings': True,
'default_search': 'auto',
'source_address': '0.0.0.0',
}
ffmpeg_options = {
'options': '-vn',
'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5'
}
ytdl = youtube_dl.YoutubeDL(ytdl_format_options)
async def get_file_duration(filepath):
try:
proc = await asyncio.create_subprocess_exec(
'ffprobe', '-v', 'error', '-show_entries', 'format=duration',
'-of', 'default=noprint_wrappers=1:nokey=1', filepath,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
stdout, _ = await proc.communicate()
if proc.returncode == 0:
return float(stdout.decode().strip())
except Exception as e:
print(f"Error getting duration with ffprobe: {e}")
return 0.0
class YTDLSource(discord.PCMVolumeTransformer):
def __init__(self, source, *, data, volume=0.5):
super().__init__(source, volume)
self.data = data
self.title = data.get('title')
self.url = data.get('url')
self.id = uuid.uuid4().hex # Unique track identifier
self.duration = data.get('duration') # Duration in seconds
self.elapsed = 0.0 # Elapsed time in seconds
self.plays_left = data.get('plays_left', None) # Remaining plays in queue
def read(self):
data = super().read()
if data:
self.elapsed += 0.02 # 20ms frames read
return data
@classmethod
async def from_url(cls, url, *, loop=None, stream=False):
loop = loop or asyncio.get_event_loop()
data = await loop.run_in_executor(None, lambda: ytdl.extract_info(url, download=not stream))
if 'entries' in data:
data = data['entries'][0]
filename = data['url'] if stream else ytdl.prepare_filename(data)
return cls(discord.FFmpegPCMAudio(filename, **ffmpeg_options), data=data)
@classmethod
async def from_file(cls, filepath, *, loop=None, title=None):
loop = loop or asyncio.get_event_loop()
duration = await get_file_duration(filepath)
filename_only = os.path.basename(filepath)
display_title = title or os.path.splitext(filename_only)[0]
data = {
'title': display_title,
'url': filepath,
'webpage_url': None,
'duration': duration,
'is_local': True,
'filepath': filepath
}
local_ffmpeg_options = {
'options': '-vn'
}
return cls(discord.FFmpegPCMAudio(filepath, **local_ffmpeg_options), data=data)
+18
View File
@@ -0,0 +1,18 @@
from __future__ import annotations
import asyncio
import logging
from zyrarbot.application import Application
def main() -> None:
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)-8s %(name)s: %(message)s",
)
asyncio.run(Application().run())
if __name__ == "__main__":
main()
+92
View File
@@ -0,0 +1,92 @@
from __future__ import annotations
import asyncio
import logging
import uvicorn
from zyrarbot.audio.media_probe import MediaProbe
from zyrarbot.audio.track_factory import TrackFactory
from zyrarbot.bot.client import ZyrarBot
from zyrarbot.bot.guild_resolver import GuildResolver
from zyrarbot.music.music_player import MusicPlayer
from zyrarbot.music.notification_channel_resolver import NotificationChannelResolver
from zyrarbot.music.track_embed_factory import TrackEmbedFactory
from zyrarbot.settings import Settings
from zyrarbot.storage.guild_config_repository import GuildConfigRepository
from zyrarbot.storage.history_repository import HistoryRepository
from zyrarbot.storage.json_file_store import JsonFileStore
from zyrarbot.storage.uploads_repository import UploadsRepository
from zyrarbot.web.factory import create_app
logger = logging.getLogger(__name__)
class Application:
"""Korzeń kompozycji: składa wszystkie zależności i prowadzi bota razem z API."""
def __init__(self, settings: Settings | None = None):
self.settings = settings or Settings.from_env()
self.config = GuildConfigRepository(
JsonFileStore(self.settings.config_file),
fallback_plays=self.settings.default_plays,
)
self.history = HistoryRepository(
JsonFileStore(self.settings.history_file), limit=self.settings.history_limit
)
self.uploads = UploadsRepository(self.settings.uploads_dir)
self.tracks = TrackFactory(self.uploads, MediaProbe())
self.bot = ZyrarBot(self.settings, self.tracks, self.uploads)
self.guilds = GuildResolver(self.bot)
self.player = MusicPlayer(
bot=self.bot,
track_factory=self.tracks,
history=self.history,
config=self.config,
channels=NotificationChannelResolver(self.bot, self.config),
embeds=TrackEmbedFactory(),
)
self.bot.player = self.player
self.api = create_app(
settings=self.settings,
player=self.player,
guilds=self.guilds,
tracks=self.tracks,
uploads=self.uploads,
config=self.config,
)
async def run(self) -> None:
"""Startuje serwer web, a następnie bota; panel działa też bez Discorda."""
config = uvicorn.Config(
self.api,
host=self.settings.web_host,
port=self.settings.web_port,
log_level="info",
)
server = uvicorn.Server(config)
async with self.bot:
server_task = asyncio.create_task(server.serve())
try:
if not self.settings.discord_token:
raise RuntimeError("Brak DISCORD_TOKEN w środowisku")
await self.bot.start(self.settings.discord_token)
except Exception as error: # noqa: BLE001 - panel ma przetrwać awarię bota
logger.error("Nie udało się wystartować bota Discord: %s", error)
logger.info("Serwer webowy działa dalej...")
await self._wait_for_shutdown(server)
finally:
server.should_exit = True
await server_task
@staticmethod
async def _wait_for_shutdown(server: uvicorn.Server) -> None:
while not server.should_exit:
try:
await asyncio.sleep(1)
except asyncio.CancelledError:
break