38550-vm/bot/worker.php
2026-02-18 05:42:57 +00:00

76 lines
2.5 KiB
PHP

<?php
/**
* Discord Bot Worker Script
* This script runs in the background and processes music requests.
* In a real-world scenario, this would use a library like discord-php
* to maintain a persistent WebSocket connection to Discord.
*/
declare(strict_types=1);
// Ensure we are running from CLI
if (PHP_SAPI !== 'cli') {
die("This script must be run from the command line.\n");
}
require_once __DIR__ . '/../includes/app.php';
echo "[*] Discord Bot Worker started...\n";
add_log('System', 'Worker Started', 'The background bot worker process has initiated.');
$settings = get_settings();
if (empty($settings['discord_token'])) {
echo "[!] WARNING: No Discord Token found in settings. Please add it via the dashboard.\n";
add_log('System', 'Worker Warning', 'Discord Token is missing. Worker is running in simulation mode.');
}
// Keep the process alive
while (true) {
try {
$pdo = db();
// 1. Check for queued requests
$stmt = $pdo->prepare('SELECT * FROM music_requests WHERE status = "queued" ORDER BY created_at ASC LIMIT 1');
$stmt->execute();
$request = $stmt->fetch();
if ($request) {
$id = $request['id'];
$query = $request['query_text'];
$guild = $request['guild_name'];
echo "[+] Processing request #{$id}: '{$query}' for server '{$guild}'\n";
// Start "playing"
$update = $pdo->prepare('UPDATE music_requests SET status = "playing" WHERE id = ?');
$update->execute([$id]);
add_log('Bot', 'Playing', "Now playing: {$query}", $guild);
// Simulation: Wait 10 seconds (in a real bot, this would wait for the audio to finish)
sleep(10);
// Mark as "ended"
$update = $pdo->prepare('UPDATE music_requests SET status = "ended" WHERE id = ?');
$update->execute([$id]);
add_log('Bot', 'Finished', "Finished playing: {$query}", $guild);
echo "[#] Request #{$id} completed.\n";
}
// 2. Refresh settings occasionally (every 30 seconds)
static $last_refresh = 0;
if (time() - $last_refresh > 30) {
$settings = get_settings();
$last_refresh = time();
}
// Sleep to avoid high CPU usage
sleep(2);
} catch (Exception $e) {
echo "[!] ERROR: " . $e->getMessage() . "\n";
add_log('System', 'Worker Error', $e->getMessage());
sleep(10); // Wait longer on error before retry
}
}