Created
May 17, 2017 14:43
-
-
Save mpociot/9cceede99361570b371665bdc35ff158 to your computer and use it in GitHub Desktop.
RasaNLU middleware for BotMan
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\BotMan\Middleware; | |
use Mpociot\BotMan\Message; | |
use Mpociot\BotMan\Http\Curl; | |
use Mpociot\BotMan\Interfaces\HttpInterface; | |
use Mpociot\BotMan\Interfaces\DriverInterface; | |
use Mpociot\BotMan\Interfaces\MiddlewareInterface; | |
class RasaNLU implements MiddlewareInterface | |
{ | |
/** @var string */ | |
protected $token; | |
/** @var string */ | |
protected $apiUrl = 'http://localhost:5000/parse?q='; | |
/** @var bool */ | |
protected $listenForAction = false; | |
/** | |
* Restrict the middleware to only listen for API.ai actions. | |
* @param bool $listen | |
* @return $this | |
*/ | |
public function listenForAction($listen = true) | |
{ | |
$this->listenForAction = $listen; | |
return $this; | |
} | |
/** | |
* Handle / modify the message. | |
* | |
* @param Message $message | |
* @param DriverInterface $driver | |
*/ | |
public function handle(Message &$message, DriverInterface $driver) | |
{ | |
$url = $this->apiUrl . urlencode($message->getMessage()); | |
$response = json_decode(file_get_contents($url)); | |
$reply = isset($response->result->speech) ? $response->result->speech : ''; | |
$action = isset($response->result->action) ? $response->result->action : ''; | |
$intent = isset($response->result->metadata->intentName) ? $response->result->metadata->intentName : ''; | |
$parameters = isset($response->result->parameters) ? (array) $response->result->parameters : []; | |
$message->addExtras('apiReply', $reply); | |
$message->addExtras('apiAction', $intent); | |
$message->addExtras('apiIntent', $intent); | |
$message->addExtras('apiParameters', $parameters); | |
} | |
/** | |
* @param Message $message | |
* @param string $test | |
* @param bool $regexMatched | |
* @return bool | |
* @internal param string $test | |
*/ | |
public function isMessageMatching(Message $message, $test, $regexMatched) | |
{ | |
if ($this->listenForAction) { | |
$parameters = collect($message->getExtras()['apiParameters']); | |
return $message->getExtras()['apiAction'] === $test && $parameters->has('type') && $parameters->has('size'); | |
} | |
return true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment