コード例 #1
0
ファイル: QuizServer.php プロジェクト: WaveCutz/skype-bot
 public function init()
 {
     Admin::registerGroup(self::CHATGROUP);
     $this->questionsCount = \Util::getLinesCount(self::QUIZ_DB_PATH);
     $this->quizDb = Factory::create(\Util::getLocalPath() . DS . 'quiz.json');
     if (!isset($this->quizDb['scores'])) {
         $this->quizDb['scores'] = [];
     }
     $this->ev->on(CoreInterface::MESSAGE, [$this, 'processMessage']);
     $this->ev->on('tick', [$this, 'processRunningQuiz']);
     \Util::console('Quiz: Questions count: ' . $this->questionsCount);
     $this->ev->on('restart', function () {
         $running = \Util::store('quiz') ?: [];
         if (count($running)) {
             foreach ($running as $chatName => $run) {
                 $msg = '(devil) Игра окончена, т.к. ведущий перезагружается.';
                 $msg .= $this->scoresMessage($chatName);
                 $this->core->send($chatName, $msg);
                 unset($running[$chatName]);
                 \Util::store('quiz', $running);
             }
         }
         return true;
     });
 }
コード例 #2
0
ファイル: Commands.php プロジェクト: WaveCutz/skype-bot
 public function getRates($force = false)
 {
     $ratesToGet = ['today' => strtotime('today'), 'tomorrow' => strtotime('tomorrow')];
     $ratesDb = Factory::create(\Util::getLocalPath() . DS . 'rates.json');
     $rates = $ratesDb['rates'] ?: [];
     foreach ($ratesToGet as $day => $stamp) {
         if ($force || empty($rates[$stamp])) {
             $response = $this->http->getResponse('GET', 'http://www.nbrb.by/Services/XmlExRates.aspx?ondate=' . date('m/d/Y', $stamp));
             if ($response && $response->getStatusCode() === 200 && ($body = $response->getBody())) {
                 /** @var \SimpleXMLElement $rate */
                 $rate = simplexml_load_string($body, 'SimpleXMLElement', LIBXML_NOCDATA);
                 if ((bool) $rate && isset($rate->Currency)) {
                     $newRate = [];
                     foreach ($rate->Currency as $currency) {
                         switch ((string) $currency->CharCode) {
                             case 'EUR':
                             case 'RUB':
                             case 'USD':
                                 $newRate[(string) $currency->CharCode] = round((double) $currency->Rate);
                                 break;
                         }
                     }
                     $rates[$stamp] = $newRate;
                 } else {
                     unset($rates[$stamp]);
                 }
                 ksort($rates);
                 $ratesDb['rates'] = $rates;
             }
         }
     }
     return $rates;
 }
コード例 #3
0
ファイル: Rss.php プロジェクト: WaveCutz/skype-bot
 public function init()
 {
     $this->ev->on('tick', [$this, 'processFeeds']);
     $this->rssDb = Factory::create(\Util::getLocalPath() . DS . 'rss.json');
 }
