Skip to content

Instantly share code, notes, and snippets.

@pmgupte
Last active October 10, 2017 08:59
Show Gist options
  • Save pmgupte/45baedb9ee611aabe90d0b72374a3bf7 to your computer and use it in GitHub Desktop.
Save pmgupte/45baedb9ee611aabe90d0b72374a3bf7 to your computer and use it in GitHub Desktop.
<?php
function print_api_ai_response($speech, $display_text = null, $followup_event = null, $context=null) {
$for_api_ai = array();
$for_api_ai['speech'] = $speech;
if ($display_text != null) {
$for_api_ai['displayText'] = $display_text;
} else {
$for_api_ai['displayText'] = $speech;
}
// {"followupEvent":{"name":"<event_name>","data":{"<parameter_name>":"<parameter_value>"}}}
if ($followup_event != null) {
$for_api_ai['followupEvent'] = array(
'name'=> $followup_event
);
}
if ($context != null) {
$for_api_ai['contextOut'] = $context;
}
$for_api_ai['data'] = '';
$for_api_ai['source'] = 'myfulfillment';
$response = json_encode($for_api_ai);
error_log($response);
echo $response;
} // print_api_ai_response
$request_body = file_get_contents('php://input');
$request_array = json_decode($request_body, true);
$intent_name = $request_array['result']['metadata']['intentName'];
$session_id = $request_array['sessionId'];
$filename = $session_id . '_response.txt';
error_log("Intent: $intent_name Session ID: $session_id");
if ($intent_name == 'result_ready') {
/*
* we have invoked this intent by sending "RESULT_READY" event.
* read the session-id and return corresponding contents from file.
*/
error_log('result_ready intent found.');
if (file_exists($filename)) {
$response = file_get_contents($filename);
print_api_ai_response($response);
ob_flush();
unlink($filename);
} else {
print_api_ai_response("working on it...", null, 'RESULT_READY');
}
}
if ($intent_name == "start_scorecard") {
$arr = start_scorecard(); // this function actually does the job and returns response text.
$context = array(
array(
"name" => "my-report-context",
"lifespan" => 5,
"parameters" => array("report_id" => $arr['report_id'])
)
);
// per documentation, if context is provided, speech is not spoken and displayText is not shown.
print_api_ai_response($arr['speech'], $arr['displayText'], null, $context);
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment