How to update session entity in Dialogflow? - dialogflow-es

I have defined an entity named visible_objects in my Dialogflow agent.
In the Dialogflow console I have put one entry named placeholder2 with a synonym placeholder.
When a user starts interacting with the agent, I'm updating this entity via the projects.agent.sessions.entity patch request. Following is the content of the request I'm sending.
`{
"name": "projects\/{PROJECT_NAME}\/agent\/sessions\/{SESSION}\/entityTypes\/visible_objects",
"entityOverrideMode": "ENTITY_OVERRIDE_MODE_OVERRIDE",
"entities": [
{
"value": "door",
"synonyms": [
"door"
]
},
{
"value": "desk",
"synonyms": [
"desk"
]
},
{
"value": "test tubes",
"synonyms": [
"test tubes",
"test",
"tubes"
]
}
]
}`
And this is the code I'm using to generate it:
<?php
$json = file_get_contents('php://input');
$request = json_decode($json, true);
$df_action = $request['queryResult']['action'];
$df_contexts = $request['queryResult']['outputContexts'];
$df_parameters = $request['queryResult']['parameters'];
// taken from private_key in my GCP authentication .json file
$CLIENT_ACCESS_TOKEN = "-----BEGIN PRIVATE KEY-----xxxxxxxxxxxxxx---END PRIVATE KEY-----\n";
// loop through the visible objects and prepare the output for dialogflow
foreach($_SESSION['STORY']['VISIBLE_OBJECTS'] as $visible_object)
{
unset($synonyms); // clear any existing synonyms
$synonyms = array();
$synonyms[] = $visible_object['name'];
if (strpos($visible_object['name'], ' ', 1))
{ // multiple words so split it as synonyms
$sub_objects = explode(' ', $visible_object['name']);
foreach($sub_objects as $sub_object)
$synonyms[] = $sub_object;
}
// add the object to the user entity
$user_ent_objects[] = array('value'=>$visible_object['name'], 'synonyms'=>$synonyms);
}
// prepare user_entity
$user_entity = array('name'=>$request['session'] . '/entityTypes/visible_objects', 'entityOverrideMode'=>'ENTITY_OVERRIDE_MODE_OVERRIDE', 'entities'=>$user_ent_objects);
// log for debugging
file_put_contents($SITE_DIR . '/webhook/user-entity-visible-objects.txt', json_encode($user_entity,JSON_PRETTY_PRINT));
$ch = curl_init('https://dialogflow.googleapis.com/v2/' . $request['session'] . '/entityTypes/visible_objects');
curl_setopt($ch, CURLOPT_POST, true); // tell it we're posting
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Authorization: Bearer ' . $CLIENT_ACCESS_TOKEN)); // set the headers
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($user_entity)); // load our data
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$curl_response = curl_exec($ch); // execute it
?>
I have an intent which is "look on the object name", where object name is mapped to the visible_objects entity. Here's what I'm seeing for some example phrases:
look on the placeholder -> "placeholder" is detected as object name
look on the test -> no object name detected
look on the tubes -> no object name detected
look on the desk -> no object name detected
Based on these responses is appears the session entity is not being updated as the new values are not detected and similarly the old value placeholder2 is not overwritten.
My webhook is written in PHP, and I'm not using the Google SDK (it is only in alpha for PHP). I am capturing the response from the request curl_exec but nothing is being returned.
Using curl_getinfo I'm seeing the following:
`[url] => https://dialogflow.googleapis.com/v2/projects/escaperoom-447aa/agent/sessions/SESSION_ID_MASKED/entityTypes/visible_objects
[content_type] => text/html; charset=UTF-8
[http_code] => 400
[header_size] => 144
[request_size] => 2002
[filetime] => -1
[ssl_verify_result] => 0
[redirect_count] => 0
[total_time] => 0.072034
[namelookup_time] => 0.023728
[connect_time] => 0.031063
[pretransfer_time] => 0.065598
[size_upload] => 394
[size_download] => 0
[speed_download] => 0
[speed_upload] => 5472
[download_content_length] => 1555
[upload_content_length] => 394
[starttransfer_time] => 0.065659
[redirect_time] => 0
[redirect_url] =>
[primary_ip] => 216.58.192.234
[certinfo] => Array
(
)
[primary_port] => 443
[local_ip] => 66.198.240.46
[local_port] => 41442
`
Can anyone see what I'm doing wrong here?