コード例 #4
0
ファイル: Web.php プロジェクト: WaveCutz/skype-bot
 public function initSkypeConnection()
 {
     $config = $this->container->get('config');
     $this->username = $config['web']['username'];
     $this->password = $config['web']['password'];
     $this->tokenDb = $this->quizDb = Factory::create(\Util::getLocalPath() . DS . 'coreWebToken.json');
     $this->lastPoll = time();
     \Util::debug('Start login');
     if ($this->tokenDb['skypeTokenTimeout'] && $this->tokenDb['skypeTokenTimeout'] < time()) {
         $this->tokenDb->clear();
         \Util::debug('Clearing timed out session');
     }
     if (!$this->tokenDb['skypeToken']) {
         \Util::debug('No token');
         $response = $this->webRequest('https://login.skype.com/login?client_id=578134&redirect_uri=https%3A%2F%2Fweb.skype.com', 'GET', null, [], false, true);
         \Util::debug('Checking if authorized already');
         $headersPos = strpos($response, "\r\n\r\n");
         $headers = $this->parseHeaders(substr($response, 0, $headersPos));
         $body = substr($response, $headersPos + 4);
         if (isset($headers['Set-Cookie'])) {
             if (is_string($headers['Set-Cookie'])) {
                 $headers['Set-Cookie'] = [$headers['Set-Cookie']];
             }
             foreach ($headers['Set-Cookie'] as $cookie) {
                 $match = [];
                 if ($this->tokenDb['skypeToken']) {
                     break;
                 }
                 if (!preg_match('/^refresh-token=(.+?);/', $cookie, $match)) {
                     continue;
                 }
                 if ($match && $match[1]) {
                     \Util::debug('Got skypeToken: ' . $match[1]);
                     $this->setSkypeToken($match[1]);
                     break;
                 }
             }
         }
         if (!$this->tokenDb['skypeToken']) {
             \Util::debug('Not authorized');
             $pq = \phpQuery::newDocumentHTML($body);
             $pie = $pq->find('input[name=pie]')->val();
             $etm = $pq->find('input[name=etm]')->val();
             $jsTime = $pq->find('input[name=js_time]')->val();
             $response = $this->webRequest('https://login.skype.com/login?client_id=578134&redirect_uri=https%3A%2F%2Fweb.skype.com', 'POST', ['username' => $this->username, 'password' => $this->password, 'persistent' => 1, 'pie' => $pie, 'etm' => $etm, 'js_time' => $jsTime, 'timezone_field' => '+03|00', 'client_id' => 578134, 'redirect_uri' => 'https://web.skype.com/']);
             $pq = \phpQuery::newDocumentHTML($response);
             $skypeToken = $pq->find('input[name=skypetoken]')->val();
             if ($skypeToken) {
                 \Util::debug('Got skypeToken: ' . $skypeToken);
                 $this->setSkypeToken($skypeToken);
             }
         }
     }
     if (!$this->tokenDb['skypeToken']) {
         \Util::debug('No skypeToken, exiting');
         die(1);
     }
     \Util::debug('Getting regToken');
     $response = $this->webRequest('https://web.skype.com/', 'POST', ['skypetoken' => $this->tokenDb['skypeToken']]);
     $response = $this->webRequest('https://client-s.gateway.messenger.live.com/v1/users/ME/endpoints', 'POST', '{"endpointFeatures":"Agent"}', ['Accept' => 'application/json, text/javascript', 'ClientInfo' => self::CLIENT_INFO, 'BehaviorOverride' => 'redirectAs404', 'LockAndKey' => 'appId=msmsgs@msnmsgr.com; time=' . $this->lastPoll . '; lockAndKeyResponse=' . hash('sha256', $this->lastPoll), 'Content-Type' => 'application/json', 'Origin' => 'https://web.skype.com', 'Referer' => 'https://web.skype.com/en/', 'ContextId' => 'tcid=' . $this->lastPoll . '00000000'], false, true);
     $headersPos = strpos($response, "\r\n\r\n");
     $headers = $this->parseHeaders(substr($response, 0, $headersPos));
     $body = substr($response, $headersPos + 4);
     $endpointUrl = $headers['Location'];
     if ($endpointUrl) {
         //            \Util::debug('raw endpointUrl: ' . $endpointUrl);
         $this->endpointUrl = rtrim(urldecode($endpointUrl), '/') . '/';
     }
     $regToken = $headers['Set-RegistrationToken'];
     if ($regToken) {
         list($regToken, $regTokenTimeout, $endpointId) = explode('; ', $regToken);
         $this->regToken = $regToken;
         $this->regTokenTimeout = str_replace('expires=', '', $regTokenTimeout);
         $this->endpointId = str_replace('endpointId=', '', $endpointId);
         \Util::debug('regToken: ' . $this->regToken);
         \Util::debug('endpointId: ' . $this->endpointId);
         $this->endpointUrl = rtrim(str_replace('/' . $this->endpointId . '/', '', urldecode($this->endpointUrl)), '/');
         \Util::debug('endpointUrl: ' . $this->endpointUrl);
         \Util::debug('Creating endpoint');
         $response = $this->webRequest($this->endpointUrl . '/' . $this->endpointId, 'PUT', '{"endpointFeatures":"Agent"}', ['Accept' => 'application/json, text/javascript', 'Accept-Encoding' => 'gzip, deflate, sdch', 'Accept-Language' => 'en-EN;q=1', 'BehaviorOverride' => 'redirectAs404', 'Cache-Control' => 'no-cache, no-store, must-revalidate', 'ClientInfo' => self::CLIENT_INFO, 'Connection' => 'keep-alive', 'Content-Type' => 'application/json', 'Expires' => '0', 'Host' => parse_url($this->endpointUrl, PHP_URL_HOST), 'Origin' => 'https://web.skype.com', 'Pragma' => 'no-cache', 'Referer' => 'https://web.skype.com/en/', 'ContextId' => 'tcid=' . $this->lastPoll . '00000000'], false, true, 5);
         \Util::debug('Body: ' . $response);
         \Util::debug('Setting subscriptions');
         $response = $this->webRequest($this->endpointUrl . '/' . 'SELF/subscriptions', 'POST', '{"channelType":"httpLongPoll","template":"raw","interestedResources":["/v1/users/ME/conversations/ALL/properties","/v1/users/ME/conversations/ALL/messages","/v1/users/ME/contacts/ALL","/v1/threads/ALL"]}', ['Accept' => 'application/json, text/javascript']);
         $this->initialized = true;
     }
 }
