Neue Raids der Elyos Allianz postet Siel (config.php: siel_api), die Website holt die Raids beider Bots und schickt Anfragen zu einem Raid an den Bot, der ihn gepostet hat. Kanäle und Rollen des Servers der Elyos Allianz liefert Siel. Premades nur noch bei Legions-Raids. Ohne siel_api-Block bleibt alles wie vorher bei Nezekan. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
405 lines
13 KiB
PHP
405 lines
13 KiB
PHP
<?php
|
|
declare(strict_types=1);
|
|
|
|
require_once __DIR__ . '/raids_api.php';
|
|
|
|
/**
|
|
* Die Event-Erinnerungen haengen - genau wie Raids/Premades/Reports - an dem einen in
|
|
* config.php unter raids_api.guild_id hinterlegten Discord-Server.
|
|
*
|
|
* @throws RuntimeException
|
|
*/
|
|
function events_guild_id(): int
|
|
{
|
|
return reports_guild_id();
|
|
}
|
|
|
|
/**
|
|
* Fuehrt einen Request gegen die Event-API des Bots aus (/api/events/...) - analog zu
|
|
* reports_api_request().
|
|
*
|
|
* @param array<string, mixed> $queryParams
|
|
* @param array<string, mixed>|null $jsonBody
|
|
* @return array<string, mixed>
|
|
* @throws RuntimeException
|
|
*/
|
|
function events_api_request(string $method, string $path = '', array $queryParams = [], ?array $jsonBody = null): array
|
|
{
|
|
// /api/events liegt - wie /api/reports - eine Ebene ueber /api/raids.
|
|
$base = preg_replace('#/raids$#', '', raids_api_config()['url']);
|
|
|
|
return bot_api_request($method, $base . '/events' . $path, $queryParams, $jsonBody, 'Event-API');
|
|
}
|
|
|
|
/**
|
|
* Fuehrt einen Request gegen die Server-Struktur-Endpunkte des Bots aus
|
|
* (/api/guilds/{guild_id}/...), ueber die Kanaele und Rollen abgefragt werden.
|
|
*
|
|
* @return array<string, mixed>
|
|
* @throws RuntimeException
|
|
*/
|
|
function guilds_api_request(string $path, ?string $guildId = null): array
|
|
{
|
|
// $guildId: ein anderer Server als der der Legion (der der Elyos Allianz) - den kennt Siel, falls eingerichtet
|
|
$siel = siel_api_config();
|
|
if ($guildId !== null && $guildId !== (string) events_guild_id() && $siel !== null) {
|
|
$base = preg_replace('#/raids$#', '', $siel['url']);
|
|
return bot_api_request('GET', $base . '/guilds/' . $guildId . $path, [], null, 'Siel', $siel['key']);
|
|
}
|
|
|
|
$base = preg_replace('#/raids$#', '', raids_api_config()['url']);
|
|
return bot_api_request('GET', $base . '/guilds/' . ($guildId ?? events_guild_id()) . $path, [], null, 'Bot-API');
|
|
}
|
|
|
|
/**
|
|
* Gemeinsamer cURL-Aufruf fuer die Event-/Guild-Endpunkte. Anders als die aelteren
|
|
* *_api_request()-Funktionen bekommt er die fertige URL uebergeben, damit nicht fuer jeden
|
|
* neuen Endpunkt dieselben 40 Zeilen cURL-Code kopiert werden muessen.
|
|
*
|
|
* @param array<string, mixed> $queryParams
|
|
* @param array<string, mixed>|null $jsonBody
|
|
* @return array<string, mixed>
|
|
* @throws RuntimeException
|
|
*/
|
|
function bot_api_request(string $method, string $url, array $queryParams, ?array $jsonBody, string $label, ?string $apiKey = null): array
|
|
{
|
|
if (!function_exists('curl_init')) {
|
|
throw new RuntimeException('Die PHP-cURL-Erweiterung ist auf diesem Server nicht aktiviert.');
|
|
}
|
|
|
|
if (!empty($queryParams)) {
|
|
$url .= '?' . http_build_query($queryParams);
|
|
}
|
|
|
|
$headers = ['X-API-Key: ' . ($apiKey ?? raids_api_config()['key'])];
|
|
|
|
$ch = curl_init($url);
|
|
$options = [
|
|
CURLOPT_RETURNTRANSFER => true,
|
|
CURLOPT_CUSTOMREQUEST => $method,
|
|
CURLOPT_TIMEOUT => 10,
|
|
CURLOPT_SSL_VERIFYPEER => true,
|
|
];
|
|
|
|
if ($jsonBody !== null) {
|
|
$headers[] = 'Content-Type: application/json';
|
|
$options[CURLOPT_POSTFIELDS] = json_encode($jsonBody, JSON_UNESCAPED_UNICODE);
|
|
}
|
|
|
|
$options[CURLOPT_HTTPHEADER] = $headers;
|
|
curl_setopt_array($ch, $options);
|
|
|
|
$response = curl_exec($ch);
|
|
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
|
$curlError = curl_error($ch);
|
|
curl_close($ch);
|
|
|
|
if ($response === false) {
|
|
throw new RuntimeException('Verbindung zur ' . $label . ' fehlgeschlagen: ' . $curlError);
|
|
}
|
|
|
|
$data = json_decode((string) $response, true);
|
|
|
|
if ($httpCode < 200 || $httpCode >= 300) {
|
|
throw new RuntimeException(bot_api_error_message($label, $httpCode, $data));
|
|
}
|
|
|
|
if (!is_array($data)) {
|
|
throw new RuntimeException('Unerwartetes Antwortformat der ' . $label . '.');
|
|
}
|
|
|
|
return $data;
|
|
}
|
|
|
|
/**
|
|
* Alle geplanten Event-Erinnerungen des Servers, aufsteigend nach naechster Erinnerung.
|
|
*
|
|
* @return array<int, array<string, mixed>>
|
|
* @throws RuntimeException
|
|
*/
|
|
function fetch_events(): array
|
|
{
|
|
$data = events_api_request('GET', '', ['guild_id' => events_guild_id()]);
|
|
|
|
if (($data['status'] ?? '') !== 'success' || !is_array($data['events'] ?? null)) {
|
|
throw new RuntimeException('Unerwartetes Antwortformat der Event-API.');
|
|
}
|
|
|
|
return $data['events'];
|
|
}
|
|
|
|
/**
|
|
* Textkanaele des Servers (inkl. Kategorie und der Info, ob der Bot dort posten darf).
|
|
*
|
|
* @return array<int, array<string, mixed>>
|
|
* @throws RuntimeException
|
|
*/
|
|
function fetch_guild_channels(?string $guildId = null): array
|
|
{
|
|
$data = guilds_api_request('/channels', $guildId);
|
|
|
|
if (($data['status'] ?? '') !== 'success' || !is_array($data['channels'] ?? null)) {
|
|
throw new RuntimeException('Unerwartetes Antwortformat der Bot-API.');
|
|
}
|
|
|
|
return $data['channels'];
|
|
}
|
|
|
|
/**
|
|
* Rollen des Servers (ohne @everyone), hoechste zuerst.
|
|
*
|
|
* @return array<int, array<string, mixed>>
|
|
* @throws RuntimeException
|
|
*/
|
|
function fetch_guild_roles(?string $guildId = null): array
|
|
{
|
|
$data = guilds_api_request('/roles', $guildId);
|
|
|
|
if (($data['status'] ?? '') !== 'success' || !is_array($data['roles'] ?? null)) {
|
|
throw new RuntimeException('Unerwartetes Antwortformat der Bot-API.');
|
|
}
|
|
|
|
return $data['roles'];
|
|
}
|
|
|
|
/**
|
|
* Legt eine neue Event-Erinnerung an. Der Zeitpunkt wird als "TT.MM.JJJJ HH:MM" uebergeben und
|
|
* erst vom Bot in einen Timestamp umgerechnet - genau wie bei der Raid-Erstellung, damit beide
|
|
* Seiten garantiert dieselbe Zeitzone verwenden.
|
|
*
|
|
* @return int Die neue Event-ID.
|
|
* @throws RuntimeException
|
|
*/
|
|
function create_event(string $name, string $message, int $channelId, int $roleId, string $nextRunRaw,
|
|
int $intervalSeconds, int $createdBy): int
|
|
{
|
|
$data = events_api_request('POST', '', [], [
|
|
'guild_id' => events_guild_id(),
|
|
'channel_id' => $channelId,
|
|
'role_id' => $roleId,
|
|
'name' => $name,
|
|
'message' => $message,
|
|
'next_run_raw' => $nextRunRaw,
|
|
'interval_seconds' => $intervalSeconds,
|
|
'created_by' => $createdBy,
|
|
]);
|
|
|
|
return (int) ($data['event_id'] ?? 0);
|
|
}
|
|
|
|
/**
|
|
* @param array<string, mixed> $fields Nur die zu aendernden Felder (name, message, channel_id,
|
|
* role_id, next_run_raw, interval_seconds).
|
|
* @throws RuntimeException
|
|
*/
|
|
function update_event(int $eventId, array $fields): void
|
|
{
|
|
events_api_request('PATCH', '/' . $eventId, [], $fields);
|
|
}
|
|
|
|
/** @throws RuntimeException */
|
|
function delete_event(int $eventId): void
|
|
{
|
|
events_api_request('DELETE', '/' . $eventId);
|
|
}
|
|
|
|
/**
|
|
* Prueft und normalisiert die Formularfelder aus dem Anlegen-/Bearbeiten-Formular. Beide Wege
|
|
* nutzen dieselben Felder und damit auch dieselbe Pruefung.
|
|
*
|
|
* @param array<string, mixed> $input Dekodierter JSON-Body.
|
|
* @return array<string, mixed>|string Die fertigen Felder, oder eine Fehlermeldung als String.
|
|
*/
|
|
function event_fields_from_input(array $input)
|
|
{
|
|
$name = trim((string) ($input['name'] ?? ''));
|
|
$message = trim((string) ($input['message'] ?? ''));
|
|
$channelId = (int) ($input['channel_id'] ?? 0);
|
|
$roleId = (int) ($input['role_id'] ?? 0);
|
|
$nextRunRaw = trim((string) ($input['next_run_raw'] ?? ''));
|
|
$intervalValue = (int) ($input['interval_value'] ?? 0);
|
|
$intervalUnit = (string) ($input['interval_unit'] ?? 'minutes');
|
|
|
|
if ($name === '') {
|
|
return 'Bitte einen Namen für das Event angeben.';
|
|
}
|
|
if (mb_strlen($name) > 100) {
|
|
return 'Der Name darf höchstens 100 Zeichen lang sein.';
|
|
}
|
|
if ($message === '') {
|
|
return 'Bitte eine Nachricht angeben.';
|
|
}
|
|
if (mb_strlen($message) > 3900) {
|
|
return 'Die Nachricht darf höchstens 3900 Zeichen lang sein.';
|
|
}
|
|
if ($channelId <= 0) {
|
|
return 'Bitte einen Kanal auswählen.';
|
|
}
|
|
if ($roleId <= 0) {
|
|
return 'Bitte eine Rolle auswählen.';
|
|
}
|
|
if (!in_array($intervalUnit, ['minutes', 'hours', 'days'], true)) {
|
|
return 'Ungültige Einheit für die Wiederholung.';
|
|
}
|
|
if ($intervalValue < 0) {
|
|
return 'Die Wiederholung darf nicht negativ sein.';
|
|
}
|
|
|
|
// Der Bot erwartet "TT.MM.JJJJ HH:MM" und rechnet selbst in einen Timestamp um (siehe
|
|
// create_event()) - hier wird nur geprueft, dass es ueberhaupt ein gueltiges Datum ist.
|
|
if (preg_match('/^(\d{2})\.(\d{2})\.(\d{4}) (\d{2}):(\d{2})$/', $nextRunRaw, $m) !== 1
|
|
|| !checkdate((int) $m[2], (int) $m[1], (int) $m[3])
|
|
|| (int) $m[4] > 23 || (int) $m[5] > 59) {
|
|
return 'Bitte einen gültigen Zeitpunkt für die erste Erinnerung angeben.';
|
|
}
|
|
|
|
return [
|
|
'name' => $name,
|
|
'message' => $message,
|
|
'channel_id' => $channelId,
|
|
'role_id' => $roleId,
|
|
'next_run_raw' => $nextRunRaw,
|
|
'interval_seconds' => event_interval_to_seconds($intervalValue, $intervalUnit),
|
|
];
|
|
}
|
|
|
|
/**
|
|
* Formatiert ein Wiederholungs-Intervall (Sekunden) ausgeschrieben: 0 = einmalig, sonst die
|
|
* groesste glatte Einheit (Tage/Stunden/Minuten).
|
|
*/
|
|
/** Ein Event anhand seiner ID (null, wenn unbekannt oder der Bot nicht erreichbar ist). */
|
|
function event_by_id(int $eventId): ?array
|
|
{
|
|
try {
|
|
foreach (fetch_events() as $event) {
|
|
if ((int) ($event['event_id'] ?? 0) === $eventId) {
|
|
return $event;
|
|
}
|
|
}
|
|
} catch (Throwable $e) {
|
|
// nur fuers Log gebraucht
|
|
}
|
|
return null;
|
|
}
|
|
|
|
/** Kanal fuers Log: "#name" statt roher ID (Fallback: Discord-Erwaehnung). */
|
|
function event_log_channel(int|string|null $channelId): string
|
|
{
|
|
static $names = null;
|
|
$channelId = (string) $channelId;
|
|
if ($channelId === '' || $channelId === '0') {
|
|
return '';
|
|
}
|
|
if ($names === null) {
|
|
try {
|
|
$names = array_column(fetch_guild_channels(), 'name', 'channel_id');
|
|
} catch (Throwable $e) {
|
|
$names = [];
|
|
}
|
|
}
|
|
return isset($names[$channelId]) ? '#' . $names[$channelId] : '<#' . $channelId . '>';
|
|
}
|
|
|
|
/** Rolle fuers Log: "@name" statt roher ID (Fallback: Discord-Erwaehnung). */
|
|
function event_log_role(int|string|null $roleId): string
|
|
{
|
|
static $names = null;
|
|
$roleId = (string) $roleId;
|
|
if ($roleId === '' || $roleId === '0') {
|
|
return '';
|
|
}
|
|
if ($names === null) {
|
|
try {
|
|
$names = array_column(fetch_guild_roles(), 'name', 'role_id');
|
|
} catch (Throwable $e) {
|
|
$names = [];
|
|
}
|
|
}
|
|
return isset($names[$roleId]) ? '@' . $names[$roleId] : '<@&' . $roleId . '>';
|
|
}
|
|
|
|
function event_interval_label(int $seconds): string
|
|
{
|
|
if ($seconds <= 0) {
|
|
return 'Einmalig';
|
|
}
|
|
if ($seconds % 86400 === 0) {
|
|
$days = intdiv($seconds, 86400);
|
|
if ($days === 1) {
|
|
return 'Täglich';
|
|
}
|
|
if ($days === 7) {
|
|
return 'Wöchentlich';
|
|
}
|
|
return 'Alle ' . $days . ' Tage';
|
|
}
|
|
if ($seconds % 3600 === 0) {
|
|
$hours = intdiv($seconds, 3600);
|
|
return $hours === 1 ? 'Stündlich' : 'Alle ' . $hours . ' Stunden';
|
|
}
|
|
|
|
$minutes = max(1, intdiv($seconds, 60));
|
|
return $minutes === 1 ? 'Jede Minute' : 'Alle ' . $minutes . ' Minuten';
|
|
}
|
|
|
|
/**
|
|
* Zerlegt ein Intervall in Wert + Einheit fuer das Bearbeiten-Formular (z.B. 604800 -> [7, 'days']).
|
|
*
|
|
* @return array{value: int, unit: string}
|
|
*/
|
|
function event_interval_parts(int $seconds): array
|
|
{
|
|
if ($seconds <= 0) {
|
|
return ['value' => 0, 'unit' => 'minutes'];
|
|
}
|
|
if ($seconds % 86400 === 0) {
|
|
return ['value' => intdiv($seconds, 86400), 'unit' => 'days'];
|
|
}
|
|
if ($seconds % 3600 === 0) {
|
|
return ['value' => intdiv($seconds, 3600), 'unit' => 'hours'];
|
|
}
|
|
|
|
return ['value' => max(1, intdiv($seconds, 60)), 'unit' => 'minutes'];
|
|
}
|
|
|
|
/**
|
|
* Rechnet Wert + Einheit aus dem Formular in Sekunden um (Gegenstueck zu event_interval_parts()).
|
|
*/
|
|
function event_interval_to_seconds(int $value, string $unit): int
|
|
{
|
|
if ($value <= 0) {
|
|
return 0;
|
|
}
|
|
|
|
return match ($unit) {
|
|
'days' => $value * 86400,
|
|
'hours' => $value * 3600,
|
|
default => $value * 60,
|
|
};
|
|
}
|
|
|
|
/**
|
|
* "in 3 Tagen" / "vor 5 Minuten" - kurze, relative Zeitangabe passend zu Discords <t:...:R>,
|
|
* damit die Website dieselbe Information zeigt wie die Bot-Uebersicht.
|
|
*/
|
|
function event_relative_time(int $timestamp): string
|
|
{
|
|
$diff = $timestamp - time();
|
|
$past = $diff < 0;
|
|
$diff = abs($diff);
|
|
|
|
if ($diff < 60) {
|
|
$text = 'weniger als einer Minute';
|
|
} elseif ($diff < 3600) {
|
|
$minutes = intdiv($diff, 60);
|
|
$text = $minutes . ($minutes === 1 ? ' Minute' : ' Minuten');
|
|
} elseif ($diff < 86400) {
|
|
$hours = intdiv($diff, 3600);
|
|
$text = $hours . ($hours === 1 ? ' Stunde' : ' Stunden');
|
|
} else {
|
|
$days = intdiv($diff, 86400);
|
|
$text = $days . ($days === 1 ? ' Tag' : ' Tagen');
|
|
}
|
|
|
|
return $past ? 'vor ' . $text : 'in ' . $text;
|
|
}
|