52 lines
1.5 KiB
PHP
52 lines
1.5 KiB
PHP
<?php
|
|
|
|
namespace App\Services;
|
|
|
|
use App\Interfaces\BaseContract;
|
|
use App\Models\Bot;
|
|
use App\Interfaces\BotContract;
|
|
use App\Interfaces\ScriptContract;
|
|
use App\Jobs\RunBot;
|
|
use Cron\CronExpression;
|
|
use Illuminate\Support\Facades\Log;
|
|
|
|
class BotService
|
|
{
|
|
public function run(): void
|
|
{
|
|
$bots = Bot::where('enabled', 1)->get();
|
|
|
|
foreach ($bots as $bot) {
|
|
$cron = new CronExpression($bot->schedule);
|
|
if ($cron->isDue()) {
|
|
$log = $bot->logs()->create([
|
|
'status' => 'pending',
|
|
'started_at' => now(),
|
|
]);
|
|
|
|
try {
|
|
$instance = app($bot->class, ['config' => $bot->config]);
|
|
|
|
if ($instance instanceof BaseContract) {
|
|
RunBot::dispatch(bot_id: $bot->id, log_id: $log->id);
|
|
$log->update([
|
|
'started_at' => now(),
|
|
'status' => 'pending'
|
|
]);
|
|
}
|
|
} catch (\Throwable $e) {
|
|
Log::error("Bot [{$bot->name}] failed: " . $e->getMessage(), ['exception' => $e]);
|
|
|
|
$log->update([
|
|
'finished_at' => now(),
|
|
'status' => 'failed',
|
|
'error' => $e->getMessage(),
|
|
]);
|
|
}
|
|
|
|
Log::info("Bot [{$bot->name}] executed successfully.");
|
|
}
|
|
}
|
|
}
|
|
}
|