コード例 #5
0
ファイル: Web.php プロジェクト: rakauchuk/skype-bot
 public function initSkypeConnection()
 {
     $config = $this->container->get('config');
     $this->username = $config['web']['username'];
     $this->password = $config['web']['password'];
     $this->tokenDb = $this->quizDb = Factory::create(\Util::getLocalPath() . DS . 'coreWebToken.json');
     $this->lastPoll = time();
     \Util::debug('Start login');
     if ($this->tokenDb['skypeTokenTimeout'] && $this->tokenDb['skypeTokenTimeout'] < time()) {
         $this->tokenDb->clear();
         \Util::debug('Clearing timed out session');
     }
     if (!$this->tokenDb['skypeToken']) {
         \Util::debug('No token');
         $response = $this->webRequest('https://login.skype.com/login?client_id=578134&redirect_uri=https%3A%2F%2Fweb.skype.com', 'GET', null, [], false, true);
         \Util::debug('loginpage');
         $headersPos = strpos($response, "\r\n\r\n");
         $headers = $this->parseHeaders(substr($response, 0, $headersPos));
         $body = substr($response, $headersPos + 4);
         if (isset($headers['Set-Cookie'])) {
             if (is_string($headers['Set-Cookie'])) {
                 $headers['Set-Cookie'] = [$headers['Set-Cookie']];
             }
             foreach ($headers['Set-Cookie'] as $cookie) {
                 $match = [];
                 if ($this->tokenDb['skypeToken']) {
                     break;
                 }
                 if (!preg_match('/^refresh-token=(.+?);/', $cookie, $match)) {
                     continue;
                 }
                 if ($match && $match[1]) {
                     $this->setSkypeToken($match[1]);
                 }
             }
         }
         if (!$this->tokenDb['skypeToken']) {
             $pq = \phpQuery::newDocumentHTML($body);
             $pie = $pq->find('input[name=pie]')->val();
             $etm = $pq->find('input[name=etm]')->val();
             $jsTime = $pq->find('input[name=js_time]')->val();
             $response = $this->webRequest('https://login.skype.com/login?client_id=578134&redirect_uri=https%3A%2F%2Fweb.skype.com', 'POST', ['username' => $this->username, 'password' => $this->password, 'persistent' => 1, 'pie' => $pie, 'etm' => $etm, 'js_time' => $jsTime, 'timezone_field' => '+03|00', 'client_id' => 578134, 'redirect_uri' => 'https://web.skype.com/']);
             $pq = \phpQuery::newDocumentHTML($response);
             $skypeToken = $pq->find('input[name=skypetoken]')->val();
             if ($skypeToken) {
                 $this->setSkypeToken($skypeToken);
             }
         }
     }
     $response = $this->webRequest('https://web.skype.com/', 'POST', ['skypetoken' => $this->tokenDb['skypeToken']]);
     $response = $this->webRequest('https://client-s.gateway.messenger.live.com/v1/users/ME/endpoints', 'POST', '{}', ['Accept' => 'application/json, text/javascript', 'ClientInfo' => 'os=Windows; osVer=10; proc=Win32; lcid=en-us; deviceType=1; country=n/a; clientName=skype.com; clientVer=908/1.21.0.115//skype.com', 'BehaviorOverride' => 'redirectAs404', 'LockAndKey' => 'appId=msmsgs@msnmsgr.com; time=' . $this->lastPoll . '; lockAndKeyResponse=' . md5($this->lastPoll), 'Content-Type' => 'application/json; charset=UTF-8', 'Origin' => 'https://web.skype.com', 'Referer' => 'https://web.skype.com/ru/', 'ContextId' => 'tcid=' . $this->lastPoll . '00000000'], false, true);
     $headersPos = strpos($response, "\r\n\r\n");
     $headers = $this->parseHeaders(substr($response, 0, $headersPos));
     $body = substr($response, $headersPos + 4);
     $endpointUrl = $headers['Location'];
     if ($endpointUrl) {
         $this->endpointUrl = rtrim(urldecode($endpointUrl), '/') . '/';
     }
     $regToken = $headers['Set-RegistrationToken'];
     if ($regToken) {
         list($regToken, $regTokenTimeout, $endpointId) = explode('; ', $regToken);
         $this->regToken = $regToken;
         $this->regTokenTimeout = str_replace('expires=', '', $regTokenTimeout);
         $this->endpointId = str_replace('endpointId=', '', $endpointId);
         $this->endpointUrl = str_replace($this->endpointId . '/', '', urldecode($this->endpointUrl));
         \Util::debug($this->endpointUrl);
         $response = $this->webRequest($this->endpointUrl . $this->endpointId, 'PUT', '{}', ['Accept' => 'application/json, text/javascript', 'ClientInfo' => 'os=Windows; osVer=10; proc=Win32; lcid=en-us; deviceType=1; country=n/a; clientName=skype.com; clientVer=908/1.22.0.117//skype.com', 'BehaviorOverride' => 'redirectAs404', 'Content-Type' => 'application/json; charset=UTF-8', 'Origin' => 'https://web.skype.com', 'Referer' => 'https://web.skype.com/ru/', 'ContextId' => 'tcid=' . $this->lastPoll . '00000000'], false, true, 5);
         $response = $this->webRequest($this->endpointUrl . 'SELF/subscriptions', 'POST', '{"channelType":"httpLongPoll","template":"raw","interestedResources":["/v1/users/ME/conversations/ALL/properties","/v1/users/ME/conversations/ALL/messages","/v1/users/ME/contacts/ALL","/v1/threads/ALL"]}', ['Accept' => 'application/json, text/javascript']);
         $this->initialized = true;
     }
 }
