Etienne Kneuss

home » repository » php » ircbot » modules » class.Module_Knowledge.php
Tree:
school
mp3
php
sample
publications
Math_Derivative
Math_Expression
ircbot
libraries
modules
class.Module_Invite.php
class.Module_Auth.php
class.Module_Control.php
class.Module_Protocol.php
class.Module.php
class.Module_Output.php
class.Module_Knowledge.php
class.Module_Perform.php
exceptions
bot.php
plopbot.sql
php.net
images
dump

Source code raw phps

    <?php require_once 'modules/class.Module.php'; class Module_Knowledge extends Module {     protected static $_answersUnknown = array ('What?',                                                'I don\'t know, sorry.',                                                'No idea.',                                                'What are you talking about?',                                                'Uh?',                                                'Eh?',                                                'What the heck?',                                                'I don\'t understand.',                                                'Precise your question please.');     protected $_lastMessages = array();     public function update(Observed $bot, $raw, $type)      {         if (($type & Bot::U_INPUT) != Bot::U_INPUT) {             return Bot::E_CONTINUE;         }         $raw_pieces = explode(' ', $raw, 4);                  if (isset($raw_pieces[1]) && $raw_pieces[1] == 'PRIVMSG' && $raw_pieces[2][0] == '#') {                          return $this->_handleChannelMessage($raw_pieces, $bot);                  } else if (isset($raw_pieces[1]) && $raw_pieces[1] == 'PRIVMSG' && $raw_pieces[2][0] != '#') {                          return $this->_handlePrivateMessage($raw_pieces, $bot);                      }         return Bot::E_CONTINUE;     }     protected function _handleChannelMessage($raw_pieces, $bot)      {         $match_prefix       = '!talk about ';         $match_short_prefix = '!+';         $search_prefix      = '!search ';         $learn_prefix       = '!learn ';         $tell_prefix        = '!tell ';                  $channel = $raw_pieces[2];                  $message = substr($raw_pieces[3], 1);         list($nick) = explode('!', substr($raw_pieces[0], 1), 2);                  if (substr($message,0, strlen($tell_prefix)) == $tell_prefix) {                          $pattern = substr($message, strlen($tell_prefix));                          $pattern_pieces = explode(' ', $pattern, 3);             if ($pattern_pieces[0][0] == '#') {                 return Bot::E_CONTINUE;             }             $from = $nick;             $to = $pattern_pieces[0];             $pattern = $pattern_pieces[2];             if ($this->_flooded()) {                 return Bot::E_CONTINUE;             }             if (($result = $this->_getMatch($pattern)) !== false) {                 if ($from == $to || $to == 'me') {                                      $bot->send('PRIVMSG '.$from.' :'.$result);                                      } else {                     $bot->send('PRIVMSG '.$to.' :'.$from.' wanted me to tell you: '.$result);                     $bot->send('PRIVMSG '.$from.' :Told '.$to.' about: '.$result);                 }                              } else {                 $bot->send('PRIVMSG '.$channel.' :'.$this->_pickRandomAnswer('unknown'));             }                              } else if (substr($message,0, strlen($match_prefix)) == $match_prefix) {             $pattern = substr($message, strlen($match_prefix));                          if ($this->_flooded()) {                 return Bot::E_CONTINUE;             }                          if (($result = $this->_getMatch($pattern)) !== false) {                 $bot->send('PRIVMSG '.$channel.' :'.$result);             } else {                 $bot->send('PRIVMSG '.$channel.' :'.$this->_pickRandomAnswer('unknown'));             }                               } else if (substr($message,0, strlen($search_prefix)) == $search_prefix) {             $pattern = substr($message, strlen($search_prefix));             if ($this->_flooded()) {                 return Bot::E_CONTINUE;             }             if (($result = $this->_search($pattern)) !== false) {                 $bot->send('PRIVMSG '.$channel.' :'.$result);             } else {                 $bot->send('PRIVMSG '.$channel.' :'.$this->_pickRandomAnswer('unknown'));             }         } else if (substr($message,0, strlen($match_short_prefix)) == $match_short_prefix) {             $pattern = trim(substr($message, strlen($match_short_prefix)));                          if ($this->_flooded()) {                 return Bot::E_CONTINUE;             }                          if (($result = $this->_getMatch($pattern)) !== false) {                 $bot->send('PRIVMSG '.$channel.' :'.$result);             } else {                 $bot->send('PRIVMSG '.$channel.' :'.$this->_pickRandomAnswer('unknown'));             }                               } else if (substr($message,0, strlen($learn_prefix)) == $learn_prefix) {             $db = DB::instance();             $pattern = trim(substr($message, strlen($learn_prefix)));                      var_dump($pattern."\n");             if (preg_match('/^(r)?\s*"((?:(?<=\\\\)"|[^"])+)"\s*=>\s*"((?:(?<=\\\\)"|[^"])+)"$/', $pattern, $matches)) {                                  echo 'matched';                                  if ($matches[1] == 'r') {                     $type = 2;                 } else {                     $type = 1;                 }                 $keyword = str_replace('\"', '"', $matches[2]);                 $info    = str_replace('\"', '"', $matches[3]);                 $query = 'INSERT INTO informations (`content`)                                 VALUES (\''.$db->escape($info).'\')';                 $db->execute($query);                 if ($id = $db->insertedId()) {                     $query = 'INSERT INTO keywords (`type_id`, `information_id`, `pattern`)                                    VALUES ('.$type.', '.$id.', \''.$db->escape($keyword).'\')';                     if (!$db->execute($query)) {                         $bot->notify('Error while learning'.mysql_error(), Bot::U_M_KNOWLEDGE | Bot::U_ERROR);                     } else {                         $bot->send('PRIVMSG '.$channel.' :Understood.');                     }                                                            } else {                     $bot->notify('Error while learning'.mysql_error(), Bot::U_M_KNOWLEDGE | Bot::U_ERROR);                 }                                                    }         }                         return Bot::E_CONTINUE;              }     protected function _insert($pattern, $infos, $type)      {         $db = DB::instance();                  $query = 'INSERT INTO informations (`content`)                                      VALUES (\''.$db->escape($info).'\')';         $db->execute($query);         if ($id = $db->insertedId()) {             $query = 'INSERT INTO keywords (`type_id`, `information_id`, `pattern`)                                     VALUES ('.$type.', '.$id.', \''.$db->escape($keyword).'\')';             if (!$db->execute($query)) {                 return false;             } else {                 return true;             }                                                    } else {             return false;         }     }          protected function _delete($pattern, $type)      {         $db = DB::instance();                  $query = 'INSERT INTO informations (`content`)                                      VALUES (\''.$db->escape($info).'\')';         $db->execute($query);         if ($id = $db->insertedId()) {             $query = 'INSERT INTO keywords (`type_id`, `information_id`, `pattern`)                                     VALUES ('.$type.', '.$id.', \''.$db->escape($keyword).'\')';             if (!$db->execute($query)) {                 return false;             } else {                 return true;             }                                                    } else {             return false;         }     }          protected function _handlePrivateMessage($raw_pieces, $bot)     {         $pattern = substr($raw_pieces[3], 1);                  list($nick) = explode('!', substr($raw_pieces[0], 1), 2);                           if ($this->_flooded()) {             return Bot::E_CONTINUE;         }                      if (($result = $this->_getMatch($pattern)) !== false) {             $this->_link->write('PRIVMSG '.$nick.' :'.$result);         } else {             $this->_link->write('PRIVMSG '.$nick.' :'.$this->_pickRandomAnswer('unknown'));         }              return Bot::E_CONTINUE;     }     protected function _getMatch($pattern)      {         $db = DB::instance();                  $pattern         = $db->escape($pattern);         $result          = $db->execute('SELECT i.content                                            FROM informations i,                                                 keywords k                                           WHERE ((k.type_id = 1 AND k.pattern = \''.$pattern.'\') OR                                                 (k.type_id = 2 AND BINARY \''.$pattern.'\' REGEXP k.pattern))  AND                                                 i.id = k.information_id                                        ORDER BY LENGTH(k.pattern)                                           LIMIT 1');                  if ($result instanceof DB_Common_Results && $result->numRows()) {             return str_replace(array("\n", "\r"), '', $result[0]['content']);         } else {             return false;         }              }     protected function _flooded() {         if (time()*count($this->_lastMessages) - array_sum($this->_lastMessages) < 2*count($this->_lastMessages)) {                                                return true;                      } else {             if (count($this->_lastMessages) == 5) {                 array_shift($this->_lastMessages);             }             $this->_lastMessages[] = time();                          return false;         }     }     protected function _search($pattern)      {         $db = DB::instance();              $pattern = $db->escape(trim($pattern));         $pattern = str_replace(array('(', ')'), array('\\(', '\\)'), $pattern);         $pattern = '*'.trim($pattern, '*').'*';                  $result = $db->execute('SELECT i.content, k.pattern                                           FROM informations i,                                                 keywords k                                           WHERE i.id = k.information_id                                             AND MATCH (i.content, k.pattern) AGAINST (\''.$pattern.'\'  IN BOOLEAN MODE)                                          ORDER BY MATCH (i.content, k.pattern) AGAINST (\''.$pattern.'\'  IN BOOLEAN MODE) + MATCH (i.content) AGAINST (\''.$pattern.'\'  IN BOOLEAN MODE)/2 DESC');              if ($result instanceof DB_Common_Results) {             if($result->numRows() == 0){                              return 'Nothing found';                              } elseif ($result->numRows() > 11){                 $keywords = array();                 for ($i=0; $i<5; $i++) {                     $keywords[] = '"'.$result[$i]['pattern'].'"';                 }                                  return 'Too many results for your request ('.$result->numRows().' items found). Most relevant results: '.implode(', ', $keywords);                              } elseif ($result->numRows() === 1) {                 $content = $result[$i]['content'];                                  return str_replace(array("\n", "\r"), '', $content);                              } else {                              $out = $result->numRows().' keywords found: ';                 $keywords = array();                 foreach($result as $found) {                     $keywords[] = '"'.$found['pattern'].'"';                 }                 $out .= implode(', ', $keywords);                 return str_replace(array("\n", "\r"), '', $out);             }         } else {             return false;         }     }     protected function _pickRandomAnswer($type)      {         switch($type) {             case 'unknown':                 $array = self::$_answersUnknown;                 break;             default :                 $array = self::$_answersUnknown;         }                  return $array[array_rand($array)];     } }

Comments

There is currently no comment here.

Add a comment

Username:

Spam Challenge: 14+19=?

Comment: