Autosave: 20260214-202505

This commit is contained in:
Flatlogic Bot 2026-02-14 20:25:06 +00:00
parent 8c4042bed6
commit bdc277f00b
3 changed files with 937 additions and 302 deletions

390
bot.php
View File

@ -48,6 +48,7 @@ $discord = new Discord([
]);
$voiceClient = null;
$joiningGuilds = [];
$ffmpegPath = trim((string)shell_exec("command -v ffmpeg"));
function logToDb($message, $level = 'info') {
@ -67,6 +68,14 @@ $discord->on('ready', function (Discord $discord) {
$db = db();
$db->prepare("INSERT INTO bot_settings (setting_key, setting_value) VALUES ('bot_status', 'online') ON DUPLICATE KEY UPDATE setting_value = 'online'")->execute();
// Listen for voice state updates to debug disconnecting issues
$discord->on(Event::VOICE_STATE_UPDATE, function ($state, Discord $discord) {
if ($state->user_id == $discord->id) {
echo "Bot voice state updated: Channel=" . ($state->channel_id ?? 'None') . " Session=" . ($state->session_id ?? 'None') . "\n";
logToDb("Bot voice state updated: Channel=" . ($state->channel_id ?? 'None'));
}
});
// Periodic timer for Sahur and Alarms
$discord->getLoop()->addPeriodicTimer(60, function () use ($discord) {
$now = date('H:i');
@ -110,6 +119,7 @@ function registerCommands(Discord $discord) {
CommandBuilder::new()->setName('setalarm')->setDescription('Set your personal alarm audio link')
->addOption((new Option($discord))->setName('link')->setDescription('Audio URL for the alarm')->setType(Option::STRING)->setRequired(true)),
CommandBuilder::new()->setName('help')->setDescription('Show help information'),
CommandBuilder::new()->setName('ping')->setDescription('Check if bot is responsive'),
];
foreach ($commands as $command) {
@ -173,59 +183,92 @@ function streamAudio(VoiceClient $vc, string $url, $interaction = null) {
$interaction->updateOriginalResponse(MessageBuilder::new()->setContent("🎶 **Now Playing:** $title"));
}
$playFunc = function () use ($vc, $streamUrl, $title, $interaction) {
$isReady = method_exists($vc, 'isReady') ? $vc->isReady() : $vc->ready;
echo "Attempting to play $title. VC Ready: " . ($isReady ? 'Yes' : 'No') . "\n";
if (!$isReady) {
echo "Voice client not ready yet for $title, waiting for ready event...\n";
$vc->once('ready', function() use ($vc, $streamUrl, $title, $interaction) {
echo "Voice client finally ready for $title, playing now.\n";
$vc->playFile($streamUrl);
});
return;
}
$vc->playFile($streamUrl)->then(function() use ($title) {
echo "Finished playing $title\n";
}, function($e) use ($vc, $streamUrl, $title, $interaction) {
echo "Error playing $title: " . $e->getMessage() . "\n";
logToDb("Error playing $title: " . $e->getMessage(), 'error');
$playFunc = function ($isFallback = false) use ($vc, $streamUrl, $title, $interaction) {
try {
$isReady = method_exists($vc, 'isReady') ? $vc->isReady() : ($vc->ready ?? false);
echo "Attempting to play $title. VC Ready: " . ($isReady ? 'Yes' : 'No') . " (Fallback: " . ($isFallback ? 'Yes' : 'No') . ")\n";
if (strpos($e->getMessage(), 'not ready') !== false) {
echo "Retrying $title in 2 seconds due to 'not ready' error...\n";
global $discord;
$discord->getLoop()->addTimer(2.0, function() use ($vc, $streamUrl, $title, $interaction) {
$vc->playFile($streamUrl);
});
if (!$isReady && !$isFallback) {
echo "Voice client not ready yet for $title, waiting for ready event...\n";
return;
}
if ($interaction) {
$interaction->updateOriginalResponse(MessageBuilder::new()->setContent("❌ Error playing: $title. " . $e->getMessage()));
}
});
echo "Calling playFile for $title. URL: " . substr($streamUrl, 0, 50) . "...\n";
$vc->playFile($streamUrl)->then(function() use ($title) {
echo "Finished playing $title\n";
}, function($e) use ($vc, $streamUrl, $title) {
echo "Error playing $title: " . $e->getMessage() . "\n";
logToDb("Error playing $title: " . $e->getMessage(), 'error');
if (strpos($e->getMessage(), 'not ready') !== false) {
echo "Retrying $title in 2 seconds due to 'not ready' error...\n";
$vc->discord->getLoop()->addTimer(2.0, function() use ($vc, $streamUrl) {
try {
$isReady = method_exists($vc, 'isReady') ? $vc->isReady() : ($vc->ready ?? false);
if ($isReady) {
$vc->playFile($streamUrl);
}
} catch (\Throwable $e) {}
});
}
});
} catch (\Throwable $e) {
echo "Exception in playFunc for $title: " . $e->getMessage() . "\n";
}
};
$isReady = method_exists($vc, 'isReady') ? $vc->isReady() : $vc->ready;
$isReady = method_exists($vc, 'isReady') ? $vc->isReady() : ($vc->ready ?? false);
if ($isReady) {
$playFunc();
} else {
echo "Voice client not ready yet for $title (initial check), waiting for ready event...\n";
$vc->once('ready', $playFunc);
echo "Voice client not ready yet for $title (initial check), adding listeners...\n";
// Safety timeout: if not ready in 15s, fail
global $discord;
$discord->getLoop()->addTimer(15.0, function () use ($vc, $interaction, $title, $playFunc) {
$isReady = method_exists($vc, 'isReady') ? $vc->isReady() : $vc->ready;
$fallbackTimer = $vc->discord->getLoop()->addTimer(7.0, function() use ($vc, $playFunc, $title) {
$isReady = method_exists($vc, 'isReady') ? $vc->isReady() : ($vc->ready ?? false);
if (!$isReady) {
$vc->removeListener('ready', $playFunc);
echo "Timed out waiting for voice client to be ready for $title\n";
if ($interaction) {
$interaction->updateOriginalResponse(MessageBuilder::new()->setContent("❌ Error: Voice client timed out waiting to be ready."));
}
echo "Still not ready after 7s for $title, trying playFunc as fallback.\n";
$playFunc(true);
}
});
$safetyTimer = $vc->discord->getLoop()->addTimer(45.0, function () use ($vc, $interaction, $title, $fallbackTimer) {
try {
$vc->discord->getLoop()->cancelTimer($fallbackTimer);
$isReady = method_exists($vc, 'isReady') ? $vc->isReady() : ($vc->ready ?? false);
if (!$isReady) {
echo "Timed out waiting for voice client to be ready for $title after 45s\n";
logToDb("Voice client timeout for $title after 45s", 'warning');
if ($interaction) {
$interaction->updateOriginalResponse(MessageBuilder::new()->setContent("⚠️ Voice client timed out waiting to be ready. Please try using `/out` then `/join` again."));
try { $vc->close(); } catch (\Exception $e) {}
}
}
} catch (\Exception $e) {
echo "Error in safety timer: " . $e->getMessage() . "\n";
}
});
$vc->once('ready', function() use ($vc, $playFunc, $fallbackTimer, $safetyTimer) {
$vc->discord->getLoop()->cancelTimer($fallbackTimer);
$vc->discord->getLoop()->cancelTimer($safetyTimer);
$playFunc();
});
$vc->once('close', function() use ($vc, $interaction, $title, $fallbackTimer, $safetyTimer) {
$vc->discord->getLoop()->cancelTimer($fallbackTimer);
$vc->discord->getLoop()->cancelTimer($safetyTimer);
echo "Voice client closed for $title while waiting for ready.\n";
if ($interaction) {
$interaction->updateOriginalResponse(MessageBuilder::new()->setContent("⚠️ Voice connection closed before it was ready."));
}
});
$vc->once('error', function ($e) use ($title) {
echo "Voice client encountered error while waiting for ready for $title: " . $e->getMessage() . "\n";
logToDb("Voice client error for $title: " . $e->getMessage(), 'error');
});
}
} else {
echo "Failed to fetch stream URL for $url. Code: $code\nError Output: $errorOutput\n";
@ -240,20 +283,51 @@ function playSahur(Discord $discord, $vcId) {
$channel = $discord->getChannel($vcId);
if (!$channel) return;
$discord->joinVoiceChannel($channel)->then(function (VoiceClient $vc) {
$vc = $discord->getVoiceClient($channel->guild_id);
if ($vc && (string)$vc->channel->id === (string)$channel->id) {
echo "Sahur: Already in channel, playing directly.\n";
$db = db();
$source = $db->query("SELECT setting_value FROM bot_settings WHERE setting_key = 'sahur_source'")->fetchColumn() ?: 'sahur.mp3';
if (filter_var($source, FILTER_VALIDATE_URL)) {
streamAudio($vc, $source);
} else if (file_exists($source)) {
if ($vc->ready) {
$vc->playFile($source);
} else {
$vc->once('ready', function () use ($vc, $source) {
$vc->playFile($source);
}
return;
}
if ($vc) {
try { $vc->close(); } catch (\Throwable $e) {}
}
$delay = $vc ? 3.0 : 0;
$discord->getLoop()->addTimer($delay, function() use ($discord, $channel) {
if ($discord->getVoiceClient($channel->guild_id)) return;
$discord->joinVoiceChannel($channel, false, false)->then(function (VoiceClient $vc) {
$db = db();
$source = $db->query("SELECT setting_value FROM bot_settings WHERE setting_key = 'sahur_source'")->fetchColumn() ?: 'sahur.mp3';
$playAction = function() use ($vc, $source) {
if (filter_var($source, FILTER_VALIDATE_URL)) {
streamAudio($vc, $source);
} else if (file_exists($source)) {
$vc->playFile($source);
}
};
$isReady = method_exists($vc, 'isReady') ? $vc->isReady() : ($vc->ready ?? false);
if ($isReady) {
$playAction();
} else {
$vc->once('ready', $playAction);
$discord = $vc->discord;
$discord->getLoop()->addTimer(10.0, function() use ($vc, $playAction) {
$isReady = method_exists($vc, 'isReady') ? $vc->isReady() : ($vc->ready ?? false);
if (!$isReady) $playAction();
});
}
}
});
});
}
@ -261,8 +335,39 @@ function playAlarm(Discord $discord, $alarm) {
$channel = $discord->getChannel($alarm['channel_id']);
if (!$channel) return;
$discord->joinVoiceChannel($channel)->then(function (VoiceClient $vc) use ($alarm) {
$vc = $discord->getVoiceClient($channel->guild_id);
if ($vc && (string)$vc->channel->id === (string)$channel->id) {
echo "Alarm: Already in channel, playing directly.\n";
streamAudio($vc, $alarm['audio_url']);
return;
}
if ($vc) {
try { $vc->close(); } catch (\Throwable $e) {}
}
$delay = $vc ? 3.0 : 0;
$discord->getLoop()->addTimer($delay, function() use ($discord, $channel, $alarm) {
if ($discord->getVoiceClient($channel->guild_id)) {
$vc = $discord->getVoiceClient($channel->guild_id);
if ((string)$vc->channel->id === (string)$channel->id) streamAudio($vc, $alarm['audio_url']);
return;
}
$discord->joinVoiceChannel($channel, false, false)->then(function (VoiceClient $vc) use ($alarm) {
$isReady = method_exists($vc, 'isReady') ? $vc->isReady() : ($vc->ready ?? false);
if ($isReady) {
streamAudio($vc, $alarm['audio_url']);
} else {
$vc->once('ready', function() use ($vc, $alarm) {
streamAudio($vc, $alarm['audio_url']);
});
$discord = $vc->discord;
$discord->getLoop()->addTimer(10.0, function() use ($vc, $alarm) {
$isReady = method_exists($vc, 'isReady') ? $vc->isReady() : ($vc->ready ?? false);
if (!$isReady) streamAudio($vc, $alarm['audio_url']);
});
}
});
});
}
@ -273,6 +378,10 @@ $discord->on(Event::INTERACTION_CREATE, function (Interaction $interaction, Disc
logToDb("Received interaction: $command from " . $interaction->member->user->username);
switch ($command) {
case 'ping':
$interaction->respondWithMessage(MessageBuilder::new()->setContent("Pong! 🏓"));
break;
case 'help':
$interaction->respondWithMessage(MessageBuilder::new()->setContent(
"**AsepSahur Bot Commands:**\n" .
@ -282,6 +391,7 @@ $discord->on(Event::INTERACTION_CREATE, function (Interaction $interaction, Disc
"`/settime [HH:MM]` - Set your alarm time\n" .
"`/setalarm [url]` - Set your alarm audio\n" .
"`/status` - Check bot status\n" .
"`/ping` - Test bot responsiveness\n" .
"`/out` - Make bot leave voice channel"
));
break;
@ -299,28 +409,70 @@ $discord->on(Event::INTERACTION_CREATE, function (Interaction $interaction, Disc
return;
}
$interaction->acknowledge();
$discord->joinVoiceChannel($userChannel)->then(function (VoiceClient $vc) use ($interaction, $userChannel) {
$interaction->updateOriginalResponse(MessageBuilder::new()->setContent("Joined " . $vc->channel->name));
$vc->on('close', function() use ($userChannel) {
echo "Voice client closed for channel " . $userChannel->name . "\n";
logToDb("Voice client closed for channel " . $userChannel->name);
});
$vc->on('error', function($e) use ($userChannel) {
echo "Voice client error in channel " . $userChannel->name . ": " . $e->getMessage() . "\n";
logToDb("Voice client error in channel " . $userChannel->name . ": " . $e->getMessage(), 'error');
});
}, function ($e) use ($interaction) {
$interaction->updateOriginalResponse(MessageBuilder::new()->setContent("Failed to join: " . $e->getMessage()));
});
break;
try {
$vc = $discord->getVoiceClient($interaction->guild_id);
if ($vc && (string)$vc->channel->id === (string)$userChannel->id) {
$interaction->updateOriginalResponse(MessageBuilder::new()->setContent("Already in " . $vc->channel->name));
return;
}
case 'out':
$vc = $discord->getVoiceClient($interaction->guild_id);
if ($vc) {
$vc->close();
$interaction->respondWithMessage(MessageBuilder::new()->setContent("Left voice channel."));
} else {
$interaction->respondWithMessage(MessageBuilder::new()->setContent("I'm not in a voice channel."));
global $joiningGuilds;
if (isset($joiningGuilds[$interaction->guild_id])) {
$interaction->updateOriginalResponse(MessageBuilder::new()->setContent("❌ A join request is already in progress. Please wait."));
return;
}
$joiningGuilds[$interaction->guild_id] = true;
if ($vc) {
echo "Closing existing VC for guild " . $interaction->guild_id . " before joining new channel.\n";
$vc->close();
}
$delay = $vc ? 3.0 : 0;
echo "Joining channel: " . $userChannel->name . " (Join command, delay: $delay)\n";
$discord->getLoop()->addTimer($delay, function() use ($discord, $userChannel, $interaction, &$joiningGuilds) {
$vc = $discord->getVoiceClient($interaction->guild_id);
if ($vc) {
unset($joiningGuilds[$interaction->guild_id]);
if ((string)$vc->channel->id === (string)$userChannel->id) {
$interaction->updateOriginalResponse(MessageBuilder::new()->setContent("Joined " . $vc->channel->name));
return;
}
}
$responded = false;
$joinTimeout = $discord->getLoop()->addTimer(20.0, function() use ($interaction, $discord, &$responded, &$joiningGuilds) {
unset($joiningGuilds[$interaction->guild_id]);
if (!$responded) {
$interaction->updateOriginalResponse(MessageBuilder::new()->setContent("❌ Joining voice channel timed out (20s)."));
$responded = true;
}
});
$discord->joinVoiceChannel($userChannel, false, false)->then(function (VoiceClient $vc) use ($interaction, $discord, $joinTimeout, &$responded, &$joiningGuilds, $userChannel) {
unset($joiningGuilds[$interaction->guild_id]);
if ($responded) return;
$discord->getLoop()->cancelTimer($joinTimeout);
$responded = true;
$interaction->updateOriginalResponse(MessageBuilder::new()->setContent("Joined " . $vc->channel->name));
$vc->on('close', function() use ($userChannel) {
echo "Voice client closed for channel " . $userChannel->name . "\n";
});
}, function ($e) use ($interaction, $discord, $joinTimeout, &$responded, &$joiningGuilds) {
unset($joiningGuilds[$interaction->guild_id]);
if ($responded) return;
$discord->getLoop()->cancelTimer($joinTimeout);
$responded = true;
echo "Error joining VC: " . $e->getMessage() . "\n";
$interaction->updateOriginalResponse(MessageBuilder::new()->setContent("❌ Error joining voice channel: " . $e->getMessage()));
});
});
} catch (\Throwable $e) {
global $joiningGuilds;
unset($joiningGuilds[$interaction->guild_id]);
$interaction->updateOriginalResponse(MessageBuilder::new()->setContent("❌ Error: " . $e->getMessage()));
}
break;
@ -334,37 +486,71 @@ $discord->on(Event::INTERACTION_CREATE, function (Interaction $interaction, Disc
$interaction->acknowledge();
$vc = $discord->getVoiceClient($interaction->guild_id);
if ($vc && $vc->channel->id === $userChannel->id) {
echo "Already in correct channel. Checking readiness...\n";
streamAudio($vc, $url, $interaction);
} else {
if ($vc) {
echo "Voice client in wrong channel or state, closing...\n";
$vc->close();
}
try {
$vc = $discord->getVoiceClient($interaction->guild_id);
echo "Joining channel: " . $userChannel->name . "\n";
// Small delay if we just closed
$delay = $vc ? 0.8 : 0.1;
$discord->getLoop()->addTimer($delay, function() use ($discord, $userChannel, $interaction, $url) {
$discord->joinVoiceChannel($userChannel)->then(function (VoiceClient $vc) use ($interaction, $url, $userChannel) {
echo "Joined voice channel, now streaming...\n";
$vc->on('close', function() use ($userChannel) {
echo "Voice client closed for channel " . $userChannel->name . "\n";
logToDb("Voice client closed for channel " . $userChannel->name);
if ($vc && (string)$vc->channel->id === (string)$userChannel->id) {
echo "Already in correct channel. Streaming...\n";
streamAudio($vc, $url, $interaction);
} else {
global $joiningGuilds;
if (isset($joiningGuilds[$interaction->guild_id])) {
$interaction->updateOriginalResponse(MessageBuilder::new()->setContent("❌ A join request is already in progress. Please wait."));
return;
}
$joiningGuilds[$interaction->guild_id] = true;
if ($vc) {
echo "Voice client in wrong channel, closing and rejoining...\n";
$vc->close();
}
$delay = $vc ? 3.0 : 0;
echo "Joining channel: " . $userChannel->name . " (Play command, delay: $delay)\n";
$discord->getLoop()->addTimer($delay, function() use ($discord, $userChannel, $interaction, $url, &$joiningGuilds) {
$vc = $discord->getVoiceClient($interaction->guild_id);
if ($vc) {
unset($joiningGuilds[$interaction->guild_id]);
if ((string)$vc->channel->id === (string)$userChannel->id) {
streamAudio($vc, $url, $interaction);
} else {
$interaction->updateOriginalResponse(MessageBuilder::new()->setContent("❌ Connection busy or in another channel. Try again in a moment."));
}
return;
}
$responded = false;
$joinTimeout = $discord->getLoop()->addTimer(20.0, function() use ($interaction, $discord, &$responded, &$joiningGuilds) {
unset($joiningGuilds[$interaction->guild_id]);
if (!$responded) {
$interaction->updateOriginalResponse(MessageBuilder::new()->setContent("❌ Joining voice channel timed out (20s). Try again."));
$responded = true;
}
});
$vc->on('error', function($e) use ($userChannel) {
echo "Voice client error in channel " . $userChannel->name . ": " . $e->getMessage() . "\n";
logToDb("Voice client error in channel " . $userChannel->name . ": " . $e->getMessage(), 'error');
$discord->joinVoiceChannel($userChannel, false, false)->then(function (VoiceClient $vc) use ($interaction, $discord, $url, $joinTimeout, &$responded, &$joiningGuilds) {
unset($joiningGuilds[$interaction->guild_id]);
if ($responded) return;
$discord->getLoop()->cancelTimer($joinTimeout);
$responded = true;
echo "Joined voice channel, now streaming...\n";
streamAudio($vc, $url, $interaction);
}, function ($e) use ($interaction, $discord, $joinTimeout, &$responded, &$joiningGuilds) {
unset($joiningGuilds[$interaction->guild_id]);
if ($responded) return;
$discord->getLoop()->cancelTimer($joinTimeout);
$responded = true;
echo "Error joining VC: " . $e->getMessage() . "\n";
$interaction->updateOriginalResponse(MessageBuilder::new()->setContent("❌ Error joining voice channel: " . $e->getMessage()));
});
streamAudio($vc, $url, $interaction);
}, function ($e) use ($interaction) {
echo "Error joining VC: " . $e->getMessage() . "\n";
$interaction->updateOriginalResponse(MessageBuilder::new()->setContent("❌ Error joining voice channel: " . $e->getMessage()));
});
});
}
} catch (\Throwable $e) {
global $joiningGuilds;
unset($joiningGuilds[$interaction->guild_id]);
echo "Fatal error in play command: " . $e->getMessage() . "\n";
$interaction->updateOriginalResponse(MessageBuilder::new()->setContent("❌ Fatal error: " . $e->getMessage()));
}
break;
@ -378,6 +564,20 @@ $discord->on(Event::INTERACTION_CREATE, function (Interaction $interaction, Disc
}
break;
case 'out':
$vc = $discord->getVoiceClient($interaction->guild_id);
if ($vc) {
try {
$vc->close();
$interaction->respondWithMessage(MessageBuilder::new()->setContent("Left voice channel."));
} catch (\Throwable $e) {
$interaction->respondWithMessage(MessageBuilder::new()->setContent("Left voice channel."));
}
} else {
$interaction->respondWithMessage(MessageBuilder::new()->setContent("I'm not in a voice channel."));
}
break;
case 'settime':
$time = $interaction->data->options['time']->value;
if (!preg_match('/^([01]?[0-9]|2[0-3]):[0-5][0-9]$/', $time)) {

View File

@ -1 +1 @@
41306
50851

File diff suppressed because one or more lines are too long