How to set dialogflow fulfillment response json context without using webhook client? - node.js

I want to create a rich response to Facebook integration using Dialogflow fulfillment. I tried using webhook but it's not working and then I try below way directly using response and now I am facing this context binding issue.
I tried below
let responseJson = {};
let rich = [
{
'text': {
'text': [
text
],
},
'platform': 'FACEBOOK'
},
];
responseJson.fulfillmentMessages = rich;
responseJson.outputContexts = context;
response.json(responseJson);
my context JSON
{ name: 'MAINTENANCE_REQUEST', lifespan: 5, parameters: { maintenanceRequest: maintenanceRequest }}

To add a custom payload without a webhook, go to your intent, and scroll to the bottom where it says "responses". Click on the plus sign (picture) and click on the facebook option. Click on the add responses -> custom payload. The format and available fields for the custom payload are described here. Delete the "Text Response" if it's there so the custom payload will be the only one to be returned.

Related

Send an alert notification from InfluxDb to Microsoft Teams

I am running an influxDb, on my server, and I created below:
Notification Check
Notification Endpoint (HTTP POST)
Notification Rule
All above are running successfuly
I have also created a webhook connector to Microsoft teams in order for InfluxDb send the notification alert to it.
However, for the Microsoft Teams webhook to work successfully, needs a key called "summary" inside request body of the POST request.
InfluxDb has no key called summary in their request body. Something like this:
{
"summary":"text"
}
I am looking to find out how to alter the request body InfluxDb sends, however there is nothing on their documentation.
Any ideas ?
The incoming webhooks send messages as a card. So, the title and summary fields are mandatory. It is by design.
This might be late but I've created my own team connection task in influxdb, where I can add mentions and buttons.
Basic Example:
Copy teams into a task in influxdb and add this next code at the end.
This Example adds a mention for Tom Cruise with its respective teams ID ( use Graph Explorer to get the correct IDs). It's possible to add multiple mentions as follow:
mentions = addMention(name : "James Bond",id:"007") + addMention(name : "Tom Cruise",id:"123456")
Adding Button / Buttons
button = addButton(type: "Action.OpenUrl", title: "Go To Google.com", url:"google.com" )
button2 = addButton(type: "Action.OpenUrl", title: "Go To Mohameds GITHUB", url:"https://github.com/Mohamedkrs" )
url= "https://..."
endpoint1 = endpoint(url: url)
mentions = addMention(name : "James Bond",id:"007")
button = addButton(type: "Action.OpenUrl", title: "Go To Google.com", url:"google.com" )
button2 = addButton(type: "Action.OpenUrl", title: "Go To Mohameds GITHUB", url:"https://github.com/Mohamedkrs" )
crit_statuses =from(bucket: "bucket")
|> range(start: -15s)
|> filter(fn: (r) => r["_measurement"] == "win_cpu")
|> endpoint1(mapFn: (r) => ({
title: "Memory Usage",
text: "<at>team user name</at>: ${r.host}: Process uses ${r._value} GB",
summary: "Alert",
mention: mentions,
button : button + button1
}),
)()

Unable to create contact with additional id

