Repository navigation
Expand file tree
/
Copy pathlolbot.php
More file actions
341 lines (307 loc) · 13.9 KB
/
Copy pathlolbot.php
File metadata and controls
341 lines (307 loc) · 13.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
#!/usr/bin/env php
<?php
require_once 'bootstrap.php';
dieIfPendingMigration();
use \Revolt\EventLoop;
use Amp\ByteStream;
use Amp\Log\ConsoleFormatter;
use Amp\Log\StreamHandler;
use function Amp\async;
use lolbot\entities\Network;
use Monolog\Logger;
use library\RestAccessLogMiddleware;
use function Amp\Http\Server\Middleware\stackMiddleware;
use knivey\cmdr\Cmdr;
use Crell\Tukio\Dispatcher;
use Crell\Tukio\OrderedListenerProvider;
use Irc\Event\{ChatEvent, PmEvent, KickEvent, ModeEvent, WelcomeEvent};
use lolbot\entities\Ignore;
$logHandler = new StreamHandler(ByteStream\getStdout());
$logHandler->setFormatter(new ConsoleFormatter);
$logHandler->setLevel(\Psr\Log\LogLevel::INFO);
/**
* helper to make replies in cmds easier
* @param \Irc\Event\ChatEvent $args
* @param \Irc\Client $bot
* @param string $prefix
* @return array{0: \Closure(string,?string=): void, 1: \Closure(string,?string=): void}
*/
function makeRepliers(\Irc\Event\ChatEvent $args, \Irc\Client $bot, string $prefix): array {
return [
function (string $msg, ?string $err = null) use ($args, $bot, $prefix) {
if($err == null) {
$bot->pm($args->chan, "\2$prefix:\2 $msg");
} else {
$bot->pm($args->chan, "\2$prefix $err:\2 $msg");
}
},
function (string $msg, ?string $err = null) use ($args, $bot, $prefix) {
if($err == null) {
$bot->notice($args->nick, "\2$prefix:\2 $msg");
} else {
$bot->notice($args->nick, "\2$prefix $err:\2 $msg");
}
}
];
}
require_once 'library/Duration.inc';
require_once 'scripts/notifier/notifier.php';
require_once 'scripts/aidesc/aidesc.php';
//require_once 'scripts/bing/bing.php';
require_once 'scripts/brave/brave.php';
require_once 'scripts/wolfram/wolfram.php';
require_once 'scripts/owncast/owncast.php';
require_once 'scripts/zyzz/zyzz.php';
require_once 'scripts/wiki/wiki.php';
require_once 'scripts/insult/insult.php';
use scripts\bomb_game\bomb_game;
use scripts\lastfm\lastfm;
use scripts\alias\alias;
use scripts\weather\weather;
use scripts\remindme\remindme;
use scripts\tell\tell;
use scripts\seen\seen;
use scripts\codesand\codesand;
use scripts\tools\tools;
use scripts\urbandict\urbandict;
use scripts\help\help;
use scripts\stocks\stocks;
use scripts\crypto\crypto;
use scripts\linktitles\linktitles;
use scripts\youtube\youtube;
use scripts\twitter\twitter;
use scripts\invidious\invidious;
use scripts\github\github;
use scripts\tiktok\tiktok;
use scripts\reddit\reddit;
use scripts\imgur\imgur;
require_once 'scripts/translate/translate.php';
require_once 'scripts/yoda/yoda.php';
require_once 'scripts/user/user.php';
require_once 'scripts/settings/settings.php';
// class file, but required (not left to autoload) so its file-level
// #[Setting] definition is declared before the attribute scan below —
// autoload would only load it at spawn time, after the permanent latch
require_once 'scripts/weather/weather.php';
//copied from Cmdr should give it its own function in there later
/**
* @param array<string> $validOpts
* @return array<string, string|null>
*/
function parseOpts(string &$msg, array $validOpts = []): array {
$opts = [];
$msga = explode(' ', $msg);
$msgb = [];
foreach ($msga as $w) {
if(str_contains($w, "=")) {
list($lhs, $rhs) = explode("=", $w, 2);
} else {
$lhs = $w;
$rhs = null;
}
if(in_array($lhs, $validOpts))
$opts[$lhs] = $rhs;
else
$msgb[] = $w;
}
$msg = implode(' ', $msgb);
return $opts;
}
require_once 'library/Nicks.php';
require_once 'library/Channels.php';
require_once 'library/extract_opts_and_args.php';
// Load every #[Setting] attribute definition from the required scripts
// before any command can run. The scan latch is permanent (functions
// declared after it are never picked up), so this call must stay after
// ALL script requires.
\library\settings\SettingsRegistry::loadAttributeSettings();
\Revolt\EventLoop::setErrorHandler(function(\Throwable $error) {
echo "Uncaught error: " . $error->getMessage() . "\n";
$e = $error->getPrevious() ?? $error;
echo " at " . $e->getFile() . ":" . $e->getLine() . "\n";
echo $e->getTraceAsString() . "\n";
while ($e = $e->getPrevious()) {
echo "Caused by: " . $e->getMessage() . " in " . $e->getFile() . ":" . $e->getLine() . "\n";
}
});
use Symfony\Component\Cache\Adapter\ArrayAdapter;
global $ORMconfig;
$ignoreCache = new ArrayAdapter(defaultLifetime: 5, storeSerialized: false, maxLifetime: 10, maxItems: 100);
function main(): void {
global $entityManager, $config, $logHandler;
$mgr = new \library\BotManager($entityManager);
// Start every existing bot (unless disabled — per-bot or per-network).
$nets = $entityManager->getRepository(Network::class)->findAll();
foreach ($nets as $network) {
if ($network->disabled)
continue;
try {
foreach ($network->getBots() as $bot) {
if ($bot->isDisabled())
continue;
$mgr->spawn($network, $bot);
}
} catch (\Throwable $e) {
// one bad network config (e.g. an unknown pinned auth_engines
// name throwing in the user-system factory) must not kill the
// whole process — log it and skip to the next network
echo "Failed to spawn bots for network {$network->name}: " . $e->getMessage() . "\n";
echo " at " . $e->getFile() . ":" . $e->getLine() . "\n";
}
}
// Global REST server (single listen + control_key), if configured.
$server = null;
if (isset($config['listen'])) {
$logger = new Logger("control");
$logger->pushHandler($logHandler);
// REST log file: daily rotation, control-server output only.
$restLogPath = trim((string)($config['restlog_path'] ?? 'logs/rest.log'));
if ($restLogPath !== '') {
$restLogDir = dirname($restLogPath);
if (!is_dir($restLogDir)) {
@mkdir($restLogDir, 0775, true);
}
try {
// LineFormatter with default settings collapses embedded newlines,
// which keeps crafted request targets from forging log lines.
// Level names parsed here instead of Logger::toMonologLevel()
// so a typo'd restlog_level falls back to INFO instead of
// throwing and disabling the file log.
$restLevel = match (strtoupper(trim((string)($config['restlog_level'] ?? 'INFO')))) {
'DEBUG' => \Monolog\Logger::DEBUG,
'INFO' => \Monolog\Logger::INFO,
'NOTICE' => \Monolog\Logger::NOTICE,
'WARNING' => \Monolog\Logger::WARNING,
'ERROR' => \Monolog\Logger::ERROR,
'CRITICAL' => \Monolog\Logger::CRITICAL,
'ALERT' => \Monolog\Logger::ALERT,
'EMERGENCY' => \Monolog\Logger::EMERGENCY,
default => \Monolog\Logger::INFO,
};
$restLogDays = (int)($config['restlog_days'] ?? 14);
if ($restLogDays <= 0) {
$restLogDays = 14;
}
$restFileHandler = new \Monolog\Handler\RotatingFileHandler(
$restLogPath,
$restLogDays,
$restLevel,
);
$restFileHandler->setFormatter(new \Monolog\Formatter\LineFormatter());
$logger->pushHandler($restFileHandler);
// Stream handlers open lazily on first write; probe now so an
// unwritable path is caught here instead of inside server start.
$logger->info("REST log started");
} catch (\Throwable $e) {
// A log file is not worth killing the bot over; continue stdout-only.
$logger->popHandler();
echo "REST log disabled ({$restLogPath}): " . $e->getMessage() . "\n";
}
}
$server = \Amp\Http\Server\SocketHttpServer::createForDirectAccess($logger);
$server->expose($config['listen']);
$router = new \Amp\Http\Server\Router($server, $logger, new \Amp\Http\Server\DefaultErrorHandler());
$coreKey = is_string($config['control_key'] ?? null) ? $config['control_key'] : '';
// POST /_control/apply {entityType, id, action, data?}
$router->addRoute('POST', '/_control/apply', new \Amp\Http\Server\RequestHandler\ClosureRequestHandler(
function (\Amp\Http\Server\Request $request) use ($mgr, $coreKey) {
if ($coreKey === '' || !hash_equals($coreKey, (string)$request->getHeader('key'))) {
return new \Amp\Http\Server\Response(403, ['content-type' => 'text/plain'], "Invalid key");
}
$payload = json_decode($request->getBody()->buffer(), true);
if (!is_array($payload) || !isset($payload['entityType'], $payload['action'])) {
return new \Amp\Http\Server\Response(400, ['content-type' => 'text/plain'], "Bad payload");
}
$data = null;
if (isset($payload['data']) && is_array($payload['data'])) {
$data = [];
foreach ($payload['data'] as $k => $v) {
$data[(string)$k] = $v;
}
}
$change = new \lolbot\config\ConfigChange(
(string)$payload['entityType'],
isset($payload['id']) ? (int)$payload['id'] : null,
(string)$payload['action'],
$data,
);
\Amp\async(fn() => $mgr->apply($change));
return new \Amp\Http\Server\Response(200, ['content-type' => 'text/plain'], "applied");
}
));
// Manual lifecycle: /_control/reconnect/{botid}, /jump/{botid}, /respawn/{botid}
$makeLifecycle = function (string $method) use ($mgr, $coreKey) {
return new \Amp\Http\Server\RequestHandler\ClosureRequestHandler(
function (\Amp\Http\Server\Request $request) use ($mgr, $coreKey, $method) {
if ($coreKey === '' || !hash_equals($coreKey, (string)$request->getHeader('key'))) {
return new \Amp\Http\Server\Response(403, ['content-type' => 'text/plain'], "Invalid key");
}
$args = $request->getAttribute(\Amp\Http\Server\Router::class);
$rawBotId = is_array($args) && isset($args['botid']) ? $args['botid'] : 0;
$botId = is_numeric($rawBotId) ? (int)$rawBotId : 0;
if (!isset($mgr->clients[$botId])) {
return new \Amp\Http\Server\Response(404, ['content-type' => 'text/plain'], "No such bot");
}
\Amp\async(fn() => match ($method) {
'reconnect' => $mgr->reconnect($botId),
'jump' => $mgr->jump($botId),
'respawn' => $mgr->respawn($botId),
default => null,
});
return new \Amp\Http\Server\Response(200, ['content-type' => 'text/plain'], "$method queued");
}
);
};
$router->addRoute('POST', '/_control/reconnect/{botid}', $makeLifecycle('reconnect'));
$router->addRoute('POST', '/_control/jump/{botid}', $makeLifecycle('jump'));
$router->addRoute('POST', '/_control/respawn/{botid}', $makeLifecycle('respawn'));
// GET /_control/status — JSON live status of all running bots (for the web panel).
$router->addRoute('GET', '/_control/status', new \Amp\Http\Server\RequestHandler\ClosureRequestHandler(
function (\Amp\Http\Server\Request $request) use ($mgr, $coreKey) {
if ($coreKey === '' || !hash_equals($coreKey, (string)$request->getHeader('key'))) {
return new \Amp\Http\Server\Response(403, ['content-type' => 'text/plain'], "Invalid key");
}
$body = json_encode(['bots' => $mgr->allBotStatuses()], JSON_UNESCAPED_SLASHES);
return new \Amp\Http\Server\Response(
200,
['content-type' => 'application/json'],
$body === false ? '{"bots":[]}' : $body,
);
}
));
// Scripts register their routes on the shared server. (Defined in Task 6.)
if (function_exists('\\scripts\\notifier\\notifier_register')) {
\scripts\notifier\notifier_register($router, $mgr);
}
// AI image description endpoint (scripts/aidesc).
if (function_exists('\\scripts\\aidesc\\aidesc_register')) {
\scripts\aidesc\aidesc_register($router, $logger);
}
// Access log wraps the whole router so 404s are logged too
// (Router::addMiddleware would only cover matched routes).
$server->start(
stackMiddleware($router, new RestAccessLogMiddleware($logger)),
new \Amp\Http\Server\DefaultErrorHandler()
);
}
EventLoop::onSignal(SIGINT, function () use ($mgr, $server): void {
shutdown($mgr, $server, "Caught SIGINT GOODBYE!!!!");
});
EventLoop::onSignal(SIGTERM, function () use ($mgr, $server): void {
shutdown($mgr, $server, "Caught SIGTERM GOODBYE!!!!");
});
}
function shutdown(\library\BotManager $mgr, ?\Amp\Http\Server\HttpServer $server, string $msg): void {
echo "shutdown started: $msg\n";
foreach ($mgr->clients as $bot) {
if (!$bot->isConnected) continue;
try { $bot->sendNow("quit :$msg\r\n"); } catch (\Exception $e) { echo "Exception when sending quit\n $e\n"; }
$bot->exit();
}
$server?->stop();
\Amp\delay(0.5);
echo "Stopped?\n";
exit(0);
}
main();
EventLoop::run();