コード例 #6
0
ファイル: JenkinsWatcher.php プロジェクト: WaveCutz/skype-bot
 public function processJobs($time)
 {
     if ($time >= $this->currentTime + self::PERIOD) {
         $this->currentTime = $time;
         $builds = [];
         // TODO move to config
         $jobsUrl = "http://jenkinshost/api/json?tree=jobs[name," . "lastBuild[building,timestamp,actions[parameters[name,value]],fullDisplayName,result,number,url," . 'changeSet[items[msg,author[fullName]]]' . "]]";
         //            \Util::debug($jobsUrl);
         $response = $this->http->getResponse('GET', $jobsUrl);
         if ($response && $response->getStatusCode() === 200 && ($body = $response->getBody())) {
             /** @var array $buildsRaw */
             $buildsRaw = json_decode($body, true)['jobs'];
             $jobs = $this->pluginConfig['jobs'];
             foreach ($buildsRaw as $build) {
                 if (in_array($build['name'], array_keys($jobs))) {
                     $builds[$build['name']] = [];
                     if (isset($build['lastBuild']['actions'][0]['parameters'])) {
                         foreach ($build['lastBuild']['actions'][0]['parameters'] as $param) {
                             $builds[$build['name']][$param['name']] = $param['value'];
                         }
                     }
                     $builds[$build['name']]['result'] = $build['lastBuild']['result'];
                     $builds[$build['name']]['displayName'] = $build['lastBuild']['fullDisplayName'];
                     $builds[$build['name']]['number'] = $build['lastBuild']['number'];
                     $builds[$build['name']]['url'] = $build['lastBuild']['url'];
                     $builds[$build['name']]['time'] = $build['lastBuild']['timestamp'];
                     $builds[$build['name']]['building'] = $build['lastBuild']['building'];
                     $changes = [];
                     if (!empty($build['lastBuild']['changeSet']['items'])) {
                         foreach ($build['lastBuild']['changeSet']['items'] as $change) {
                             $changes[] = [$change['author']['fullName'], $change['msg']];
                         }
                     }
                     $builds[$build['name']]['changes'] = $changes;
                 }
             }
             $jobsDb = Factory::create(\Util::getLocalPath() . DS . 'jobs.json');
             $msg = '';
             $prevBuilds = $jobsDb['jobs'] ?: [];
             foreach ($builds as $name => $build) {
                 $extra = [];
                 $job = !empty($jobs[$name]) ? $jobs[$name] : [];
                 if (isset($prevBuilds[$name]) && ($build['number'] !== $prevBuilds[$name]['number'] || $build['result'] !== $prevBuilds[$name]['result'])) {
                     $xtext = '';
                     if (isset($build['DEPLOY_STAGE'])) {
                         $extra['on'] = $build['DEPLOY_STAGE'];
                     }
                     if (isset($build['TARGET_SERVER'])) {
                         $extra['on'] = $build['TARGET_SERVER'];
                     }
                     if (isset($build['DEPLOY_BRANCH'])) {
                         $extra['source:'] = $build['DEPLOY_BRANCH'];
                     }
                     if (count($extra)) {
                         $texts = [];
                         foreach ($extra as $xname => $xval) {
                             $texts[] = "{$xname} {$xval}";
                         }
                         $xtext = implode(', ', $texts);
                     }
                     if (!$build['building']) {
                         \Util::console("Jenkins: job '{$name}'' state {$build['result']}");
                         $result = $build['result'];
                         $link = '';
                         $versionUrl = null;
                         switch ($result) {
                             case 'SUCCESS':
                                 if (array_key_exists('skipSections', $job) && in_array('success', $job['skipSections'])) {
                                     \Util::console("Jenkins: job '{$name}' skip success");
                                     continue 2;
                                 }
                                 $result = '(y) SUCCESS';
                                 break;
                             case 'FAILURE':
                                 if (array_key_exists('skipSections', $job) && in_array('failure', $job['skipSections'])) {
                                     \Util::console("Jenkins: job '{$name}' skip failure");
                                     continue 2;
                                 }
                                 $result = ';( FAILURE';
                                 $link = $build['url'];
                                 break;
                         }
                         if (!empty($job)) {
                             if (array_values($job) === $job) {
                                 $versionUrl = current($job);
                             } else {
                                 if (array_key_exists('DEPLOY_STAGE', $build) && !empty($build['DEPLOY_STAGE']) && !empty($job[$build['DEPLOY_STAGE']])) {
                                     $versionUrl = $job[$build['DEPLOY_STAGE']];
                                 } elseif (array_key_exists('TARGET_SERVER', $build) && !empty($build['TARGET_SERVER']) && !empty($job[$build['TARGET_SERVER']])) {
                                     $versionUrl = $job[$build['TARGET_SERVER']];
                                 }
                             }
                         }
                         $version = null;
                         if ($versionUrl && $build['result'] === 'SUCCESS') {
                             $response = $this->http->getResponse('GET', $versionUrl, [RequestOptions::AUTH => [$this->pluginConfig['auth']['user'], $this->pluginConfig['auth']['passwd']]]);
                             if ($response && $response->getStatusCode() === 200 && ($body = $response->getBody())) {
                                 $xtext .= ' (ver. ' . trim($body) . ')';
                             }
                         }
                         $msg .= PHP_EOL . "[J] {$build['displayName']} {$result} {$xtext} " . date('Y-m-d H:i', $build['time'] / 1000) . " {$link}" . PHP_EOL;
                         if (count($build['changes'])) {
                             $msg .= 'Changeset:' . PHP_EOL;
                             $changeSet = [];
                             foreach ($build['changes'] as $change) {
                                 list($changeName, $changeMessage) = $change;
                                 $changeName = trim($changeName);
                                 if (!isset($changeSet[$changeName])) {
                                     $changeSet[$changeName] = [];
                                 }
                                 $taskNum = preg_replace('/^([A-Z]+\\-\\d+).*$/', '\\1', $changeMessage);
                                 if ($taskNum) {
                                     if (!isset($changeSet[$changeName][$taskNum])) {
                                         $changeSet[$changeName][$taskNum] = 0;
                                     }
                                     $changeSet[$changeName][$taskNum]++;
                                 }
                             }
                             foreach ($changeSet as $changer => $tasks) {
                                 foreach ($tasks as $task => $count) {
                                     $msg .= $changer . ': ' . $task . " ({$count} commit(s))" . PHP_EOL;
                                 }
                             }
                         }
                     } else {
                         \Util::console("Jenkins: job '{$name}' started");
                         if (!empty($job) && array_key_exists('skipSections', $job) && in_array('start', $job['skipSections'])) {
                             \Util::console("Jenkins: job '{$name}' skip start");
                             continue;
                         }
                         $msg .= PHP_EOL . "[J] {$build['displayName']} build began {$xtext}";
                     }
                 }
             }
             $jobsDb['jobs'] = $builds;
             if ($msg) {
                 $chats = $this->db['chats'] ?: [];
                 if (isset($chats[self::CHATGROUP]) && count($chats[self::CHATGROUP])) {
                     foreach ($chats[self::CHATGROUP] as $chatName) {
                         $this->core->send($chatName, trim($msg));
                     }
                 }
             }
         } else {
             \Util::console('Jenkins builds failed to fetch: ' . ($response ? $response->getBody() : '.'));
         }
     }
 }