The issue is that you're not setting $CLIENT_ACCESS_TOKEN to an access token. You're setting it to your private key which should be associated with a service account.
You will need to use that private key to generate an access token - it is not the access token itself. Since there is a service definition for the Dialogflow service, you can choose to just generate a signed JWT for the service.

Related

Lookup function does not work within the Profile for Puppet

I am getting the following error in the event viewer on my node during a puppet run. I suspect the issue is with incorrect lookup function in my profile.
Could not retrieve catalog from remote server: Error 500 on SERVER: Server Error: Evaluation Error: Error while evaluating a Resource Statement, Scconfig::Coserveradmin[SomeSettings]:
parameter 'parameterA' expects a String value, got Undef
parameter 'parameterB' expects a String value, got Undef
parameter 'parameterC' expects a String value, got Undef
parameter 'parameterD' expects a String value, got Undef
coserveradmin is a define resource with all string parameters. I would like to do lookup of values from a Json file
{
"SASettings" : {
"Watchdog" : {
"ParameterA" : "somevalue",
"ParameterB" : "somevalue"
},
"Serversettings" : {
"ParameterC" : "somevalue",
"ParameterD" : "somevalue",
},
"GeneralSettings" : {
"ParameterE" : "somevalue",
"ParameterF" : "somevalue",
},
"customsettings_prod" : {
"ParameterG" :"somevalue",
"ParameterH" : "%{facts.hostname}.example-cloud.com"
},
"customsettings_dev" : {
"ParameterI" :"",
"ParameterK" : "%{facts.hostname}.example.net"
}
}
}
In my hiera.yaml file I have defined the name and path to the json file.
- name: "Desired Some Settings"
path: "default/serveradmin.json"
In profile I have the following code .
class profile::scconfig_someprofile_a {
.
.
.
$hname= $::facts['hostname']
$mac= "${facts['macaddress'].delete(':')}"
$adminpropeties = lookup('SASettings')
if $hname=~someregex {
scconfig::coserveradmin{ 'SomeSettings':
property1 => $adminpropeties['customsettings_prod.ParameterG'],
property2 => $adminproperties['Watchdog.ParameterA'],
property3 => $adminproperties['Watchdog.ParameterB'],
property4 => $adminproperties['Serversettings.ParameterC'],
.
.
.
.
and so on
.
macaddress => $mac,
}
elsif $hname=~someregex {
scconfig::coserveradmin{ 'SomeSettings':
property1 => $adminpropeties['customsettings_dev.ParameterI'],
property2 => $adminproperties['Watchdog.ParameterA'],
property3 => $adminproperties['Watchdog.ParameterB'],
property4 => $adminproperties['Serversettings.ParameterC'],
.
.
.
.
and so on
.
macaddress => $mac,
}
Also adding the code for the "define" resource as requested.
define scconfig::coserveradmin(
String $Property1,
String $Property2,
String $Property3,
String $Property4,
.
.
.
String $macaddress,
) {
$dscmoduleversion = lookup('requires.modules.codsc.version')
if $dscmoduleversion != '' {
$module = {
'name' => 'codsc',
'version' => $dscmoduleversion,
}
}else{
$module = 'codsc'
}
$configname1='someconfig1'
$configname2='someconfig2'
$configname3='someconfig3'
dsc { 'someconfig1':
require => lookup('requires.cloudopssoftware'),
resource_name => 'Someresourcename',
module => $module,
properties => {
configname => $configname1,
Prop1 => $Property1,
Prop2 => $Property2,
Prop3 =>$Property3,
},
}
dsc { 'someconfig2':
require => lookup('requires.cloudopssoftware'),
resource_name => 'someresourcename2',
module => $module,
properties => {
configname => $configname2,
Prop1 => $Property4,
Prop2 => $Property5,
Prop3 =>$Property6,
},
}
dsc { 'someconfig3':
require => lookup('requires.cloudopssoftware'),
resource_name => 'someresourcename3',
module => $module,
properties => {
configname => $configname3,
Prop1 => $Property6,
Prop2 => $Property7,
Prop3 =>$Property8,
.
.
.
Propn => $macaddress
},
}
Please note that the last property which is the macaddress is evaluated within the profile class therefore I don't see any error for it.
Any ideas what could be the issue.
I suspect the issue is with incorrect lookup function in my profile.
That does not appear to be the case. If your lookup() call were not successfully looking up and returning a hash then you would get a different error when you tried to extract values.
I guess it's possible that you're retrieving the wrong hash -- which would be a matter of your hiera configuration and / or data, not the lookup() call itself -- but whether it's the right hash or the wrong one, the syntax you are trying to use to extract the data from it is not matched to the hash structure presented in the question. For example, this expression
$adminpropeties['customsettings_prod.ParameterG']
attempts to retrieve the value whose key is 'customsettings_prod.ParameterG', but the data presented contain no such key.
What you seem to want is
$adminpropeties['customsettings_prod']['ParameterG']
That extracts the value having key 'customsettings_prod', and, that value being a hash itself, extracts its value associated with key 'ParameterG'.
Alternatively, you may find the dig() function convenient for extracting data from nested data structures such as yours:
dig($adminpropeties, 'customsettings_prod', 'ParameterG')

DocuSign Api creating envelope in Production

I have a problem with creating Envelope through the Api.
The authorization is performed without errors.
$options = new \DocuSign\eSign\Api\AuthenticationApi\LoginOptions();
$loginInformation = $authenticationApi->login($options);
I get this in response:
LoginInformation {
#container: array:2 [
"api_password" => null
"login_accounts" => array:1 [
0 => LoginAccount {
#container: array:11 [
"account_id" => "xxxxx"
"account_id_guid" => null
"base_url" => "https://na2.docusign.net/restapi/v2/accounts/xxxxx"
"email" => "xxxxx#xxxxxx.com"
"is_default" => "true"
"login_account_settings" => null
"login_user_settings" => null
"name" => "xxxxxxx, LLC"
"site_description" => ""
"user_id" => "xxxxxxxxxxxxxxxxxxx"
"user_name" => "xxxxxx Contracts Team"
]
}
]
]
}
But when I’m trying to create the Envelope this way:
$envelopeApi->createEnvelope($this->config->getAccountId(), $envelop_definition, $options);
I get this error: «[401] Error connecting to the API (https://www.docusign.net/restapi/v2/accounts/xxxxx/envelopes)”
This error notifies me that I’m not authorized. This code works properly in Sandbox.
I think that the problem is in settings of account - maybe there is a lack of special rights...
You need to use the right production platform. The right production platform is determined by the DocuSign Account ID.
See step 1 in the Post Go Live document.

Azure Schema Extension - Error message:Object reference not set to an instance of an object

I'm testing Azure Schema Extensions with a simple groovy script to the Microsoft Graph API. I first query for a list of schema extensions and this seems to work (though I am not sure where the extensions in the response have been set, I assume they are there by default). I then try to POST a schema extension but this fails with this error message:
[error: [
code:InternalServerError,
message:Object reference not set to an instance of an object.,
innerError:[request-id:xxxxx-xxxx-xxx-xxxxxx, date:2018-05-14T00:46:00]]]
This is the code for the GET query and the response:
def uriTestGET = "https://graph.microsoft.com/v1.0/schemaExtensions?"
def httpTestGET = new HTTPBuilder(uriTestGET)
httpTestGET.ignoreSSLIssues()
httpTestGET.request(GET,JSON) { req ->
httpTestGET.parser.'application/json'
headers.'Authorization' = 'Bearer ' + AzureToken
headers.'Content-Type' = 'application/json'
response.failure = { resp, json ->
println "GET Failure. GROUP: ${resp.statusLine}"
println(json)
}
response.success = { resp, json ->
println "GET Success. GROUP: ${resp.statusLine}"
println(json)
}
}
Response
[
#odata.context:https://graph.microsoft.com/v1.0/$metadata#schemaExtensions,
#odata.nextLink:https://graph.microsoft.com/v1.0/schemaExtensions?$skiptoken=XXXXXXXXXX,
value:[[
id:adatumisv_exo2,
description:sample desccription,
targetTypes:[Message],
status:Available,
owner:xxxxxx-xxxx-xxxx-xxxx,
properties:[
[name:p1, type:String],
[name:p2, type:String]]],
[id:circuitid_globals,
description:Circuit ID Graph Global Schema,
targetTypes:[Group, User], .. etc
And the following POST request:
def uriTestPOST = "https://graph.microsoft.com/v1.0/schemaExtensions?"
def httpTestPOST = new HTTPBuilder(uriTestPOST)
httpTestPOST.ignoreSSLIssues()
httpTestPOST.request(POST,JSON) { req ->
httpTestPOST.parser.'application/json'
headers.'Authorization' = 'Bearer ' + AzureToken
headers.'Content-Type' = 'application/json'
body = [
"id":"TestExtension",
"description": "Test to add user object schema extension",
"status": "Available",
"targetTypes": ["user"]
]
response.failure = { resp, json ->
println "POST Failure. GROUP: ${resp.statusLine}"
println(json)
}
response.success = { resp, json ->
println "POST Success. GROUP: ${resp.statusLine}"
println(json)
}
}
This gets the response:
[error:[
code:InternalServerError,
message:Object reference not set to an instance of an object.,
innerError:[request-id:xxxx-xxxx-xxxx-xxxx, date:2018-05-14T00:46:00]]]
Updated Body looks like this -
body = [
"id":"TestExtension",
"description": "Test to add user object schema extension",
// "status": "Available",
"targetTypes": ["User"],
"properties" : [["name": "ExtensionProperty", "type":"String"]]
]
And this is the new error message:
[error:[
code:Authorization_RequestDenied,
message:Insufficient privileges to complete the operation.,
innerError:[request-id:xxxx-xxxx-xxxx-xxxx, date:2018-05-14T05:09:41]]]
I've decoded the token and it shows the following roles are included:
Decoding the token it states the following roles:
"roles": [
"User.ReadWrite.All",
"Directory.ReadWrite.All",
"User.Invite.All" ]
I've been adding additional permissions to get this to work, these seem to be greater privileges than is required as far as I can see.
The system automatically chooses between using Application or Delegated permissions based on the OAuth Grant you've chosen:
Client Credentials Grant = Application
Authorization Code Grant = Delegated
Implicit Grant = Delegated
This is because you need an actual User to authenticate if you want them to delegate your application to act on their behalf. Without a User authenticated there isn't anyone to delegate permissions so you need to operate under Application scopes.

Azure Table Service REST API error

I would like to execute inset table entity REST API in Table Storage Service but it doesn't work.
I referred this doc.
My request code is here,
<?php
// storage account name
$account = "mystgaccount";
$tablestoragename = "mytablename";
$accessKey = "myaccesskey";
$date = gmdate('D, d M Y H:i:s T',time());
$api_version = "2015-12-11";
$url = "https://$account.table.core.windows.net/$tablestoragename";
$method = "POST";
$body = '{"Address":"MountainView","Age":23,"AmountDue":200.23,"CustomerCode#odata.type":"Edm.Guid","CustomerCode":"c9da6455-213d-42c9-9a793e9149a57833","CustomerSince#odata.type":"Edm.DateTime","CustomerSince":"2008-0710T00:00:00","IsActive":true,"NumberOfOrders#odata.type":"Edm.Int64","NumberOfOrders":"255","PartitionKey":"mypartitionkey","RowKey":"myrowkey"}';
$stringToSign = [
// VERB
$method,
// Content-MD5
'',
// Content-Type
'',
// Date
$date,
];
$stringToSign = array_merge($stringToSign, ["/$account/$tablestoragename"]);
$stringToSign = implode("\n", $stringToSign);
$signature = base64_encode(hash_hmac('sha256', $stringToSign, base64_decode($accessKey), true));
$headers = [
"x-ms-date:{$date}",
"x-ms-version:$api_version",
"Authorization:SharedKey $account:{$signature}",
"Content-Type: application/json",
];
$ch = curl_init();
$options = array(
CURLOPT_URL => $url,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_CUSTOMREQUEST => $method,
CURLOPT_SSL_VERIFYPEER => FALSE,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_POSTFIELDS => http_build_query($body),
);
curl_setopt_array($ch, $proxy_options);
curl_setopt_array($ch, $options);
$response = curl_exec($ch);
var_dump($response);
echo curl_error($ch);
curl_close($ch);
?>
Response
"<?xml version="1.0" encoding="utf-8"?><m:error xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata"><m:code>AuthenticationFailed</m:code><m:message xml:lang="en-US">Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature.
RequestId:b93fe560-0002-0028-129a-571361000000
Time:2017-11-07T07:34:13.3303714Z</m:message></m:error>"
I read related questions but it hasn't resolved yet :(
Do you have any ideas?
One possible reason for this error could be because of Content-Type header. You're specifying this header in your request but is not included in your $stringToSign. Please try again by changing your $stringToSign to something like:
$stringToSign = [
// VERB
$method,
// Content-MD5
'',
// Content-Type
'application/json',
// Date
$date,
];

Custom Document Fields

I'm using the dev account and the demo.docusign.net site to test out the API. I want to create a template with a document that has custom data fields. I created a template and on the page where you drag fields on to the document, I created a custom field. I called it "Last Name". I saved the custom field and saved the template. Now I want to create a new document for signing through the API and populate that field. Using the Walkthroughs as a guide, I was able to create a new draft envelope from a template. I then wanted to populate the custom field with data. However, this is failing. I'm getting the following error:
{
"errorCode": "INVALID_REQUEST_BODY",
"message": "The request body is missing or improperly formatted."
}'
Below is my code based off the Walkthroughs. In addition to having a custom field attached at design time, I wanted to test dynamically adding a new custom field and modifying it as well. So, first I make a POST request to add a new field and set it using the Recipients/Tabs API. Then I make a GET request to get the Tabs for the recipient so I can capture the Tag ID. Then I make a PUT request to modify the field and that's where I get the error message. But the request body looks fine to me and it contains the only required field for TagId. I assume the only other needed field is one to set the value. The same request body works fine for the POST request. I just copied it and changed the fields. The POST works fine and I can validate the added field by opening it in the Console. The new field is there. It's just the PUT to modify that isn't working.
/////////////////////////////////////////////////////////////////////////////////////////////////
// STEP 1 - Add New Tab
/////////////////////////////////////////////////////////////////////////////////////////////////
$curl = curl_init($baseUrl . "/envelopes/" . $envelopeId . "/recipients/1/tabs" );
$data = array (
'textTabs' =>
array (
0 =>
array (
'documentId' => '1',
'pageNumber' => '1',
'tabLabel' => 'test tab',
'value' => 'test',
),
),
);
$data_string = json_encode($data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string),
"X-DocuSign-Authentication: $header" )
);
$json_response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ( $status != 201 ) {
echo "error calling webservice, status is:" . $status;
exit(-1);
}
$response = json_decode($json_response, true);
curl_close($curl);
//--- display results
/////////////////////////////////////////////////////////////////////////////////////////////////
// STEP 2 - Get recipient tab information
/////////////////////////////////////////////////////////////////////////////////////////////////
$curl = curl_init($baseUrl . "/envelopes/" . $envelopeId . "/recipients/1/tabs" );
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
"X-DocuSign-Authentication: $header" )
);
$json_response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ( $status != 200 ) {
echo "error calling webservice, status is:" . $status;
exit(-1);
}
$response = json_decode($json_response, true);
curl_close($curl);
$lastNameTabID = $response['textTabs'][0]['tabId'];
$testTabID = $response['textTabs'][1]['tabId'];
//--- display results
/////////////////////////////////////////////////////////////////////////////////////////////////
// STEP 3 - update tab value
/////////////////////////////////////////////////////////////////////////////////////////////////
$curl = curl_init($baseUrl . "/envelopes/" . $envelopeId . "/recipients/1/tabs" );
$data = array (
'textTabs' =>
array (
0 =>
array (
'tabId' => $testTabID,
'value' => 'Some Value',
),
),
);
$data_string = json_encode($data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_PUT, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string),
"X-DocuSign-Authentication: $header" )
);
$json_response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ( $status != 201 ) {
echo "error calling webservice, status is:" . $status;
exit(-1);
}
$response = json_decode($json_response, true);
curl_close($curl);
And here is the output of the Request Body
data_string= '{"textTabs":[{"tabId":"627883d0-542c-40c7-a58c-ce68d9e057e1","value":"Some Value"}]}'
I appreciate some guidance.
Thanks
Joe
I think this is easier than we think. You should be able to define the additional tag in the post to create the envelope. Below is part of my json to define a template role and text tabs. The first one is a field defined in the Template labeled "Company". The second one is a data field I'm adding on the fly and placing on the 3rd page with XY coordinates. You can also place this using anchor text.
"templateRoles": [
{
"tabs": {
"textTabs": [
{
"tabLabel": "Company",
"value": "Acme Inc"
},
{
"tabLabel": "business",
"value": "widgets",
"pageNumber": "3",
"documentId": "1",
"yPosition": "300",
"xPosition": "300",
"locked": false
}
]
},
"roleName": "Customer",
"name": "Customer Bob",
"email": "signerrob#outlook.com"
}
],
Alright, so I did a little digging and think I have what we need here. First, to get the Recipient ID as well as associated Tab ID's for the envelope, use the following GET: v2/accounts/:accountId/envelopes/:envelopeId/recipients. This will give you what you need to edit existing tags. Once you have the info here, you can use the PUT v2/accounts/:accountId/envelopes/:envelopeId/recipients/:recipientId/tabs to edit the tabs you're looking to edit. Here is a sample JSON request I sent using Postman to successfully update a text tabs value.
{
"textTabs": [
{
"tabId": "c75d32c4-8024-48c0-975a-acc232b20212",
"value": "ABC Corp",
}
]
}
To add tabs to that recipient, use the same URL as the edit, but use a POST.

Resources