} }); // Handle close event (Not exactly gracefully, but consider it handled... /** @var \Discord\WebSockets\WebSocket $websocket */ /** @var \Sluggard\SluggardApp $app */ $websocket->on("close", function ($websocket, $reason, $discord) use($app) { $app->log->err("Connection was closed: " . $reason); die; }); // Handle close event (Not exactly gracefully, but consider it handled... /** @var \Discord\WebSockets\WebSocket $websocket */ /** @var \Sluggard\SluggardApp $app */ $websocket->on("error", function ($error, $websocket) use($app) { $app->log->err("Error: {$error}"); }); // Handle reconnect event /** @var \Sluggard\SluggardApp $app */ $websocket->on("reconnect", function () use($app) { $app->log->info("Reconnecting to Discord"); }); // Handle reconnected event /** @var \Sluggard\SluggardApp $app */ $websocket->on("reconnected", function () use($app) { $app->log->info("Reconnected to Discord"); }); // Setup the cache (Only works aslong as the bot is running) \Discord\Cache\Cache::setCache(new \Discord\Cache\Drivers\ArrayCacheDriver()); // Add some config options to Guzzle.. \Discord\Helpers\Guzzle::addGuzzleOptions(array("http_errors" => false, "allow_redirects" => true)); // Start the bot $websocket->run();
/** * Starts the bot. * * @return void */ public function start() { // set_error_handler(function ($errno, $errstr) { // if (!(error_reporting() & $errno)) { // return; // } // echo "[Error] {$errno} {$errstr}\r\n"; // throw new \Exception($errstr, $errno); // }, E_ALL); $this->websocket->on(Event::MESSAGE_CREATE, function ($message, $discord, $new) { $config = Config::getConfig($this->configfile); if (substr($message->content, 0, strlen($config['prefix'])) == $config['prefix']) { foreach ($this->commands as $command => $data) { $parts = []; $content = explode(' ', $message->content); foreach ($content as $index => $c) { foreach (explode("\n", $c) as $p) { $parts[] = $p; } } $content = $parts; if ($content[0] == $config['prefix'] . $command) { array_shift($content); $user_perms = @$config['perms']['perms'][$message->author->id]; if (empty($user_perms)) { $user_perms = $config['perms']['default']; } if ($user_perms >= $data['perms']) { try { $data['class']::handleMessage($message, $content, $new, $config, $this); $this->log->addInfo("{$message->author->username}#{$message->author->discriminator} ({$message->author}) ran command {$config['prefix']}{$command}", $content); } catch (\Throwable $e) { try { $this->log->addError("Error running the command {$config['prefix']}{$command}", ['message' => $e->getMessage()]); $message->reply("There was an error running the command. `{$e->getMessage()}`"); } catch (\Throwable $e2) { } } } else { try { $message->reply('You do not have permission to do this!'); } catch (\Throwable $e2) { } $this->log->addWarning("{$message->author->username}#{$message->author->discriminator} ({$message->author}) attempted to run command {$config['prefix']}{$command}", $content); } } } } }); $this->websocket->on(Event::MESSAGE_CREATE, function ($message, $discord, $new) { $triggers = ['bless up', ':pray:', '🙏']; if (Str::contains(strtolower($message->content), $triggers) && $message->author->id != $discord->id) { $config = Config::getConfig($this->configfile); $content = explode(' ', $message->content); Arr::forget($content, 0); Khaled::handleMessage($message, $content, $new, $config, $this); } }); $this->websocket->on(Event::MESSAGE_CREATE, function ($message, $discord, $new) { if ($message->author->id == '81726071573061632' && strtolower($message->content) == 'we dem') { $message->channel->sendMessage('BOIZ'); } }); $this->websocket->on('ready', function ($discord) { $this->log->addInfo('WebSocket is ready.'); $discord->updatePresence($this->websocket, 'DiscordPHP ' . Discord::VERSION, false); }); $this->websocket->on('error', function ($error, $ws) { $this->log->addError("WebSocket encountered an error", [$error->getMessage()]); }); // $this->websocket->on('heartbeat', function ($epoch) { // echo "Heartbeat at {$epoch}\r\n"; // }); $this->websocket->on('close', function ($op, $reason) { $this->log->addWarning("WebSocket closed.", ['code' => $op, 'reason' => $reason]); }); $this->websocket->on('reconnecting', function () { $this->log->addInfo('WebSocket is reconnecting...'); }); $this->websocket->on('reconnected', function () { $this->log->addInfo('WebSocket has reconnected.'); }); $config = Config::getConfig($this->configfile); if (isset($config['cache']) && $config['cache'] == 'redis') { Cache::setCache(new RedisCacheDriver('localhost')); } if (isset($config['carbon_bot']) && $config['carbon_bot']['enabled']) { $guzzle = new Client(['http_errors' => false]); $body = ['key' => $config['carbon_bot']['key']]; $this->log->addInfo('Enabling Carbon server count updates...'); $carbonHeartbeat = function () use($guzzle, &$body) { $body['servercount'] = $this->discord->guilds->count(); $this->log->addDebug('Sending Carbon server count update...'); $request = new Request('POST', 'https://www.carbonitex.net/discord/data/botdata.php', ['Content-Type' => 'application/json'], json_encode($body)); $response = $guzzle->send($request); if ($response->getStatusCode() !== 200) { $this->log->addWarning('Carbon server count update failed.', ['status' => $response->getStatusCode(), 'reason' => $response->getReasonPhrase()]); } else { $this->log->addDebug('Sent Carbon server count update successfully.'); } }; $carbonHeartbeat(); $this->websocket->loop->addPeriodicTimer(60, $carbonHeartbeat); } $this->websocket->run(); }
/** * Sovereign constructor. * @param Container $container */ public function __construct(Container $container) { $this->container = $container; $this->log = $container->get('log'); $this->globalConfig = $container->get('config'); $this->db = $container->get('db'); $this->curl = $container->get('curl'); $this->settings = $container->get('settings'); $this->permissions = $container->get('permissions'); $this->users = $container->get('users'); $this->extras['startTime'] = time(); $this->extras['memberCount'] = 0; $this->extras['guildCount'] = 0; $this->pool = new \Pool(count($this->onMessage), \Worker::class); $this->timers = new \Pool(count($this->onTimer), \Worker::class); // Init Discord and Websocket $this->log->addInfo('Initializing Discord and Websocket connections..'); $this->discord = Discord::createWithBotToken($this->globalConfig->get('token', 'bot')); Cache::setCache(new ArrayCacheDriver()); $this->websocket = new WebSocket($this->discord); }