I am currently using SDK version 3.39.0 and version 0004 of the API_MKT_CONTACT service definition to try to create a new Contact with an AdditionalID in Marketing Cloud with the following code:
ODataRequestUpdate contactRequest =
contactService
.updateContactOriginData(contact)
.withHeader("Sap-Cuan-RequestTimestamp", getFormattedTime(System.currentTimeMillis()))
.withHeader("Sap-Cuan-SequenceId", "UpdatePatch")
.withHeader("Sap-Cuan-SourceSystemType", "EXT")
.withHeader("Sap-Cuan-SourceSystemId", "sdk-test")
.toRequest();
var additionalId =
AdditionalID.builder()
.externalContactID(pii.getId().toString())
.originOfContact(origin)
.originOfContact_2("EMAIL") //ContactAdditionalOrigin
.externalContactID_2(pii.getEmail()) //ContactAdditionalID
.build();
var additionalIdRequest = contactService
.updateAdditionalIDs(additionalId)
.replacingEntity()
.withHeader("Sap-Cuan-RequestTimestamp", getFormattedTime(System.currentTimeMillis()))
.withHeader("Sap-Cuan-SourceSystemType", "EXT")
.withHeader("Sap-Cuan-SourceSystemId", "sdk-test")
.toRequest();
// use low level API as a work around for https://github.com/SAP/cloud-sdk/issues/156
ODataRequestBatch requestBatch = new ODataRequestBatch(ContactService.DEFAULT_SERVICE_PATH, ODataProtocol.V2);
requestBatch
.beginChangeset()
.addUpdate(contactRequest)
.addUpdate(additionalIdRequest)
.endChangeset();
HttpClient httpClient = HttpClientAccessor.getHttpClient(contactsDestination);
ODataRequestResultMultipartGeneric batchResult = requestBatch.execute(httpClient);
batchResult.getResult(additionalIdRequest);
This results in the following error:
{
"error": {
"code": "SY/530",
"message": {
"lang": "en",
"value": "Inline component is not defined or not allowed (HTTP PUT)"
},
"innererror": {
"application": {
"component_id": "CEC-MKT-DM-IC",
"service_namespace": "/SAP/",
"service_id": "API_MKT_CONTACT_SRV",
"service_version": "0004"
},
"transactionid": "3B63A2A6CC9205E0E00604E1D31F1CDF",
"timestamp": "20210315142401.8432680",
"Error_Resolution": {
"SAP_Transaction": "For backend administrators: use ADT feed reader \"SAP Gateway Error Log\" or run transaction /IWFND/ERROR_LOG on SAP Gateway hub system and search for entries with the timestamp above for more details",
"SAP_Note": "See SAP Note 1797736 for error analysis (https://service.sap.com/sap/support/notes/1797736)",
"Batch_SAP_Note": "See SAP Note 1869434 for details about working with $batch (https://service.sap.com/sap/support/notes/1869434)"
},
"errordetails": []
}
}
}
I am using this documentation as a guide for building my requests (under the section "Create Contacts with Additional IDs"). When I run the example code in Postman it works as expected. Note that the payload for the AdditionalIDs is an empty JSON object.
So I enabled HTTP wire logs and noticed that the SDK seems to be including the following payload:
PUT AdditionalIDs(ContactAdditionalOrigin='EMAIL',ContactAdditionalID='wade.watts#theoasis.com',ContactID='ae46e174-52a3-4de6-8caa-57213151b295',ContactOrigin='<CONTACT_ORIGIN>') HTTP/1.1
Sap-Cuan-SourceSystemId: sdk-test
Accept: application/json
Sap-Cuan-SourceSystemType: EXT
Content-Type: application/json
Sap-Cuan-RequestTimestamp: '2021-03-15T14:24:00.828'
{"ContactOrigin":"<CONTACT_ORIGIN>","ContactID":"ae46e174-52a3-4de6-8caa-57213151b295","ContactAdditionalOrigin":"EMAIL","ContactAdditionalID":"wade.watts#theoasis.com","ContactAdditionalIdUUID":null,"ContactUUID":null,"ContactAddlIDIsInvalid":null,"MarketingAreas":[]}
Unfortunately, I can't seem to find a way to omit the payload/inline component while using the SDK so that it matches the example code. Is this an issue with the SDK or am I doing something wrong? Any help would be much appreciated!
Cheers!
UPDATE
Applying the suggested workaround from #matkuhr I changed my additionalIdRequest above to this and it worked:
ODataEntityKey key = new ODataEntityKey(ODataProtocol.V2)
.addKeyProperty(AdditionalID.EXTERNAL_CONTACT_ID.getFieldName(), mcContact.getContactId())
.addKeyProperty(AdditionalID.ORIGIN_OF_CONTACT.getFieldName(), origin)
.addKeyProperty(AdditionalID.ORIGIN_OF_CONTACT_2.getFieldName(), "EMAIL")
.addKeyProperty(AdditionalID.EXTERNAL_CONTACT_I_D_2.getFieldName(), mcContact.getEmailAddress());
var request = new ODataRequestUpdate(
ContactService.DEFAULT_SERVICE_PATH,
"AdditionalIDs",
key,
"{}",
UpdateStrategy.REPLACE_WITH_PUT,
null,
ODataProtocol.V2);
request.addHeader("Sap-Cuan-RequestTimestamp", getFormattedTime(System.currentTimeMillis()));
request.addHeader("Sap-Cuan-SourceSystemType", "EXT");
request.addHeader("Sap-Cuan-SourceSystemId", "sdk-test);
It's not you doing something wrong, it's also not the SDK, it's the service. The service seems to substantially deviate from the OData V2 conventions as well as basic HTTP conventions.
You can work around this by leveraging the low-level APIs of the SDK even more. Create the update request fully manually with the payload the service requires, e.g.:
ODataEntityKey key = new ODataEntityKey(ODataProtocol.V2)
.addKeyProperty(Contact.XYZ.getFieldName(), contact.getXyz())
request = new ODataRequestUpdate(
contactService.getServicePath(),
contact.getEntityCollection(),
key,
"{ }", // this will be the payload
UpdateStrategy.REPLACE_WITH_PUT,
null,
ODataProtocol.V2);
request.addHeader("key", "val");
// add more headers & parameters if needed and execute

DocuSign REST API DELETE method requires a body

For example to remove a member from a signing group you call:
/restapi/v2/accounts/1686083/signing_groups/{groupId}/users
and provide:
{
"users": [
{
"userName": "sample string 1",
"email": "sample string 2"
}
]
}
as the body
But my REST object (in ServiceNow) does not allow me to provide a body when I'm using the delete method. Am I just stuck?
I don't think there is any another way to remove the user from a SigningGroup using API. You can try to update the user in a Signing group to a Dummy Email so that original user will not get email for signing. And once in a while DS Admin can go to WEBApp and manually delete it, if Service now is not allowing DS API delete operation with a body.
If you're using RestMessageV2 in ServiceNow scripted Outbound REST, there's a setRequestBody method you can use to set the request body as a string:
Example in the docs here
var sm = new sn_ws.RESTMessageV2("Update user","post");
var body = "{ ...Message body content... }";
sm.setRequestBody(body);

Facebook Messenger Extensions on Microsoft Edge -- GET parameters absent

I want to use Facebook Messenger Extensions (opening a Webview) with Microsoft Edge.
My app sends a request to the REST API endpoint messages. The payload is as follows. Documentation on this.
{
"messaging_type":"RESPONSE",
"recipient":{
"id":"<id>"
},
"message":{
"attachment":{
"type":"template",
"payload":{
"template_type":"button",
"text":"Test text",
"buttons":[
{
"type":"web_url",
"url":"https://c0292fc0.ngrok.io/facebook/render_multi_choice?data=24561",
"title":"Test Button",
"webview_height_ratio":"full",
"messenger_extensions":"true",
"fallback_url":"https://c0292fc0.ngrok.io/facebook/render_multi_choice?data=24561"
}
]
}
}
}
}
When the user taps the button "Test Button" in Messenger, a Webview pops up and displays the response at the fallback URL / URL : https://c0292fc0.ngrok.io/facebook/render_multi_choice?data=24561
Note the URL contains one parameter, data = 24561
My Python Flask App receives the request:
#application.route("/facebook/render_multi_choice", methods=["GET"])
def render_multi_choice():
args = request.args
print(args)
return "OK"
The issue is that one would expect args to be printed out as:
ImmutableMultiDict([('data', 24561), ('fb_iframe_origin', '')])
Yet, it is printed out as:
ImmutableMultiDict([('data', ''), ('fb_iframe_origin', '')])
My flow works fine in Google Chrome, but NOT on Microsoft Edge. Do you have any idea what the issue could be? If I open the URL directly in the browser (without the Webview), things work as expected on Edge.

Send back rich responses to Actions on Google through Dialogflow webhook fulfillment

To get Google Assistant to display rich responses to the user, one must provide it with a response like the example on the Actions on Google docs. However, since I'm using Dialogflow as the intermediary party between my server and Google's, I need to provide some kind of response to Dialogflow in my webhooks to indicate that there should be a rich response. As you can see from that link, the docs mention how to send rich responses to FB Messenger, Kik, LINE, etc. but not Google Assistant.
What am I missing here? I see an option for rich responses in the Dialogflow web console, but there I can only seem to input hardcoded responses with no dynamic data from the server. What's the right way to do this?
Using the Dialogflow integration, the response JSON your webhook should return for a rich response will look like:
{
"data":{
"google":{
"expectUserResponse":true,
"noInputPrompts":[
],
"richResponse":{
"items":[
{
"simpleResponse":{
"textToSpeech":"Welcome to this Basic Card",
"displayText":"Welcome to this Basic Card"
}
},
{
"basicCard":{
"buttons":[
{
"title":"Button Title",
"openUrlAction":{
"url":"https://some.url"
}
}
],
"formattedText":"Some text",
"image":{
"url":"http://some_image.jpg",
"accessibilityText":"Accessibility text describing the image"
},
"title":"Card Title"
}
}
],
"suggestions":[
{
"title":"Aléatoire"
},
{
"title":"Top"
}
]
}
}
}
}
If you are using the Node.js library You can also use the provided methods for Dialogflow integration to build your rich response.
If you're using Node.js you should call the method buildRichResponse() and then add items as child of that object, like this:
app.ask(app.buildRichResponse()
.addSimpleResponse('A text to be spoken')
.addBasicCard(app.buildBasicCard('Some text to be displayed')
.setTitle('A title')
.addButton('Read more', 'https://example.google.com/something')
.setImage('https://example.google.com/image.png', 'Image alternate text')
.setImageDisplay('CROPPED')
)
);
That was an example for adding a BasicCard, you can see how to add Carousels, Lists and Suggestions Chips at https://developers.google.com/actions/assistant/responses#rich-responses

Resources