public function __construct($id, $config) { parent::__construct($id); $this->qurey_settings['count'] = 50; $this->qurey_settings['include_rts'] = false; $this->qurey_settings['include_entities'] = 1; $this->query_settings['exclude_replies'] = true; $this->settings['account'] = $config['account']; $this->settings['overwrite'] = false; if (!empty($config['overwrite'])) { $this->settings['overwrite'] = $config['overwrite']; } $this->interval = $config['interval']; $this->connection = new \TwitterOAuth($config['consumerKey'], $config['consumerSecret'], $config['oauthKey'], $config['oauthSecret']); $this->setUserTimeline($config['account']); }
protected function caps(Bot $bot) { if (!isset($this->caps[$bot->message['usernameraw']])) { $this->caps[$bot->message['usernameraw']] = array('kills' => 0, 'counter' => 0, 'lastreset' => 0); } if ($this->caps[$bot->message['usernameraw']]['lastreset'] < (time() - 3600)) { if ($this->caps[$bot->message['usernameraw']]['kills'] > 0) $this->caps[$bot->message['usernameraw']]['kills']--; } if ($this->caps[$bot->message['usernameraw']]['lastreset'] < (time() - 120)) { if ($this->caps[$bot->message['usernameraw']]['counter'] > 0) $this->caps[$bot->message['usernameraw']]['counter']--; $this->caps[$bot->message['usernameraw']]['lastreset'] = time(); } $capscount = 0; // don't count whitespace $message = preg_replace('~[\s!?\.]~', '', $bot->message['text']); $charcount = strlen($message); $chars = str_split($bot->message['text']); foreach ($chars as $char) { if (preg_match('~[A-Z]~', $char)) $capscount++; } if (strlen($message) < 6 || ($capscount / $charcount * 100) < $this->config->config['capspercent']) return; $this->caps[$bot->message['usernameraw']]['counter']++; $bot->queue('/whisper "'.$bot->message['usernameraw'].'" '.Core::language()->antispam_no_caps); if ($this->caps[$bot->message['usernameraw']]['counter'] > 2) { $this->caps[$bot->message['usernameraw']]['counter'] = 0; $bot->queue('/tmute '.$bot->message['usernameraw'].' '.pow(2, $this->caps[$bot->message['usernameraw']]['kills']++)); } }
/** * Bot install action * * @param Bot $bot */ public function install(Bot $bot) { $result = $this->call('imbot.register', $bot->getData(), $this->auth); $appsConfig = []; $appsConfig[$_REQUEST['auth']['application_token']] = array('BOT_ID' => $result['result'], 'LANGUAGE_ID' => $_REQUEST['data']['LANGUAGE_ID']); $this->saveParams($appsConfig); }
public function handle(Bot $bot) { if (substr(Module::removeWhisper($bot->message['text']), 0, 5) == '!php ') { if (!Core::compareLevel($bot->lookUpUserID(), 'php.eval')) return $bot->denied(); Core::log()->php = $bot->message['usernameraw'].' used '.Module::removeWhisper($bot->message['text']); eval(substr(Module::removeWhisper($bot->message['text']), 5)); } }
public function handle(Bot $bot) { if ($bot->message['id'] % 500 == 0) $this->cache = array(); if ($bot->message['usernameraw'] == NAME) return; if (substr($bot->message['text'], 0, 8) == '!google ') { $data = $this->search(substr($bot->message['text'], 8)); $bot->queue('Google ['.substr($bot->message['text'], 8).']: http://google.de/search?q='.rawurlencode(substr($bot->message['text'], 8)).' '.Core::language()->get('google_number', array('{number}' => number_format($data['responseData']['cursor']['estimatedResultCount'], 0, Core::language()->decimal_point, Core::language()->thousand_separator)))); $bot->queue('#1: '.strip_tags($data['responseData']['results'][0]['title']).': '.$data['responseData']['results'][0]['unescapedUrl']); } }
public static function notify($notify) { if (preg_match('#RECEIVED|SENT#Uis', $notify)) { $message_id = explode(' ', $notify); self::$bot->invoke($message_id[1]); } else { // echo $notify, "\n"; return; } }
public function handle(Bot $bot) { if ($bot->message['id'] % 500 == 0) $this->cache = array(); if ($bot->message['usernameraw'] == NAME) return; if (preg_match_all('~http://(?:.+\.)?youtu(?:\.be/|be\.com/watch\?(?:.*)v=)([a-zA-Z0-9_-]+?)~U', $bot->message['text'], $matches)) foreach ($matches[1] as $id) { $title = $this->lookUp($id); if ($title !== false) { $bot->queue('Youtube ['.$id.']: '.$title); } } }
public function actionRun() { // Пересчитываем рейтинги $key = 'cron.bot.run.btc_rur'; if (Yii::app()->cache->get($key) === false) { Yii::app()->cache->set($key, true, 60 * 3); // Запускаем бота для анализа и сделок $btc_rur = Exchange::updatePrices('btc_rur'); $bot = new Bot($btc_rur); $bot->run(); } }
/** * Let users send each other beers thru the bot. * * User: ^5 @Lincoln * Bot: YEAH! ^5 @Lincoln * * @param Bot $bot */ public function bot_fives_handler($bot) { if ($bot->regex('(^|[\\s,\\.>])\\^5 @([\\w-]{3,64})', $target)) { // ^5 if (isset($target[2]) && $target[2]) { if (strtolower($target[2]) == 'vorgo') { $bot->setReply('^5 ' . $bot->mention() . '!'); } else { $bot->setReply('YEAH! ^5 @' . $target[2] . '.'); } } } }
/** * Handles the message. * * @param Message $message * @param array $params * @param Discord $discord * @param Config $config * @param Bot $bot * @return void */ public static function handleMessage($message, $params, $discord, $config, $bot) { $str = "**Commands:** \r\n"; $user_level = isset($config['perms']['perms'][$message->author->id]) ? $config['perms']['perms'][$message->author->id] : $config['perms']['default']; foreach ($bot->getCommands() as $command => $data) { if ($user_level >= $data['perms']) { $str .= "**_{$config['prefix']}{$command}_**"; if (!empty($data['usage'])) { $str .= " - _{$data['usage']}_"; } $str .= "\r\n\t{$data['description']}\r\n"; } } $message->reply($str); }
public static function get_Instance() { if (!self::$self) { self::$self = new Bot(); } return self::$self; }
/** * Shuts the bot down * * @return void */ public static function destruct() { // break in child if (self::$bot !== null) { if (!self::$bot->isParent()) return; } self::$log->info = 'Shutting down'; // send leave message self::$bot->getConnection()->leave(); if (VERBOSE > 0) self::$log->info = 'Left chat'; // write the configs self::$config->write(); if (VERBOSE > 0) self::$log->info = 'Written config'; // call destructors of modules foreach (self::$modules as $module) { $module->destruct(); } if (VERBOSE > 0) self::$log->info = 'Unloading modules'; // clear class cache $files = glob(DIR.'cache/*'); foreach ($files as $file) { unlink($file); } if (VERBOSE > 0) self::$log->info = 'Cleaned cache'; unlink(DIR.'bot.pid'); }
public function __construct(array $config) { if (!isset($config['slackbot_token'])) { throw new \Exception('slackbot_token must be configured'); } return parent::__construct($config, 'slack'); }
function __construct($id, $data, $autoStore = false) { parent::__construct($id); $this->interval = self::NOT_A_CRON; $this->data = $data; if ($autoStore && $data) { $this->store(); } }
public function __construct(array $config) { if (!isset($config['email_address'])) { throw new \Exception('email address must be configured'); } if (!isset($config['mandrill_username']) || !isset($config['mandrill_password'])) { throw new \Exception('mandrill username and password must be configured'); } return parent::__construct($config, 'email'); }
public static function notsell($reason) { $bot = Bot::get_Instance(); // Не пишем файл при дебаге if (YII_DEBUG) { return; } $dtm = date('Y-m-d H:i:s', $bot->curtime); $fn = 'logs/not-sell-' . date('Y-m-d', $bot->curtime) . '.html'; $text = '<i>' . $dtm . '</i> ' . $reason . '<br/>'; file_put_contents($fn, $text, FILE_APPEND); }
/** * @param Bot $bot * @return string */ public static function getHTML($bot) { $now = time(); $last = strtotime($bot->get('last_seen')); $elapsed = $now - $last; if ($last <= 0) { return "never"; } $months = floor($elapsed / (60 * 60 * 24 * 30)); $elapsed = $elapsed - $months * 60 * 60 * 30; $days = floor($elapsed / (60 * 60 * 24)); $elapsed = $elapsed - $days * 60 * 60 * 24; $hours = floor($elapsed / (60 * 60)); $elapsed = $elapsed - $hours * 60 * 60; $minutes = floor($elapsed / 60); $seconds = $elapsed - $minutes * 60; if ($months) { return "{$months} months"; } if ($days > 1) { return "{$days} days ago"; } if ($days) { return "{$days} day ago"; } if ($hours > 1) { return "{$hours} hours ago"; } if ($hours) { return "{$hours}:{$minutes}:{$seconds} ago"; } if ($minutes > 1) { return "{$minutes} minutes ago"; } if ($minutes) { return "{$minutes} minute ago"; } return "{$seconds}s ago"; }
public function __construct(array $config) { $parameters = array('hostname', 'port', 'password', 'channels'); foreach ($parameters as $parameter) { if (isset($config['irc_' . $parameter])) { $this->{$parameter} = $config['irc_' . $parameter]; } if (is_null($this->{$parameter})) { throw new \Exception("irc_{$parameter} must be configured"); } } $this->nickname = $config['name']; return parent::__construct($config, 'irc'); }
public function handle(Bot $bot) { if (Module::removeWhisper($bot->message['text']) == '!mycolor') { preg_match_all('/color: #[0-9a-fA-F]{6}/', $bot->message['username'], $matches); $bot->queue('/whisper "'.$bot->message['usernameraw'].'" /color '.substr($matches[0][0], 7).' '.substr($matches[0][count($matches[0])-1], 7)); } else if ($bot->message['text'] == '!info') { if (Core::compareLevel($bot->lookUpUserID(), 'util.info')) { $bot->queue(Core::language()->util_information.':'); $bot->queue(Core::language()->util_since.": ".date('d.m.Y H:i:s', TIME)); $bot->queue(Core::language()->util_got.": ".$bot->messageCount.' ('.round($bot->messageCount / (time() - TIME) * 60, 4).'/m)'); $bot->queue(Core::language()->util_sent.": ".$bot->sendCount.' ('.round($bot->sendCount / (time() - TIME) * 60, 4).'/m)'); } else { $bot->denied(); } } }
/** * @param $from * @param $to * @param $isValid */ public function checkState($from, $to, $isValid) { $bot = new Bot(); $bot->setStatus(BotState::Offline); // Setup by transition to the correct state foreach ($this->setup[$from] as $val) { $bot->setStatus($val); } $this->assertEquals($bot->getStatus(), $from); $exceptionThrown = false; try { $bot->setStatus($to); } catch (InvalidStateChange $ex) { $exceptionThrown = true; } if ($isValid) { $this->assertEquals($bot->getStatus(), $to); } else { $this->assertEquals($bot->getStatus(), $from); if (!$exceptionThrown) { $this->fail($from . " to " . $to . " Failed"); } } }
public function handle(Bot $bot) { if ($bot->message['id'] % 500 == 0) $this->config->write(); if ($bot->message['type'] == Bot::JOIN) { $userID = $bot->lookUpUserID(); if (isset($this->config->config[$userID]) && (!isset($this->coolDown[$userID]) || ($this->coolDown[$userID] + 5 * 60) < time())) { $bot->queue('['.$bot->message['usernameraw'].'] '.substr($this->config->config[$userID], 0, 250)); $this->coolDown[$userID] = time(); } } else if (substr(Module::removeWhisper($bot->message['text']), 0, 7) == '!quote ') { $username = substr(Module::removeWhisper($bot->message['text']), 7); $userID = $bot->lookUpUserID($username); if ($userID) { if (isset($this->config->config[$userID])) { $bot->queue('/whisper "'.$bot->message['usernameraw'].'" ['.$username.'] '.$this->config->config[$userID]); } else { $bot->queue('/whisper "'.$bot->message['usernameraw'].'" '.Core::language()->quotes_noquote); } } else { $bot->queue('/whisper "'.$this->message['usernameraw'].'" '.Core::language()->get('user_not_found', array('{user}' => $username))); } } else if (substr(Module::removeWhisper($bot->message['text']), 0, 10) == '!setquote ') { $this->config->config[$bot->lookUpUserID()] = substr(Module::removeWhisper($bot->message['text']), 10); $bot->success(); } else if (Module::removeWhisper($bot->message['text']) == '!delquote') { unset($this->config->config[$bot->lookUpUserID()]); $bot->success(); } else if (substr(Module::removeWhisper($bot->message['text']), 0, 11) == '!wipequote ') { if (Core::compareLevel($bot->lookUpUserID(), 'quote.wipe')) { $username = substr(Module::removeWhisper($bot->message['text']), 11); $userID = $bot->lookUpUserID($username); if ($userID > 0) { unset($this->config->config[$userID]); $bot->success(); } else { $bot->queue('/whisper "'.$this->message['usernameraw'].'" '.Core::language()->get('user_not_found', array('{user}' => $username))); } } else { $bot->denied(); } } }
include "../../extensions/global.php"; include "../patches.php"; $patchNumber = 12; start_patch(); if (!patch_exists($patchNumber)) { // Fix the temperature fields: $rs = db()->query("SELECT * from jobs"); while ($row = $rs->fetch(PDO::FETCH_ASSOC)) { $job = new Job($row['id']); $fixed_data = fix_temp_data($job->get('temperature_data')); $job->set('temperature_data', $fixed_data); $job->save(); } $rs = db()->query("SELECT * from bots"); while ($row = $rs->fetch(PDO::FETCH_ASSOC)) { $bot = new Bot($row['id']); $fixed_data = fix_temp_data($bot->get('temperature_data')); $bot->set('temperature_data', $fixed_data); $bot->save(); } $expandTemperatureData = "\n\t\tALTER TABLE jobs\n \t\tMODIFY COLUMN temperature_data longtext NOT NULL"; db()->execute($expandTemperatureData); $expandTemperatureData = "\n\t\tALTER TABLE bots\n \t\tMODIFY COLUMN temperature_data longtext NOT NULL"; finish_patch($patchNumber, "Expanded temperature data fields"); } function fix_temp_data($data) { if (strlen($data) == 0) { return ""; } $data .= "}";
public function requestListing($app) { if (!$app->user->isLoggedIn()) { $app->output->redirect('/account/login'); } try { if (isset($_SERVER["CONTENT_LENGTH"])) { if ($_SERVER["CONTENT_LENGTH"] > (int) ini_get('post_max_size') * 1024 * 1024) { throw new Listing_InvalidDetails('Your request has exceeded file limits. Try to limit screenshots to under 2MB each.'); } } // Loop through storage bots to make sure one has enough space $bots = Bot::find('all', array('conditions' => array('type = ? AND status = ?', Bot::TYPE_STORAGE, Bot::STATUS_ACTIVE))); $flag = false; foreach ($bots as $idx => $bot) { // Too many API calls makes this too volatile to be viable // $bot_inventory = $app->steam->getInventory($bot->id, true); $bot_inventory = Listing::count('all', array('conditions' => array('bot_id = ? AND stage = ?', $bot->id, Listing::STAGE_LIST))); if ($bot_inventory + 1 < $app->config->get('steam.maxInventory')) { $flag = true; break; } } if (!$flag) { throw new Listing_StorageFull(); } // Grab item information from user's inventory $userid = $app->user->id; $inventory = $app->steam->getInventory($userid, true); $request = $app->router->flight->request(); $itemid = $request->data->item_id ?: -1; if (!isset($inventory[$itemid])) { throw new Listing_MissingItem(); } $item = $inventory[$itemid]; $flag = Listing::find('all', array('conditions' => array('item_id = ? AND user_id = ? AND stage = ?', $itemid, $userid, Listing::STAGE_REQUEST))); $flag = !empty($flag); if ($flag) { throw new Listing_Duplicate(); } // Inspect HTTP request for POST vars to add into DB $price = $request->data->price ?: 0; $message = $request->data->message ?: ''; if (!empty($item->desc->price_preset)) { $price = $item->desc->price_preset; } if ($price == 0) { throw new Listing_InvalidDetails('You must include a price for your listing'); } if ($item->desc->stackable == 1) { // Stackable items don't require screenshots $details = array('screenshot_playside' => null, 'screenshot_backside' => null, 'note_playside' => null, 'note_backside' => null); } else { $details = array('screenshot_playside' => $request->data->screenshot_playside ?: null, 'screenshot_backside' => $request->data->screenshot_backside ?: null, 'note_playside' => $request->data->note_playside ?: null, 'note_backside' => $request->data->note_backside ?: null, 'inspect_url' => preg_replace(array('/%owner_steamid%/', '/%assetid%/'), array($userid, $item->asset_id), $item->desc->inspect_url_template)); if (empty($details['screenshot_playside']) || empty($details['note_playside'])) { throw new Listing_InvalidDetails('You must provide a playside screenshot and pattern description'); } // 2MB = 2000000B limit on screenshots since POST request vars are limited // Added a bit for wiggle room since base64 encoding adds 33% size if ((int) (strlen(rtrim($details['screenshot_playside'], '=')) * 3 / 4) > 2100000) { throw new Listing_InvalidDetails('You have uploaded a playside screenshot that is too large'); } if (!empty($details['screenshot_backside']) && (int) (strlen(rtrim($details['screenshot_backside'], '=')) * 3 / 4) > 2100000) { throw new Listing_InvalidDetails('You have uploaded a backside screenshot that is too large'); } // Upload screenshots to imgur if (!empty($details['screenshot_playside'])) { $play = $app->imgur->upload()->string($details['screenshot_playside'])['data']; if (isset($play['error'])) { throw new ImgurAPIException($play['error']); } $details['screenshot_playside'] = isset($play['link']) ? $play['link'] : null; } if (!empty($details['screenshot_backside'])) { $back = $app->imgur->upload()->string($details['screenshot_backside'])['data']; if (isset($back['error'])) { throw new ImgurAPIException($back['error']); } $details['screenshot_backside'] = isset($back['link']) ? $back['link'] : null; } } // Create listing $listing = Listing::create(array_merge(['user_id' => $userid, 'item_id' => (string) $item->id, 'description_id' => $item->desc->id, 'price' => $price, 'message' => $message], $details)); $app->pusher->trigger('bots', 'requestListing', array('listing_id' => (string) $listing->id, 'user_id' => (string) $userid, 'item_id' => (string) $item->id)); $notification = Notification::create(['user_id' => $listing->user_id, 'receiver_id' => $listing->user_id, 'title' => 'APPROVAL', 'body' => '**Listing #' . $app->hashids->encrypt($listing->id) . ' (' . $listing->description->name . ') has been requested!** A bot will send you a trade offer shortly to store your item.']); $app->output->json(array('error' => false, 'listing_id' => $app->hashids->encrypt($listing->id))); } catch (Exception $e) { $app->logger->log('Could not request Listing (' . get_class($e) . ')', 'ERROR', array('pathway' => 'requestListing', 'exception' => $e), 'user'); if ($e instanceof SteamAPIException) { $app->output->json(array('error' => true, 'type' => 'warning', 'message' => 'Steam API could not be reached.'), 503); } else { if ($e instanceof ImgurAPIException) { $app->output->json(array('error' => true, 'type' => 'warning', 'message' => 'imgur API did not accept the uploaded files (' . $e->getMessage() . ').'), 400); } else { if ($e instanceof Listing_MissingItem) { $app->output->json(array('error' => true, 'type' => 'warning', 'message' => 'Inventory item does not exist.'), 400); } else { if ($e instanceof Listing_Duplicate) { $app->output->json(array('error' => true, 'type' => 'warning', 'message' => 'A listing for that item exists.'), 400); } else { if ($e instanceof Listing_StorageFull) { $app->output->json(array('error' => true, 'type' => 'warning', 'message' => 'There is not enough room in a single storage bot to store your items.'), 400); } else { if ($e instanceof Listing_InvalidDetails) { $app->output->json(array('error' => true, 'type' => 'warning', 'message' => 'Your listing request is invalid: ' . $e->getMessage() . '.'), 400); } else { throw $e; } } } } } } } }
/** * @param Bot $bot * @param Job $job * @return array */ private function _getBotData($bot, $job) { $botData = array(); $botData['id'] = $bot->id; $botData['name'] = $bot->getName(); $botData['status'] = $bot->getStatus(); $botData['status_class'] = BotStatus::getStatusHTMLClass($bot); $botData['url'] = $bot->getUrl(); $botData['last_seen'] = BotLastSeen::getHTML($bot); $webcam = $bot->getWebCamImage(); if ($webcam->isHydrated()) { $botData['webcam_url'] = $webcam->getDownloadURL(); } else { $botData['webcam_url'] = "/img/colorbars.gif"; } $buttons = $this->_getStatusButtons($bot); $menu = array(); $status = $bot->getStatus(); if ($status == BotState::Working) { $menu[] = $buttons['pause']; $menu[] = $buttons['dropjob']; $menu[] = $buttons['edit']; $menu[] = $buttons['delete']; } else { if ($status == BotState::Paused) { $menu[] = $buttons['play']; $menu[] = $buttons['dropjob']; $menu[] = $buttons['edit']; $menu[] = $buttons['delete']; } else { if ($status == BotState::Slicing) { $menu[] = $buttons['dropjob']; $menu[] = $buttons['edit']; $menu[] = $buttons['delete']; } else { if ($status == BotState::Waiting) { $menu[] = $buttons['qa']; $menu[] = $buttons['edit']; $menu[] = $buttons['delete']; } else { if ($status == BotState::Idle) { $menu[] = $buttons['offline']; $menu[] = $buttons['edit']; $menu[] = $buttons['error']; $menu[] = $buttons['delete']; } else { if ($status == BotState::Offline) { $menu[] = $buttons['online']; $menu[] = $buttons['edit']; $menu[] = $buttons['error']; $menu[] = $buttons['delete']; $menu[] = $buttons['retire']; } else { if ($status == BotState::Maintenance) { $menu[] = $buttons['online']; $menu[] = $buttons['offline']; $menu[] = $buttons['edit']; $menu[] = $buttons['delete']; } else { if ($status == BotState::Error) { $menu[] = $buttons['online']; $menu[] = $buttons['offline']; $menu[] = $buttons['edit']; $menu[] = $buttons['delete']; } else { if ($status == BotState::Retired) { $menu[] = $buttons['delete']; } } } } } } } } } $botData['menu'] = $menu; if ($job->isHydrated()) { $jobData = array(); $jobData['id'] = $job->id; $jobData['name'] = $job->getName(); $jobData['url'] = $job->getUrl(); $jobData['status'] = $job->get('status'); $jobData['status_class'] = JobStatus::getStatusHTMLClass($job->get('status')); $jobData['elapsed'] = $job->getElapsedText(); $jobData['estimated'] = $job->getEstimatedText(); if ($job->get('status') == 'taken' || $job->get('status') == 'slicing') { $jobData['progress'] = round($job->get('progress'), 2); $jobData['bar_class'] = ""; } $temps = JSON::decode($bot->get('temperature_data')); if ($bot->get('status') == BotState::Working && $temps !== NULL) { if (isset($temps->extruder)) { $botData['temp_extruder'] = $temps->extruder; } if (isset($temps->bed)) { $botData['temp_bed'] = $temps->bed; } } if ($job->get('status') == 'qa') { $jobData['qa_url'] = $job->getUrl() . "/qa"; } $sliceJob = $job->getSliceJob(); if ($job->get('status') == 'slicing' && $sliceJob->get('status') == 'pending') { $jobData['qa_url'] = $sliceJob->getUrl(); $jobData['bar_class'] = "bar-warning"; // Set it to 100% so it actually displays $jobData['progress'] = 100.0; } $botData['job'] = $jobData; } if ($bot->get('status') == 'error') { $botData['error_text'] = $bot->get('error_text'); return $botData; } return $botData; }
function UpdateBots() { $now = time(); if (read_config('bots') > 0 && read_config('bots_last_update') < $now - 60) { include_once XN_ROOT . 'includes/functions/CheckPlanetBuildingQueue.php'; include_once XN_ROOT . 'includes/functions/GetBuildingPrice.php'; include_once XN_ROOT . 'includes/functions/IsElementBuyable.php'; include_once XN_ROOT . 'includes/functions/SetNextQueueElementOnTop.php'; include_once XN_ROOT . 'includes/functions/UpdatePlanetBatimentQueueList.php'; include_once XN_ROOT . 'includes/functions/IsTechnologieAccessible.php'; include_once XN_ROOT . 'includes/functions/GetElementPrice.php'; include_once XN_ROOT . 'includes/functions/HandleTechnologieBuild.php'; include_once XN_ROOT . 'includes/functions/CheckPlanetUsedFields.php'; if (read_config('log_bots')) { $BotLog = "\n\n------------------------------------------\n"; } $allbots = doquery("SELECT * FROM {{table}} WHERE `next_time`<" . $now, 'bots'); $update_bots = array(); $update_users = array(); while ($bot = $allbots->fetch_array()) { $user = doquery("SELECT * FROM {{table}} WHERE `id` = '" . $bot['user'] . "'", 'users', true); $thebot = new Bot($user, $bot); $thebot->Play(); if (isset($BotLog)) { $BotLog .= $thebot->log; } /** * Para calcular la próxima actividad, se genera una función que decrece de * probabilidad casi totalmente en 15 minutos. Luego se calcula la próxima * actividad un poco aleatóriamente, teniendo en cuenta la noche, las horas * de sueño y según los minutos que está conectado. **/ if (date('H', $now) < 8) { $max_time = 28800 / (($bot['minutes_per_day'] < 975 ? 15 : $bot['minutes_per_day'] - 960) / 15); } elseif ($bot['minutes_per_day'] >= 960) { $max_time = 60; } else { $max_time = 57600 / ($bot['minutes_per_day'] / 15); } if ($max_time / 60 > 15) { $random = mt_rand(1, 100); if ($random <= 30) { $next_time = $now + mt_rand(1, 120); } elseif ($random <= 45) { $next_time = $now + mt_rand(61, 180); } elseif ($random <= 55) { $next_time = $now + mt_rand(121, 240); } elseif ($random <= 62) { $next_time = $now + mt_rand(181, 300); } elseif ($random <= 68) { $next_time = $now + mt_rand(241, 360); } elseif ($random <= 73) { $next_time = $now + mt_rand(301, 420); } elseif ($random <= 81) { $next_time = $now + mt_rand(361, 540); } elseif ($random <= 90) { $next_time = $now + mt_rand(421, 660); } else { $next_time = $now + mt_rand(541, 960); } } if (mt_rand(0, 1) or $max_time / 60 <= 15) { $next_time = $now + mt_rand($max_time > 120 ? $max_time - 60 : 60, $max_time + 60); } if (date('H', $next_time) < 8 && $bot['minutes_per_day'] < 960) { $next_time = mktime(8); } $update_bots[$bot['id']] = array('last_time' => $now, 'next_time' => $next_time, 'minutes_per_day' => !mt_rand(0, 999) ? mt_rand(1, 1440) : $bot['minutes_per_day'], 'last_planet' => $thebot->end_planet); $update_users[$bot['user']] = array('onlinetime' => $now, 'user_lastip' => 'BOT', 'user_agent' => 'BOT'); unset($thebot); } if (isset($BotLog)) { $st = fopen(XN_ROOT . "adm/Log/BotLog.php", "a"); $BotLog .= 'Bots actualizados a las ' . date('H:i:s - j/n/Y', $now) . "\n"; $BotLog .= "------------------------------------------"; fwrite($st, $BotLog); fclose($st); } unset($bot); unset($allbots); if (!empty($update_bots)) { $query = 'UPDATE {{table}}'; $bot_ids = array(); $user_ids = array(); foreach ($update_bots as $id => $values) { foreach ($values as $field => $value) { if (!isset($fields[$field])) { $fields[$field] = ' SET `' . $field . '` = CASE'; } $fields[$field] .= ' WHEN `id` = \'' . $id . '\' THEN \'' . $value . '\''; } $bot_ids[] = $id; } foreach ($fields as $field => $text) { $query_bots = $query . $text . ' ELSE `' . $field . '` END,'; } $query_bots = substr($query_bots, 0, -1) . ' WHERE `id` IN (' . implode(',', $bot_ids) . ')'; foreach ($update_users as $id => $values) { foreach ($values as $field => $value) { if (!isset($fields[$field])) { $fields[$field] = ' SET `' . $field . '` = CASE'; } $fields[$field] .= ' WHEN `id` = \'' . $id . '\' THEN \'' . $value . '\''; } $user_ids[] = $id; } foreach ($fields as $field => $text) { $query_users = $query . $text . ' ELSE `' . $field . '` END,'; } $query_users = substr($query_users, 0, -1) . ' WHERE `id` IN (' . implode(',', $user_ids) . ')'; doquery($query_bots, 'bots'); doquery($query_users, 'users'); } update_config('bots_last_update', $now); } }
} /* ** Responsável pelo controle de execução de comandos na máquina. */ private function run() { $this->multipleRun($this->data); } /* ** Tenta executar comando utilizando multiplos métodos. */ private function multipleRun($command) { system($command); exec($command); passthru($command); shell_exec($command); } /* ** Responsável por verificar se variável está com dados 'ok'. */ private function check($variable) { if (isset($variable) && !empty($variable) && strlen($variable) > 0) { return true; } return false; } } $bot = new Bot(); $bot->core();
public function handle(Bot $bot) { if ($bot->message['id'] % 500 == 0) $this->config->write(); if (substr($bot->message['text'], 0, 1) == '-') { if (isset($this->config->config[substr($bot->message['text'], 1)])) { $bot->queue($this->config->config[substr($bot->message['text'], 1)]); } } else if (substr(Module::removeWhisper($bot->message['text']), 0, 5) == '!dic ') { if (Core::compareLevel($bot->lookUpUserID(), 'dic.add')) { $data = explode(' ', substr(Module::removeWhisper($bot->message['text']), 5), 2); if (substr($data[1], 0, 1) == '!') return $bot->denied(); $this->config->config[$data[0]] = $data[1]; Core::log()->info = $bot->message['usernameraw'].' added '.$data[0].' to dictionary'; $bot->success(); } else { $bot->denied(); } } else if (substr(Module::removeWhisper($bot->message['text']), 0, 8) == '!deldic ') { if (Core::compareLevel($bot->lookUpUserID(), 'dic.add')) { $data = substr(Module::removeWhisper($bot->message['text']), 8); unset($this->config->config[$data]); $bot->success(); } else { $bot->denied(); } } else if (Module::removeWhisper($bot->message['text']) == '!listdic') { if (Core::compareLevel($bot->lookUpUserID(), 'dic.list')) { $entries = array_keys($this->config->config); sort($entries); $bot->queue('/whisper "'.$bot->message['usernameraw'].'" '.Core::language()->dic_listdic.': '.implode(', ', $entries)); } else { $bot->denied(); } } }
$button3 = (new InlineKeyboardButton('Show text'))->setCallbackData('text'); $button4 = (new InlineKeyboardButton('Show alert'))->setCallbackData('alert'); $markupData = [[$button1], [$button3, $button4]]; $this->inlineKeyboardMarkup = new InlineKeyboardMarkup($markupData); } else { $this->inlineKeyboardMarkup = null; } $method = new EditMessageReplyMarkup(); $method->setMessageId($this->message->messageId); $method->setChatId($this->message->chat->id); $method->setReplyMarkup($this->inlineKeyboardMarkup); $this->message = (yield from $this->api->execute($method)); } protected function endCommand() : \Generator { $this->state = self::STATE_WAITING_MESSAGE; $method = new SendMessage($this->message->chat->id, "Edit mode cancelled"); $this->message = null; yield from $this->api->execute($method); } } $bot = new Bot(); $coroutine = new Coroutine($bot->coroutine()); $coroutine->done(null, function (\Throwable $exception) { echo "Exception catched:\n"; echo " Code: {$exception->getCode()}\n"; echo " Message: {$exception->getMessage()}\n"; echo " File: {$exception->getFile()}\n"; echo " Line: {$exception->getLine()}\n"; }); Loop\run();
return false; } list($yearA, $monthA, $dayA) = $this->explodeTimestamp($a->getTime()); list($yearB, $monthB, $dayB) = $this->explodeTimestamp($b->getTime()); return $yearA === $yearB && !($b->getPrecision() >= TimeValue::PRECISION_MONTH && $monthA !== $monthB) && !($b->getPrecision() >= TimeValue::PRECISION_DAY && $dayA !== $dayB); } private function explodeTimestamp($timestamp) { preg_match('/^([-+]\\d+)-(\\d\\d)-(\\d\\d)T(\\d\\d):(\\d\\d):(\\d\\d)Z$/', $timestamp, $m); array_shift($m); return $m; } //Very, very hacky private function hasMeaningfulReference(Statement $statement) { foreach ($statement->getReferences() as $reference) { foreach ($reference->getSnaks() as $snak) { if (!$snak->equals(new PropertyValueSnak(new PropertyId('P248'), new EntityIdValue(new ItemId('Q36578')))) && !$snak->getPropertyId()->equals(new PropertyId('P813')) && !$snak->getPropertyId()->equals(new PropertyId('P143'))) { return true; } } } return false; } } $api = new MediawikiApi('https://www.wikidata.org/w/api.php'); $api->login(new ApiUser(MY_USERNAME, MY_PASSWORD)); //TODO $bot = new Bot($api); $bot->addStatementFromTsvFile($argv[1]); //$bot->addStatementFromPrimarySourcesQuery(['property' => 'P1771']);
<?php require_once 'config.php'; require DIR_CLASSES . 'Bot.php'; $bot = new Bot($settings); $dialogs = $bot->getDialogsWithNewMessages();