コード例 #7
0
ファイル: bot.php プロジェクト: rakauchuk/skype-bot
use Interop\Container\ContainerInterface;
$builder = new DI\ContainerBuilder();
$builder->useAnnotations(true);
$builder->addDefinitions(['config.path' => ROOT . DS . 'config', 'config' => function (ContainerInterface $c) {
    $config = \Symfony\Component\Yaml\Yaml::parse(file_get_contents($c->get('config.path') . DS . 'bot.yml'));
    return $config;
}, 'loop' => \DI\object(React\EventLoop\StreamSelectLoop::class), 'event' => \DI\object(Sabre\Event\EventEmitter::class)]);
$container = $builder->build();
spl_autoload_register(function ($className) use($container) {
    $className = ltrim($className, "\\");
    $fileName = '';
    if (($lastNsPos = strrpos($className, "\\")) !== false) {
        $namespace = substr($className, 0, $lastNsPos);
        $className = substr($className, $lastNsPos + 1);
        $fileName = str_replace("\\", DS, $namespace) . DS;
    }
    $fileName .= str_replace('_', DS, $className) . '.php';
    $requirePath = __DIR__ . DS . 'src' . DS . $fileName;
    require $requirePath;
});
$config = $container->get('config');
Util::$debug = $config['debug'];
$db = \Bot\Filebase\Factory::create(BASE . DS . 'main.json');
$container->set('Core', \DI\object("\\Bot\\Core\\Web"));
$container->set('db', $db);
Util::store('container', $container);
/**
 * @var \Bot\App $app
 */
$app = $container->get('\\Bot\\App');
$app->run();