pricehook.php source code

This page contains the PHP source code for the pricehook webhook that we added to our Dialogflow-based GROCERYbot.

<?php

/**
* @file
* pricehook is called by Dialogflow when an intent fires and pricehooks
* are enabled.
*
* It returns a response string displayed to the user as a response
* to an utterance asking about prices.
*/

/* file for reading post data */
$jfile = “php://input”;

/* get the json data for the request and decode it */
$rawdata = file_get_contents($jfile);
$decoded = json_decode($rawdata);

/* Check input for required fields and
get the values of the entity and attribute being requested */
if (!array_key_exists(‘queryResult’,$decoded)) {
echo ” “;
exit;
}
if (!array_key_exists(‘parameters’,$decoded->queryResult)) {
echo ” “;
exit;
}

/* scan the parameters */
$att = NULL;
$varname = NULL;
$varvalue = NULL;
foreach ($decoded->queryResult->parameters as $key => $s) {
if ($key == ‘attribute’) {
$att = $s;
}
else {
$entity = $key;
$entity_value = $s;
}
}

if ($att == NULL) {
echo ” “;
exit;
}

/* get the actual entity synonym value from the parameters */
$entity_orig_key = $entity.”.original”;
$xx = (array)$decoded->queryResult->outputContexts[0]->parameters;
$entity_orig = $xx[$entity_orig_key];

/* read in the CSV database and search for a match */

/* default negative response */
$resp = “Sorry, we could not find the price.”;
$csvfile = “grocery_prices.csv”;
$fdcsv = fopen($csvfile,’r’);

/* search for the first match */
while($line = fgetcsv($fdcsv,1024)) {
$p = $line[0];
$a = $line[1];
$v = $line[2];

if (strpos($p,$entity_orig)!==false) {
if ($a == $att) {
/* we found a match, set the response */
$resp = “The “.$a.” of “.$p.” is “.$v;
break;
}
}
}

fclose($fdcsv);

/* initialize the response */
$outj = ‘{
“fulfillmentText”: “**RESPONSE**”,
“fulfillmentMessages”: [{“simpleResponses”: {“simpleResponses”: [ {
“textToSpeech”: “**RESPONSE**”,
“displayText”: “**RESPONSE**”
}]}}]
}’;

/* create the final response string */
$outj = str_replace(“**RESPONSE**”,$resp,$outj);

/* send the response back to Dialogflow */
echo $outj;

?>

Information architecture, linguistic analysis, text annotation, writing, editing, scripting in Python and R