Twilio - Incoming calls not being processed (quickstart) - node.js

I've sign up to start using Twilio and I'm trying to setup the quickstart (https://www.twilio.com/docs/voice/client/javascript/quickstart) and it's almost working but incoming calls are not being received by:
Client code (used on browser after getTokenCapabilities):
Twilio.Device.incoming(function (conn) {
log('Incoming connection from ' + conn.parameters.From);
var archEnemyPhoneNumber = '+12093373517';
if (conn.parameters.From === archEnemyPhoneNumber) {
conn.reject();
log('It\'s your nemesis. Rejected call.');
} else {
// accept the incoming connection and start two-way audio
conn.accept();
}
});
Code on Twilio Function for voice calls (consoles are always printed and else condition is never called:
exports.handler = function(context, event, callback) {
let twiml = new Twilio.twiml.VoiceResponse();
console.log('entrou aqui');
if(event.To) {
console.log('entrou ali');
// Wrap the phone number or client name in the appropriate TwiML verb
// if is a valid phone number
const attr = isAValidPhoneNumber(event.To) ? 'number' : 'client';
const dial = twiml.dial({
callerId: context.CALLER_ID,
});
dial[attr]({}, event.To);
} else {
twiml.say('Thanks for calling!');
}
console.log('callback');
callback(null, twiml);
};
/**
* Checks if the given value is valid as phone number
* #param {Number|String} number
* #return {Boolean}
*/
function isAValidPhoneNumber(number) {
return /^[\d\+\-\(\) ]+$/.test(number);
}
I've include my phone number as Verified Caller ID, got a number from Twilio and create the functions using template Twilio Client Quickstart.
On Twilio Client Quickstart, i've paste TwiML SID as TWIML_APP_SID and tried to use my phone number and the number from Twilio as CALLER_ID.
Also I've changed VOICE URL on TwiML configuration and changed the VOICE URL on phone number from twilio configuration.
Any ideas on what is missing or what is wrong? When I open on browser http://127.0.0.1:8080/, It's possible to make calls but I don't receive any call on browser when I call to twilio number.

In order to answer call, you need to have your token name identity in a tag in your VoiceResponse, here is an example.
exports.incomingVoiceResponse = function voiceResponse( to ) {
// Create a TwiML voice response
const twiml = new VoiceResponse();
// Wrap the phone number or client name in the appropriate TwiML verb
// if is a valid phone number
const attr = isAValidPhoneNumber(to) ? 'client' : 'number';
const dial = twiml.dial({
callerId: to,
});
dial[attr]({}, 'jesus');
console.log(twiml.toString())
return twiml.toString();
};
See the 'jesus' client tag I have put ? Here is the token generator side :
exports.tokenGenerator = function tokenGenerator() {
const identity = 'jesus';
const capability = new ClientCapability({
accountSid: config.accountSid,
authToken: config.authToken,
});
capability.addScope(new ClientCapability.IncomingClientScope(identity));
capability.addScope(new ClientCapability.OutgoingClientScope({
applicationSid: config.twimlAppSid,
clientName: identity,
}));
// Include identity and token in a JSON response
return {
identity: identity,
token: capability.toJwt(),
};
};
This works for me using the node quickstart as is and changing both of these functions.
However, don't forger to change the from 'number' to 'client' in function voiceResponse because it's an incoming call and not an outgoing.
const attr = isAValidPhoneNumber(to) ? 'client' : 'number';
instead of
const attr = isAValidPhoneNumber(to) ? 'number' : 'client';
Since the default nameGenerator from the client-quickstart-node from Twilio generates a random name, it isn't properly set when receiving incoming call.

Related

Stripe Webhook Signature Checks - Node js - IBM Functions / OpenWhisk

There is some kind of encoding issue when I try to verify the signature for a Stripe Webhook. I know it’s not an issue with the Stripe package itself because I get different signatures when trying to manually hash the body data and compare the HMAC-256SHA signature with the signature from Stripe in the headers. I have tried so many different things to so many different parts, that it’s possible I have had multiple mistakes.
You’re not able to see here, but the IBM Cloud Function has been set to pass raw HTTP data, and that’s why you the decoding function being used.
The webhook is successful without verifying the signatures.
The error generated by the Stripe event function is, “No signatures found matching the expected signature for payload. Are you passing the raw request body you received from Stripe?”
Note: Errors are not handled correctly here while trying to debug this issue.
const stripe = require('stripe')('sk_test_********’);
var crypto = require('crypto');
// tried with the CLI secret and the one from the dashboard.
const endpointSecret = 'whsec_****’;
// Convert the stripe signature in string format to a JSON object
function sig_conversion(data){
var sig_obj = {}
var data_list = data.split(",").map((x)=>x.split("="));
var data_json = data_list.map((x)=>{sig_obj[x[0]] = x[1]})
return sig_obj
}
function decode(args) {
var decoded = new Buffer.from(args.__ow_body, 'base64')//.toString('utf-8')
return {body: decoded}
}
function main(params){
//let sig = sig_conversion(params.__ow_headers['stripe-signature']);
let sig = params.__ow_headers['stripe-signature']
let signature = sig_conversion(params.__ow_headers['stripe-signature']);
//console.log(222, signature);
var data = decode(params);
let event;
// Trying to see the result from manually checking the signatures.
var signed_payload = data.body + "." + signature.t
var hmac = crypto.createHmac('sha256', endpointSecret);
var hmac_sig = hmac.update(signed_payload);
var gen_hmac= hmac_sig.digest('hex');
console.log(gen_hmac, 222, signature, 444)
try {
event = stripe.webhooks.constructEvent(JSON.parse(data.body), sig, endpointSecret);
//event = JSON.parse(data.body);
}
Here are some steps to help people trying the same thing (some of the steps are general steps not directly related to the problem from above).
Ensure that web actions are enabled under the Endpoints menu.
Check the option for Raw HTTP handling under the same screen (Most of the documentation you will see is in relation to using Node.js + Express. The error that people experience in Express is the same, which is that the raw signature data in the header and the body data is needed for the verifying the signature. This applies to regardless of whether you are using Stripe’s package or manually verifying the signatures.)
Process the body data from ‘base64’ encoding.
If the endpoint secret from the Stripe CLI tool doesn’t work, try the one from the dashboard; and vice-versa.
Note: People using Google Cloud Functions or Pub-sub will likely have similar issues with signature verification.
function decode(args) {
var decoded = new Buffer.from(args.__ow_body, 'base64')
return {body: decoded}
}
// Match the raw body to content type application/json
function main(params){
let sig = params.__ow_headers['stripe-signature']
var data = decode(params);
let event;
try {
event = stripe.webhooks.constructEvent(data.body, sig, endpointSecret);
}
// The rest is the same as the stripe boilerplate code.
catch (err) {
return {
body: {payload:''},
statusCode:200,
headers:{ 'Content-Type': 'application/json'}
};
}
// Handle the event
switch (event.type) {
case 'payment_intent.succeeded':
const paymentIntent = event.data.object;
console.log('PaymentIntent was successful!')
break;
case 'payment_method.attached':
const paymentMethod = event.data.object;
console.log('PaymentMethod was attached to a Customer!')
break;
// ... handle other event types
default:
// Unexpected event type
return {
body: {payload:''},
statusCode:200,
headers:{ 'Content-Type': 'application/json'}
};
}
// Return a response to acknowledge receipt of the event
return {
body: {payload:''},
statusCode:200,
headers:{ 'Content-Type': 'application/json'}
};
};

How to add IBM API authentication to my code?

Watson Assistant only supports one Webhook url. The issue is I have multiple nodes in Assistant that need to call different "Actions" I have hosted in IBM Cloud Functions. How can I do that? I tried to code and "Action" that uses the NPM Axios to call the other "Actions" but it fails as it lacks authentication.
Can someone tell me how to do it? I need the BASE URL to be athenticated via my IBM Cloud user API to grant access to my namespace.
this is the action I created that acts as a "Dispatch" for webhooks for Watson Assistant.
/**
*
* main() will be run when you invoke this action
*
* #param Cloud Functions actions accept a single parameter, which must be a JSON object.
*
* #return The output of this action, which must be a JSON object.
*
*
* Version: 1.5 beta (API HUB)
* Date: 24/04/2020
*
*/
const axios = require("axios");
// Change to your "BASE_URL". Type in the "Web Action" url without the name of it at the end. (must NOT contains the end '/')
// All "Actions" must be within the same namespace.
const BASE_URL = "https://jp-tok.functions.cloud.ibm.com/api/v1/web/
const POST = "post";
const GET = "get";
const ANY = "any";
const ALL = "all";
/* List all your API methods
1. method - API Name (This is the "Actions" name at the end of the Web Action URL or just the name)
2. attr - Attributes that should be available in the params object
3. rule - Currently supports 2 rules;
a) any - params is valid if "any" of the attributes are present
b) all - params is valid only if all attributes are present
4. httpmethod -Supports "POST" and "GET"
5. contains - Use for validating GET URL parameters
*/
const API_METHODS = [{
method: "Emails", // Change to your API method "Please put the function name located at the end of the url without "/" example "Email"
attr: ["client_email", "department_email"],
rule: ANY,
httpmethod: POST,
contains: null
},
{
method: "testapi", // If Watson needs to "GET" information to a user or athenticate a user
attr: [],
rule: ALL,
httpmethod: GET,
contains: "?ID="
},
]
// Returns true if the "params" is valid for the given API method
function isValidParam(method, params = {}) {
var attributes = [];
attributes = method.attr;
var isAny = method.rule === ANY;
for (let index = 0; index < attributes.length; index++) {
const attr = attributes[index];
if (isAny) {
if (Object.hasOwnProperty.call(params, attr)) {
return true;
}
} else {
if (!Object.hasOwnProperty.call(params, attr)) {
return false;
}
}
}
if (attributes.length === 0 && method.contains) {
return (JSON.stringify(params).indexOf(method.contains) > -1)
}
// if the code reaches this position, inverse of "isAny" should return the actual validation status.
return !isAny;
}
async function main(params) {
var result = [];
// Stop on first failure
// We iterate through all API methods. Because there can be more than one matching API for the given param type
for (let index = 0; index < API_METHODS.length; index++) {
const apiMethod = API_METHODS[index];
const url = BASE_URL + '/' + apiMethod.method;
if (isValidParam(apiMethod, params)) {
let response = apiMethod.httpmethod === POST ?
await axios.post(url, params) :
await axios.get(url + params); // Expects the parameter to be a string in this case like '?id=345343'
console.log(response);
result.push({
sent: true,
url: url,
request: params,
});
}
}
return {
sent: true,
details: result
};
}
// THe part of the code that needs to be copied to call other functions within the namespace.
/* const API_METHODS = [{
method: "Emails", // Change to your API method "Please put the function name located at the end of the url without "/" example "Email"
* attr: ["bamboo_email", "latitude_email", "latest_r_email", "department_email"],
rule: ANY,
httpmethod: POST,
contains: null
},
{
method: "testapi", // If Watson needs to "GET" information to a user or athenticate a user
attr: [],
rule: ALL,
httpmethod: GET,
contains: "?ID="
},
] */
When I run it in Watson Assistant I get the following error:
Webhook call response body exceeded [1050000] byte limit.response code: 200, request duration: 591, workspace_id: 150088ee-4e86-48f5-afd5-5b4e99d171f8, transaction_id: a8fca023d456d1113e05aaf1f59b1b2b, url_called: https://watson-url-fetch.watson-url-fetcher:443/post?url=https%3A%2F%2Fjp-tok.functions.cloud.ibm.com%2Fapi%2Fv1%2Fweb%2F23d61581-fa68-4979-afa2-0216c17c1b29%2FWatson+Assistant%2FAssistant+Dispatch.json (and there is 1 more error in the log)

Access Facebook Messenger User Profile API in DialogFlow

I'm building a cross-platform chatbot in Google's DialogFlow. I'd like to access the Facebook User Profile API to learn the user's first name.
I'm struggling to find advice on how (or if) I can make this happen.
https://developers.facebook.com/docs/messenger-platform/identity/user-profile/
Has anybody here achieved this?
I did that for one of my bots yesterday, you need 2 things, first the Page Token and second is the psid which is Page scope user ID.
On dialogflow, you will receive the request block with psid as sender id. You can find it at:
agent.originalRequest.payload.data.sender.id
This psid needs to be passed to api get request at
/$psid?fields=first_name with your page Token as accessToken to get the first name in response.
You need to make a call to Facebook Graph API in order to get user's profile.
Facebook offers some SDKs for this, but their official JavaScript SDK is more intended to be on a web client, not on a server. They mention some 3rd party Node.js libraries on that link. I'm particularly using fbgraph (at the time of writing, it's the only one that seems to be "kind of" maintained).
So, you need a Page Token to make the calls. While developing, you can get one from here:
https://developers.facebook.com/apps/<your app id>/messenger/settings/
Here's some example code:
const { promisify } = require('util');
let graph = require('fbgraph'); // facebook graph library
const fbGraph = {
get: promisify(graph.get)
}
graph.setAccessToken(FACEBOOK_PAGE_TOKEN); // <--- your facebook page token
graph.setVersion("3.2");
// gets profile from facebook
// user must have initiated contact for sender id to be available
// returns: facebook profile object, if any
async function getFacebookProfile(agent) {
let ctx = agent.context.get('generic');
let fbSenderID = ctx ? ctx.parameters.facebook_sender_id : undefined;
let payload;
console.log('FACEBOOK SENDER ID: ' + fbSenderID);
if ( fbSenderID ) {
try { payload = await fbGraph.get(fbSenderID) }
catch (err) { console.warn( err ) }
}
return payload;
}
Notice you don't always have access to the sender id, and in case you do, you don't always have access to the profile. For some fields like email, you need to request special permissions. Regular fields like name and profile picture are usually available if the user is the one who initiates the conversation. More info here.
Hope it helps.
Edit
Promise instead of async:
function getFacebookProfile(agent) {
return new Promise( (resolve, reject) => {
let ctx = agent.context.get('generic');
let fbSenderID = ctx ? ctx.parameters.facebook_sender_id : undefined;
console.log('FACEBOOK SENDER ID: ' + fbSenderID);
fbGraph.get( fbSenderID )
.then( payload => {
console.log('all fine: ' + payload);
resolve( payload );
})
.catch( err => {
console.warn( err );
reject( err );
});
});
}

Dialogflow assistant app exiting after successful fulfillment

I have a dialogflow assistant app with 3 intents. The first intent asks the user for location and name details from google. I am using a webhook for the fulfillment of this intent. I am able to extract the user information name and location, but after it is showing output from webhook, it is exiting from flow. But it is supposed to pass the location parameters to next intent and stay on the flow. Can anybody help me how to stop assistant from exiting?
Here is the webhook code
'use strict';
const functions = require('firebase-functions');
const DialogflowApp = require('actions-on-google').DialogflowApp;
exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
const requestPermission = (app) => {
app.askForPermissions('To report ', [app.SupportedPermissions.NAME, app.SupportedPermissions.DEVICE_PRECISE_LOCATION]);
};
const userInfo = (app) => {
if (app.isPermissionGranted()) {
const address = app.getDeviceLocation().coordinates;
const name = app.getUserName().givenName;
if (name) {
app.tell(`You are name ${name}`);
}
else {
// Note: Currently, precise locaton only returns lat/lng coordinates on phones and lat/lng coordinates
// and a geocoded address on voice-activated speakers.
// Coarse location only works on voice-activated speakers.
app.tell('Sorry, I could not figure out where you are.Plaese try again');
}
} else {
app.tell('Sorry, I could not figure out where you are.Please try again');
}
};
const app = new DialogflowApp({request, response});
const actions = new Map();
actions.set('request_permission', requestPermission);
actions.set('user_info', userInfo);
app.handleRequest(actions);
});
The problem is that you are calling app.tell() in your code which is a signal to the Assistant to send the message and then end the conversation.
If you want to send the message and then leave the microphone open for the user to reply, you should use app.ask() instead. It takes the same parameters - the only difference is that it expects the user to reply.
So that portion of your code might look something like
if (name) {
app.ask(`You are name ${name}. What would you like to do now?`);
}
(You should make sure that the prompt for the user is one that they will expect to reply. The review process will reject your Action if you reply and it isn't obvious that the user is supposed to reply to you.)

agent.set.context() not working Dialogflow fulfillment

We are facing issues while managing multiple user interaction at the same time in Dialogflow.
How we can manage user unique session as we are using custom event which will process our 3rd party API and then return a response to the specific user.
To manage User unique session We try Dailogflow Set/Get Context method, to set Context with Unique Id (using this id will store API response to the Redis server) from the first intent when a user makes a first request then will traverse that Unique Id through the custom event.
Will get that Unique Id from Context and grab data from Redis server which we stored in first intent.
We used agent.set.context() to set unique id but this method is not working with "dialogflow-fulfillment"  version ^0.5.0, To get this work we have updated the version with "^0.6.1". But this will provide other error like "UnhandledPromiseRejectionWarning: Error: No responses defined for platform: null".
Required Output: Context set with a unique id and will get a proper response.
Current Output: UnhandledPromiseRejectionWarning: Error: No responses defined for platform: null
async function searchFromAPI(agent){
axios.post('https://testApi.com', searchString.data, {headers: headers})
.then((resp) => {
response.data = resp;
redisClient.set(sessionId, JSON.stringify(response));
}
}).catch(error => {
response.error = true;
response.message = error.response.statusText;
redisClient.set(sessionId, JSON.stringify(response));
});
await customsleep(2000);
const sessionId = uuid.v4();
const contextData = {'name':'userSession','lifespan': 5,'parameters':{'sessionId':sessionId}};
agent.context.set(contextData);
console.log(contextData);
agent.add('We are processing your request, Could you please wait?');
agent.add(new Suggestion("Yes"));
agent.add(new Suggestion("No"));
}
// wait for 4.5sec and call custom event
async function followOne(agent){
await customsleep(4500);
agent.setFollowupEvent('followUpTwo');
}
// wait for 4.7sec then red API response from redis server and return
async function followUpTwo(agent){
await customsleep(4000);
sess = session;
//get context
const response = agent.context.get('userSession');
// get the sessionId, Get the data from redis server
agent.add(response);
}
async function PleaseWait(agent){
await customsleep(3500);
agent.setFollowupEvent('followUpOne');
}
I found the only workaround to reassign a new context object via context.set(ctx). Then it worked.
//update context to show full menu
let context = agent.context.get('user_data');
if (!context) throw "User_data context ius nod defined in PreferrenceAdd"
let context2 = new Object();
context2 = {'name': 'user_data', 'lifespan': 40,
'parameters': context.parameters};
console.log("ctx: = " + JSON.stringify(context2));
context2.parameters.new = false;
context2.parameters.refresh = true;
agent.context.set(context2);
Check this resource on how to set a new Dialogflow outgoing context
dialogflow webhook-client.
I hope this helps you?

Resources