getConfig()['masters']); return $masters[array_rand($masters, 1)]; } /** * Bot constructor. * @param array $config */ public function __construct(array $config = []) { $this->config = $config; } /** * @param Request $request * @return bool */ public function isValid(Request $request) { $this->request = $request; return $this->config['token'] === $request->getToken(); } /** * @param string $pattern the pattern to listen for * @param \Closure|string $callback the callback to execute. Either a closure or a Class@method notation * * @return $this */ public function hears($pattern, $callback) { if (!array_key_exists($pattern, $this->events)) { $this->events[$pattern] = $callback; } else { error_log(sprintf('Event %s déjà en place', $pattern)); } // $this->events[$pattern][] = $callback; return $this; } /** * Try to match messages with the ones we should * listen to. */ public function listen($sentence) { foreach ($this->events as $pattern => $command) { $preg_pattern = sprintf('#%s#i', $pattern); if (preg_match($preg_pattern, $sentence, $matches)) { if (is_callable($command)) { call_user_func($command, $this); } else { call_user_func([$command, 'getMessage'], $this, $matches); } } else { error_log(sprintf('%s ne match pas %s', $preg_pattern, $sentence)); } } $this->replyPolitely('Je n\'ai pas compris'); } /** * @param string $message */ public function replyPolitely($message) { $message .= ', '.$this->getMaster().'.'; $this->reply($message); } /** * @param string $message */ public function reply($message) { header('Content-type: application/json'); die('{"text": "'.$message.'"}'); } public function getConfig() { return $this->config; } }