Print raw Dialogflow query result fulfillment message - flutter

I have the following DialogFlow default and Facebook responses for an intent.
I have a simple Flutter app that calls detectIntent on a DialogflowAPI object that returns a response with query result. I want to print the raw fulfilment messages to console.
...
var response = await df.detectIntent(request, sessionPath);
List<GoogleCloudDialogflowV2IntentMessage> payloads = response.queryResult.fulfillmentMessages;
debugPrint("Got response length: ${payloads.length}");
payloads.forEach((element) => debugPrint(element.payload.toString()));
I get the below console output:
flutter: Got response length: 3
flutter: {text: this is some default text!, replies: [default option 1, default option 2]}
flutter: null
flutter: {replies: [default option 1, default option 2], text: this is some default text!}
There are 3 responses, of which 2 are printed correctly. It does not print the quick replies part of the facebook response.

Each GoogleCloudDialogflowV2IntentMessage has a payload member, which is a json-like Map<String, Object?>. You can print this out:
payloads.forEach((element) => debugPrint(element.payload.toString()));
Alternatively
There is also a toJson() method, which might give you more complete information. You can try printing that as well:
payloads.forEach((element) => debugPrint(jsonEncode(element.toJson())));
Note: you'll need to include import 'dart:convert';.

Related

How to create a chrome webRequest to validate response code

I want to check if my Linkedin Pixel tag is installed properly inside my webpages.
To validate, I would need to get a 302 response when the tag is fired.
Trying to create a chrome extension that could perform this validation.
chrome.webRequest.onSendHeaders.addListener(
(e) => {
console.log(e);
},
{
urls: ["https://px.ads.linkedin.com/*"],
}
);
--console.log object--
{documentId: 'E3A1D48B4697AC34E10A4D2A888CC8A9', documentLifecycle: 'active', frameId: 0, frameType: 'outermost_frame', initiator: 'https://www.theb2bhouse.com', …}
documentId: "E3A1D48B4697AC34E10A4D2A888CC8A9"
documentLifecycle: "active"
frameId: 0
frameType: "outermost_frame"
initiator: "https://www.theb2bhouse.com"
method: "GET"
parentFrameId: -1
requestId: "2395"
tabId: 2
timeStamp: 1652447005855.711
type: "image"
url: "https://px.ads.linkedin.com/collect?v=2&fmt=js&pid=2742940&time=1652447005855&url=https%3A%2F%2Fwww.theb2bhouse.com%2F"
[[Prototype]]: Object
Does anyone know how to send a webRequest to check if this above details got back a 302-redirect response?
On my inspect -> network request, I could see that the tag is fired correctly and recieved a response code of 302. Yet, I find the correct method to do the validation on webRequest.

flutter params array getting stringified on api request

In flutter dart am making an API call like below
Future<dynamic> fetchInstitutionsCall() {
List<int> requestedItemsList =[18,5];
return ApiManager.instance.makeApiCall(
callName: 'fetchInstitutions',
apiUrl: 'https://localhost:3000/api/v1/find_institutions/',
callType: ApiCallType.GET,
params: {
'user': 'sam',
'requested_items': requestedItemsList,
},
returnResponse: true,
);
}
The above request when received in server is received as a string instead of an array for the requested_items params like below
Parameters: {"user"=>"sam", "requested_items"=>"[18,5]"}
But the server is expecting in below format
Parameters: {"user"=>"sam", "requested_items"=>["18", "5"]}
How can we send a request in flutter so that requested_items params array won't get stringified when received in server?
Thank you

How to get latest bot response in rasa Chatbot?

How to get latest bot response with Rasa Chatbot?
For getting user input we use : tracker.latest_message['text']
So, what is syntax for getting latest bot response ?
Thanks
You can use the tracker.events list to fetch the latest bot event.
bot_event = next(e for e in reversed(tracker.events) if e["event"] == "bot")
This will go through the reversed list of events (making it from latest to oldest) and pick the first bot event using the next() function.
The event will be have the following format:
{'event': 'bot', 'timestamp': 1601789469.174273, 'text': 'Hey! How are you?', 'data': {'elements': None, 'quick_replies': None, 'buttons': None, 'attachment': None, 'image': None, 'custom': None}, 'metadata': {}}
There you can simply take the 'text' param if you are only interested in the message.

Why is my PaymentMethod ID not detected when I run my AWS stripe application via Docker?

