Skip to content

Instantly share code, notes, and snippets.

@christophrumpel
Created January 6, 2017 11:02
Show Gist options
  • Save christophrumpel/f7d4a18994c15ef7195219d9649c3c30 to your computer and use it in GitHub Desktop.
Save christophrumpel/f7d4a18994c15ef7195219d9649c3c30 to your computer and use it in GitHub Desktop.
BotMan API.ai middleware
<?php
namespace Mpociot\BotMan\Middleware;
use Illuminate\Support\Facades\Log;
use Mpociot\BotMan\Drivers\Driver;
use Mpociot\BotMan\Message;
use Mpociot\BotMan\Http\Curl;
use Mpociot\BotMan\Interfaces\HttpInterface;
use Mpociot\BotMan\Interfaces\MiddlewareInterface;
class ApiAi implements MiddlewareInterface
{
/** @var string */
protected $token;
/** @var HttpInterface */
protected $http;
/** @var string */
protected $apiUrl = 'https://api.api.ai/v1/query';
/**
* Wit constructor.
* @param string $token wit.ai access token
* @param HttpInterface $http
*/
public function __construct($token, HttpInterface $http)
{
$this->token = $token;
$this->http = $http;
}
/**
* Create a new Wit middleware instance.
* @param string $token wit.ai access token
* @return ApiAi
*/
public static function create($token)
{
return new static($token, new Curl());
}
/**
* Handle / modify the message.
*
* @param Message $message
* @param Driver $driver
*/
public function handle(Message &$message, Driver $driver)
{
$response = $this->http->post($this->apiUrl, [], [
"query" => [$message->getMessage()],
"sessionId" => str_random(36),
"lang" => "en"
], [
'Authorization: Bearer ' . $this->token,
"Content-Type: application/json; charset=utf-8"
], true);
Log::info('api response: reply: ' . $response->getContent());
$response = json_decode($response->getContent());
$reply = $response->result->speech ?? '';
$action = $response->result->action ?? '';
$intent = $response->result->metadata->intentName ?? '';
$message->addExtras('apiReply', $reply);
$message->addExtras('apiAction', $action);
$message->addExtras('apiIntent', $intent);
}
/**
* @param Message $message
* @param string $test
* @param bool $regexMatched
* @return bool
* @internal param string $test
*/
public function isMessageMatching(Message $message, $test, $regexMatched)
{
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment