Google Apps Script - Unable to query property from JSON data - json

dialogflow sends the following:
{
"responseId": "XXX-YYY-ZZZ",
"queryResult": {
"queryText": "random text",
"parameters": {
"command": "do it"
},
"allRequiredParamsPresent": true,
"fulfillmentText": "Sorry, can't understand it.",
"fulfillmentMessages": [
{
"text": {
"text": [
"Sorry, can't understand it."
]
}
}
],
"outputContexts": [
{
"name": "projects/xxx-vyyy/agent/sessions/xxx-yyy-zzz/contexts/__system_counters__",
"parameters": {
"no-input": 0,
"no-match": 0,
"command": "do it",
"command.original": "do it"
}
}
],
"intent": {
"name": "projects/xxx-vyyy/agent/sessions/xxx-yyy-zzz",
"displayName": "testCommands"
},
"intentDetectionConfidence": 1,
"languageCode": "en"
},
"originalDetectIntentRequest": {
"payload": {}
},
"session": "projects/xxx-vyyy/agent/sessions/xxx-yyy-zzz"
}
TypeError: Cannot read property 'parameters' of undefined (line 5, file "this-file")
and the goal is to query the command field. This is the current code:
function doPost(e) {
//EXTRACTION
var dialogflow = e.postData.contents;
var desiredField = dialogflow.queryResult.parameters.command;
}
but then this error thrown:
TypeError: Cannot read property 'parameters' of undefined (line 4, file "this-file")
I tried JSON.stringify(e) and e.postData.contents, but still not working.
Documentation on doPost() https://developers.google.com/apps-script/guides/web
and WebhookRequest sent by dialogflow https://cloud.google.com/dialogflow/docs/fulfillment-webhook#webhook_request
Thanks in advance!

At doPost(e), e.postData.contents is not parsed as JSON object. I think that your error message is due to this. So how about the following modification using JSON.parse()?
Modified script:
function doPost(e) {
//EXTRACTION
var dialogflow = JSON.parse(e.postData.contents); // Modified
var desiredField = dialogflow.queryResult.parameters.command;
}
Reference:
Web Apps

Related

AppScript - AppSheet API Post Issues

I'm attempting to send a row to an appsheet app with their provided API. I have it all set up in app script and I'm getting a code 200 (success) but it's not adding the data to the spreadsheet. Am I doing something wrong?
function testingAPI(){
let appId = APP ID HERE
var url = `https://api.appsheet.com/api/v2/apps/${appId}/tables/opportunity/Action`;
var options = {
"method": "post",
"headers": {
"applicationAccessKey": ACCESS KEY HERE
},
"httpBody": {
"Action": "Add",
"Properties": {
"Locale": "en-US",
"Location": "47.623098, -122.330184",
"Timezone": "Pacific Standard Time",
"UserSettings": {
"Option 1": "value1",
"Option 2": "value2"
}
},
"Rows": [
{
"IntentionSetID": "1H3t8Dt",
"AgentID": "11234",
"ActivityID": 12,
"taskComplete": true,
"taskVerified": false,
"task_verified_by": "",
"proof": "https://drive.google.com/open?id=1CpzebeLtAljqHTsFHvVCCDFc-A6aXC3O",
"agent_expected_part_detail": "",
"poc_expected_part_detail": '',
"assigned_point_value": '',
"points_assigned_by": "10/31/2014",
"actual_part_detail": "8:15:25",
"verification_date": "18:30:33"
}
]
}
};
var response = UrlFetchApp.fetch(url, options);
console.log(response.getResponseCode())
}
I was able to find that the API call is indeed going through, but it's saying the "Action" is missing:
{
"RestAPIVersion": 2,
"TableName": "opportunity",
"AppTemplateVersion": "1.000247",
"Errors": "'Action' is missing.",
"AppTemplateName": "e280cf5a-e2de-4d24-89d3-95d384a2c044",
"Operation": "REST API invoke",
"RecordType": "Stop",
"Result": "Success",
"ResultSuccess": true,
"StatusCode": "OK"
}
changing httpBody to payload got me a step further, so now it's recognizing the "add" aspect, but it's still not understanding the properties correctly. it's showing a bunch of escape characters.
REST API:
{
"Action": "Add",
"Properties": {},
"Rows": []
}
Properties:
{
"RestAPIVersion": 2,
"TableName": "opportunity",
"AppTemplateVersion": "1.000250",
"Action": "Add",
"Errors": "API 'Properties' does not have unexpected Type of 'JObject'. Value is: '{\r\n \"Action\": \"Add\",\r\n \"Properties\": \"{Timezone=Pacific Standard Time, Location=47.623098, -122.330184, Locale=en-US}\",\r\n \"Rows\": \"[Ljava.lang.Object;#489763c2\"\r\n}'",
"AppTemplateName": "e280cf5a-e2de-4d24-89d3-95d384a2c044",
"Operation": "REST API invoke",
"RecordType": "Start",
"Result": "Failure"
}
The AppSheets API POST https://api.appsheet.com/api/v2/apps/{appId}/tables/{tableName}/Action can be used to invoke an action. This means that the action should be created in AppSheet before it can be called.
Resources
Invoke an Action | AppSheet

Google Apps Script - GoogleJsonResponseException: API call to sheets.spreadsheets.values.update failed with error: Invalid values[1][0]

the goal is to query fields inside a JSON object . But when executed the error above is throwned.
Dialogflow is integrated inside Slack as an App. The Google Apps Script is the web app. Here is the code:
//Writes in a sheet the Slack User id
function doPost(e) {
//Parse incoming JSON from Dialogflow into an object
var dialogflow = JSON.parse(e.postData.contents);
//Extracts userId from Slack
var desiredField = dialogflow.originalDetectIntentRequest.payload.data.event.user;
//Instantiates Sheets function
var valueRange = Sheets.newValueRange();
//Value to insert in cell
var values = [[ desiredField]];
valueRange.values = values;
//Inserts value in cell
var result = Sheets.Spreadsheets.Values.update(valueRange, 'XXX-YYY-ZZZ', 'rangeReceivingData', {valueInputOption: 'RAW'});
}
and here's the incoming JSON:
{
"responseId": "XXX-YYY-ZZZ",
"queryResult": {
"queryText": "oi",
"action": "input.welcome",
"parameters": {
},
"allRequiredParamsPresent": true,
"fulfillmentText": "Oi!",
"fulfillmentMessages": [{
"text": {
"text": ["Oi!"]
}
}],
"outputContexts": [{
"name": "projects/test-agent-xxyy/agent/sessions/xxx-yyy-zzz/contexts/__system_counters__",
"parameters": {
"no-input": 0.0,
"no-match": 0.0
}
}],
"intent": {
"name": "projects/test-agent-xxyy/agent/intents/xxx-yyy-zzz",
"displayName": "Default Welcome Intent"
},
"intentDetectionConfidence": 1.0,
"languageCode": "pt-br"
},
"originalDetectIntentRequest": {
"source": "slack",
"payload": {
"data": {
"event_time": "1589561467",
"api_app_id": "xxxyyyzzz",
"type": "event_callback",
"event": {
"event_ts": "1589561467.000200",
"team": "xxxyyyzzz",
"blocks": [{
"type": "rich_text",
"block_id": "xxxyyyzzz",
"elements": [{
"elements": [{
"text": "oi",
"type": "text"
}],
"type": "rich_text_section"
}]
}],
"ts": "1589561467.000200",
"channel_type": "im",
"client_msg_id": "xxx-yyy-zzz",
"text": "oi",
"type": "message",
"channel": "xxxyyyzzz",
"user": "T1H2E3G4O5A6L7"
},
"authed_users": ["XXXYYYZZZ"],
"event_id": "xxxyyyzzz",
"token": "xxxyyyzzz",
"team_id": "xxxyyyzzz"
}
}
},
"session": "projects/test-agent-xxyy/agent/sessions/xxx-yyy-zzz"
}
also, the fulfillment response in dialogflow have this weird formating:
fields {
key: "action"
value {
string_value: "input.welcome"
}
} ... (this is inside the sheets api error response)
When debuging it was possible to query the respondeId field (the first field from the incoming JSON). It looks that the program is taking lots of processing time on queryng further fields and in the end it throws the error. Any suggestion?
Documentation references:
Writing in Sheets
Handling POST requests in apps scripts
Dialogflow documentation on webhooks
Thanks in advance!
Error, solved. First, point:
It was possible to recover the received JSON from the webhook by using JSON.stringify:
function doPost(e) {
//Parse incoming JSON from Dialogflow
var dialogflow = JSON.parse(e.postData.contents);
//Stringify webhook after parsing
var desiredField = JSON.stringify(dialogflow);
//Outputs value in sheet
var valueRange = Sheets.newValueRange();
//Value to insert in cell
var values = [[ desiredField]];
valueRange.values = values;
//Inserts value in cell
var result = Sheets.Spreadsheets.Values.update(valueRange, 'spreadSheetId', 'range',
{valueInputOption: 'RAW'});
}
The incoming JSON was as expected then it was just a matter of querying the desired field:
from this:
//Stringify webhook after parsing
var desiredField = JSON.stringify(dialogflow);
to this:
//Extracts userId from Slack
var desiredField = dialogflow.originalDetectIntentRequest.payload.data.event.user;
Error solved!