I am learning web development and I am currently working on creating a lambda test application for stripe. The paymentMethod id from the front-end is not being detected by my lambda function when I run it locally by calling sam local start-api. I am doing my development on VS Code.
I followed the instructions on this page to create and run my application. My directory structure looks like this:
hello_world/app.py has my Lambda function.
The code for invoking the lambda end-point in script.jslooks like this:
var stripe = Stripe('pk_test_DIGITS');
var elements = stripe.elements();
form.addEventListener('submit', function(event) {
// We don't want to let default form submission happen here,
// which would refresh the page.
event.preventDefault();
stripe.createPaymentMethod({
type: 'card',
card: cardElement,
billing_details: {
// Include any additional collected billing details.
name: 'Jenny Rosen',
},
}).then(stripePaymentMethodHandler);
});
function stripePaymentMethodHandler(result) {
if (result.error) {
// Show error in payment form
} else {
// Otherwise send paymentMethod.id to your server (see Step 4)
fetch('http://127.0.0.1:3000/payment', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
payment_method_id: result.paymentMethod.id,
})
}).then(function(result) {
// Handle server response (see Step 4)
result.json().then(function(json) {
handleServerResponse(json);
})
});
}
}
I ran the application on the browser by doing this:
When I click on Pay from my browser I can see the response in the logs on my dashboard:
The following code is for my lambda function app.py:
import json
import stripe
import requests
import logging
stripe.api_key= "sk_test_DIGITS"
def process_payment(event, context):
try:
print("START PRINTING")
print(event)
print("END PRINTING")
intent = stripe.PaymentIntent.create(
payment_method = 'event["body"]["payment_method_id"]',
amount = 1555,
currency = 'usd',
confirmation_method = 'automatic',
confirm = True,
payment_method_types=["card"]
)
return {
"statusCode": 200,
"body": json.dumps({
'clientSecret': intent['client_secret'],
# "location": ip.text.replace("\n", "")
}),
}
except Exception as e:
return {
"statusCode": 400,
"body": json.dumps({
"message": str(e),
# "location": ip.text.replace("\n", "")
}),
}
My template.yaml is as follows:
Globals:
Function:
Timeout: 30
Resources:
StripePaymentProcessor:
Type: AWS::Serverless::Function
Properties:
CodeUri: hello_world/
Handler: app.process_payment
Runtime: python3.6
Events:
Payment:
Type: Api
Properties:
Path: /payment
Method: post
Outputs:
HelloWorldApi:
Description: "API Gateway endpoint URL for Prod stage for Payment function"
Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/payment/"
HelloWorldFunction:
Description: "Payment Lambda Function ARN"
Value: !GetAtt StripePaymentProcessor.Arn
HelloWorldFunctionIamRole:
Description: "Implicit IAM Role created for Payment function"
Value: !GetAtt StripePaymentProcessorRole.Arn
While keeping the browser window open, I ran the sam build command and it worked properly. After that I ran the sam local invoke command and it produced the following output:
I do not understand why event is empty. Should it not show the JSON data that got produced when I hit the pay button?
To do some trouble-shooting, I ran sam local start-api, invoked the POST method on Postman by pasting the JSON body from my Stripe logs:
What I did on Postman makes no sense to me and the snippet above raised another question for me. I do not understand why I see "message": "string indices must be integers" as a response on Postman.
EDIT:
After following wcw's suggestion I edited my fetch code to look like this:
I did not not see any written matter on the console by changing my code in this way.
I am keeping the browser open via the command prompt and I ran sam local start-api via the VS code console to keep http://127.0.0.1:3000/payment open. When I clicked on the pay button, I got the following response:
So the image above seems to indicate that the lambda function is not detecting the paymentmethod body.

When PUTting to a playlist on Soundcloud's API, the playlist doesn't actually get updated?

When I try to HTTP PUT a SoundCloud playlist through the API, with a data structure: {"tracks": [{"id": 12345}, {"id": 45678}]}, the playlist doesn't get updated. The API returns a 200 response with what was in the playlist, completely ignoring the modifications.
What I think might be wrong
The SoundCloud API doesn't accept that format of data
Somehow the authorization is invalid, even though it's returning a 200
The code:
import requests
playlist_url = 'https://api.soundcloud.com/playlists/XXXXX?client_id=XXXXX'
like_url = 'https://api.soundcloud.com/users/XXXXX/favorites?client_id=XXXXX'
likes = requests.get(like_url)
likes_json = likes.json()
# oauth2_token = requests.post('https://api.soundcloud.com/oauth2/token', data=opts).json()
oauth2_token = 'XXXXX'
playlist = {'tracks': []}
for like in likes_json[::-1]:
track_id = like['id']
playlist['tracks'].append({'id': track_id})
resp = requests.put('https://api.soundcloud.com/playlists/XXXXX', json=playlist, params={
'oauth_token': oauth2_token,
'client_id': 'XXXXX',
'client_secret': 'XXXXX'
})
It turns out I was simply sending the wrong data structure. It should have been {'playlist': {'tracks': [{'id': 1234}, {'id': 4567}]}}.
https://stackoverflow.com/a/28847716/2350164