Cannot set key of conference solution in manifest file

I cannot set "key" property in manifest file of GSuit application
"conferenceSolution": [{
"onCreateFunction": "createConference",
"id": "messanger",
"name": "Some messanger",
"key": {
"type": "addOn"
},
"logoUrl": "https://logos.com/some/logo123.png"
}]
but on push, I get error that:
GaxiosError: "appsscript.json" has errors: Invalid manifest: unknown fields: [addOns.calendar.conferenceSolution[0].key]
at Gaxios._request (C:\Users\iyano\AppData\Roaming\npm\node_modules\#google\clasp\node_modules\gaxios\build\src\gaxios.js:85:23)
at processTicksAndRejections (internal/process/task_queues.js:93:5)
at async OAuth2Client.requestAsync (C:\Users\iyano\AppData\Roaming\npm\node_modules\#google\clasp\node_modules\google-auth-library\build\src\auth\oauth2client.js:350:18)
Sample request of how to create an event with conference data in Apps Script:
function myFunction() {
var calendarId = "primary";
var resource = {
"summary": "event with conference data",
"end": {
"date": "2020-04-10"
},
"start": {
"date": "2020-04-10"
},
"conferenceData": {
"createRequest": {
"requestId": "123",
"conferenceSolutionKey": {
"type": "eventNamedHangout"
}
}
}
};
var event=Calendar.Events.insert(resource, calendarId,{"conferenceDataVersion":"1"})
Logger.log(event.id);
}
If it is for an Addon - I assume that type should be addOn instead of eventNamedHangout.

JSON Import with Javascript, how to skip deferred exception?

I have written an javascript importer for a external json dataset
<script type="text/javascript" src="data.json"></script>
var importData = JSON.stringify(data);
var importCompany = data.report.company.name;
if(importCompany != ''){
jQuery('.company .name').text(importCompany);
}
All working perfectly :D
My issue is when I update the script to read data2.json and data.report.company.name doesn't exist, I get this error in the developer console
jQuery.Deferred exception: Cannot read property 'name' of undefined TypeError: Cannot read property 'name' of undefined
How do i overcome this issue?
Thanks
EDIT
data.json (external)
var data = {
"report": {
"company": {
"name": "XXX"
"other": "123"
},
"information": "GB-0-01777777",
"references": "2018-06-26T07:48:41.104Z"
}
data2.json (external)
var data = {
"report": {
"company": {
"other": "123"
},
"information": "GB-0-01777777",
"references": "2018-06-26T07:48:41.104Z"
}

Use Apps Script URLFetchApp to access Google Datastore Data

I want to experiment with Google Datastore via Apps Script because I have a current solution based on Google sheets that runs into timeout issues inherent in constantly transacting with Drive files. I've created a test project in Google cloud with a service account and enabled library MZx5DzNPsYjVyZaR67xXJQai_d-phDA33
(cGoa) to handle the Oauth2 work. I followed the guide to start it up here and got all the pertinent confirmation that it works with my token (and that removing the token throws an 'authentication failed prompt').
Now I want to start with a basic query to display the one entity I already put in. I can use the API Explorer here and run this query body:
{
"query": {}
}
and get this result:
{
"batch": {
"entityResultType": "FULL",
"entityResults": [
{
"entity": {
"key": {
"partitionId": {
"projectId": "project-id-5200707333336492774"
},
"path": [
{
"kind": "Transaction",
"id": "5629499534213120"
}
]
},
"properties": {
"CommentIn": {
"stringValue": "My First Test Transaction"
},
"Status": {
"stringValue": "Closed"
},
"auditStatus": {
"stringValue": "Logged"
},
"User": {
"stringValue": "John Doe"
},
"Start": {
"timestampValue": "2017-08-17T18:07:04.681Z"
},
"CommentOut": {
"stringValue": "Done for today!"
},
"End": {
"timestampValue": "2017-08-17T20:07:38.058Z"
},
"Period": {
"stringValue": "08/16/2017-08/31/2017"
}
}
},
"cursor": "CkISPGogc35whh9qZWN0LWlkLTUyMDA3MDcwODA1MDY0OTI3NzRyGAsSC1RyYW5zYWN0aW9uGICAgICAgIAKDBgAIAA=",
"version": "1503004124243000"
}
],
"endCursor": "CkISPGogc35wcm9qZWN0LWlkLTUyMDAxxDcwODA1MDY0OTI3NzRyGAsSC1RyYW5zYWN0aW9uGICAgICAgIAKDBgAIAA=",
"moreResults": "NO_MORE_RESULTS"
}
}
I try to do the same thing with this code:
function doGet(e)
{
var goa = cGoa.GoaApp.createGoa('Oauth2-Service-Account',
PropertiesService.getScriptProperties()).execute(e);
if(goa.hasToken()) {var token = goa.getToken();}
var payload = {"query":{}}
;
var result = UrlFetchApp.fetch('https://datastore.googleapis.com/v1/projects/project-id-5200707333336492774:runQuery',
{
method: "POST",
headers: {authorization: "Bearer " + goa.getToken()},
muteHttpExceptions : true,
payload: payload
});
Logger.log(result.getBlob().getDataAsString());
}
and get this error in the logger:
"error": {
"code": 400,
"message": "Invalid JSON payload received. Unknown name \"query\": Cannot bind query parameter. 'query' is a message type. Parameters can only be bound to primitive types.",
"status": "INVALID_ARGUMENT",
"details": [
{
"#type": "type.googleapis.com/google.rpc.BadRequest",
"fieldViolations": [
{
"description": "Invalid JSON payload received. Unknown name \"query\": Cannot bind query parameter. 'query' is a message type. Parameters can only be bound to primitive types."
}
]
}
]
}
}
If I try to use another word such as 'resource' or 'GqlQuery', I get this error:
"error": {
"code": 400,
"message": "Invalid JSON payload received. Unknown name \"GqlQuery\": Cannot bind query parameter. Field 'GqlQuery' could not be found in request message.",
"status": "INVALID_ARGUMENT",
"details": [
{
"#type": "type.googleapis.com/google.rpc.BadRequest",
"fieldViolations": [
{
"description": "Invalid JSON payload received. Unknown name \"GqlQuery\": Cannot bind query parameter. Field 'GqlQuery' could not be found in request message."
}
]
}
]
}
}
I can't tell from the API Documentation what my syntax is supposed to be. Can anyone tell me how to compile a functional request body from Apps Script to Datastore?
You need to set the contentType of your payload as well as stringify your JSON payload as follows:
var result = UrlFetchApp.fetch(
'https://datastore.googleapis.com/v1/projects/project-id-5200707333336492774:runQuery',
{
'method':'post',
'contentType':'application/json',
'headers': {authorization: "Bearer " + goa.getToken()},
'payload':JSON.stringify(payload)
}
);