How to add verified caller ID's using twilio Node.js - node.js

Hey guys I am trying to use Twilio and add verified numbers to my list. So far it is just my own but I am trying to use the documentation with it saying this:
var accountSid = 'AC2394ac048859f6b48e7cdf630c29e631';
var authToken = "your_auth_token";
var Client = require('twilio').RestClient
var client = new Client(accountSid, authToken);
client.outgoingCallerIds.create({
friendlyName: "My Home Phone Number",
phoneNumber: "+14158675309"
}, function(err, callerId) {
if(err){
console.error(err);
} else {
console.log(callerId.sid);
}
});
to add them but all I get is this error saying this:
ReferenceError: client is not defined
client.outgoingCallerIds.list({ phoneNumber: "+14158675309" }, function(err, data) {
Does anyone know how to fix this?

Twilio developer evangelist here.
I'm not sure where you got the calling of RestClient on the Twilio module from, but if you could share that I will try to clear that up.
Instead of calling RestClient you can pass your account details straight to the module itself. To list your outgoing caller IDs you can do the following:
const accountSid = 'your_account_';
const authToken = 'your_auth_token';
const client = require('twilio')(accountSid, authToken);
client.outgoingCallerIds.list({ phoneNumber: '+14158675309' }, function(callerId) {
console.log(callerId.phoneNumber)
});
Let me know if that helps at all.
edit
Creating a new outgoing caller ID
To verify a new outgoing caller ID via the API you need to do two things, make the API request to create a new outgoing caller ID and then display the resultant code that the user receiving the call will then have to enter into the phone to verify.
You do this like so:
const accountSid = 'your_account_sid';
const authToken = 'your_auth_token';
const client = require('twilio')(accountSid, authToken);
client.outgoingCallerIds
.create({
phoneNumber: '+14158675309',
})
.then(function(callerId) {
// somehow display the validation code
console.log(callerId.validationCode);
});

Related

Unable to retrieve auth string from auth endpoint - received status: 500

I using react native and backend is node.I trying implement pusher in my app.
Object {
"error": "Unable to retrieve auth string from auth endpoint - received status: 0 from http://10.0.27.124:8070/pusher/auth. Clients must be authenticated to join private or presence channels. See: https://pusher.com/docs/authenticating_users",
"status": 0,
"type": "AuthError",
}
Here is my react native code :
const pusher = new Pusher('73286f08a5b2aeeea398', {
cluster: 'ap1',
authEndpoint: 'http://10.0.27.124:8070/pusher/auth',
});
console.log(pusher)
const presenceChannel = pusher.subscribe('presence-channel');
Here is my node js code :
exports.authPusher = function (req, res) {
const socketId = req.body.socket_id;
const channel = req.body.channel_name;
console.log(req.body);
const presenceData = {
user_id: 'unique_user_id',
user_info: { name: 'Mr Channels', twitter_id: '#pusher' },
};
const auth = pusher.authenticate(socketId, channel, presenceData);
res.send(auth);
};
Thank you for answering.
I think you just forgot to use quote marks around authEndpoint parameter. Pusher is trying to call http instead of http://10.0.27.124:8070/pusher/auth.
const pusher = new Pusher('73286f08a5b2aeeea398', {
cluster: 'ap1',
authEndpoint: 'http://10.0.27.124:8070/pusher/auth',
});
If you open network tab on the web-developers toolbar of your browser, you must be able to see the actual request and debug it from there.

Sending Proactive Messages from Azure functions to botservice - node

I am using botframework v4, but coming over from v3, I have not found any documentation that is similar to the code I use below but for v4, regarding sending proactive messages from Azure Function App
Below is the code I previously used but am having trouble adapting:
var builder = require('botbuilder');
// setup bot credentials
var connector = new builder.ChatConnector({
appId: process.env.MICROSOFT_APP_ID,
appPassword: process.env.MICROSOFT_APP_PASSWORD
});
module.exports = function (context, req) {
if (req.body) {
var savedAddress = req.body.channelAddress;
var inMemoryStorage = new builder.MemoryBotStorage();
var bot = new builder.UniversalBot(connector).set('storage', inMemoryStorage);
sendProactiveMessage(savedAddress, bot)
}
};
function sendProactiveMessage(address, bot) {
var msg = new builder.Message().address(address);
msg.textLocale('en-US');
var img = {
attachments: [{
contentType: "image/jpg",
contentUrl: latestUrl,
}]
};
msg.addAttachment(img.attachments[0]);
msg.text('hello');
bot.send(msg);
}
This works fine with v3 but not v4.
If possible I would also like to find a way to log a user out:
await botAdapter.signOutUser(innerDc.context, this.connectionName);
This is how I do it in the bot itself, but doing so from Azure Functions again is proving difficult.
Any help would be appreciated.
Great that you are making the move from v3 to v4! Have you had a look at Send proactive notifications to users? This example is pretty straight forward and can be used within an Azure function.
First you retrieve the Conversation Reference in your bot by calling TurnContext.getConversationReference(context.activity);. This is the reference you could use in your proactive function to open the conversation. In your case you provide that via the request body to a proactive function, so I will do the same in my example.
My proactive endpoint example is written in Typescript, however it works the same way in plain Javascript. Create a HTTP trigger in Azure Functions and use the following code. I have added comments inline for clarity.
const { BotFrameworkAdapter } = require('botbuilder');
// Create adapter.
// If you need to share this adapter in multiple functions, you could
// instantiate it somewhere else and import it in every function.
const adapter = new BotFrameworkAdapter({
appId: process.env.MicrosoftAppId,
appPassword: process.env.MicrosoftAppPassword
});
module.exports = async function (context, req) {
// Validate if request has a body
if (!req.body) {
context.res = {
status: 400,
body: "Please pass a conversation reference in the request body"
};
return;
}
// Retrieve conversation reference from POST body
const conversationReference = req.body;
// Open the conversation and retrieve a TurnContext
await adapter.continueConversation(conversationReference, async turnContext => {
// Send a text activity
// Depending on the channel, you might need to use https://aka.ms/BotTrustServiceUrl
await turnContext.sendActivity('Proactive hello');
});
context.res = {
body: 'Message sent!'
};
};
In the end you could make a request to this Azure Function, where you pass the Conversation Reference as body of the type application/json.
Extending this example with features like signOutUser is simple. You can call all functions within the continueConversation function, just as in a normal bot. You can even receive the adapter object there if you wish.
await adapter.continueConversation(conversationReference, async turnContext => {
// Sign user out
turnContext.adapter.signOutUser(turnContext, 'connection-name');
});

Twilio messages API does not allow variables or concatenated strings in its message body

I'm trying to send an SMS which contains a generated token to my phone. If I pass a normal hard-coded string to the message body, I get the text but if I pass in a variable or concatenated string, I get an error showing up on my Twilio dashboard: 30003 - Unreachable destination handset. However, I get a success response from Twilio even though it failed to send.
// twilio.js
const accountSid = process.env.TWILIO_ACCOUNT_SID;
const authToken = process.env.TWILIO_AUTH_TOKEN;
const client = require('twilio')(accountSid, authToken);
exports.sendSMS = async ({ phone, message }) => {
await client.messages.create({
to: phone,
from: process.env.TWILIO_PHONE_NUMBER,
body: message // this doesn't work
// body: 'Hello' works
});
};
// somewhere in other-file.js
const token = generateToken() // abc123
const message = `Your token is ${token}.`;
await twilio.sendSMS({
phone: user.phone,
message
});
Is there a workaround to this? What am I doing wrong here?

If MFA enabled in AWS cognito, do I need to create js on client side to call cognitoUser.authenticateUser() because of the promt for code?

I am using reactjs and node for server side.
As you can see in the "mfa required" part of the code below, if this is all on node, then I can't really do "prompt" the user for the code, I have to pass this back to the front end.
Tried solution: If I do pass the MFA required to front end and get the users input then send it back to node to call "respondToAuth" I am getting two MFA codes in my SMS message.
Have I tried other solutions?
I am hesitant to use amplify because everything is on the front end, I would ideally like to do my authentication on the back end (thus node).
Another option I am leaning towards is just using initiateAuth api instead of "cognitoUser.AuthenticateUser". This way I can get the challenge response and pass it on in sequence. But as per my initial question, I am wondering if I can implement the below code and be able to route users to input MFA code (without duplicating MFA sms message)
AWS.config.update({
region: process.env.Region
});
var AmazonCognitoIdentity = require('amazon-cognito-identity-js');
const poolData = { //--Moved to env variables
UserPoolId: process.env.UserPoolId, // your user pool id here
ClientId: process.env.ClientId // your app client id here
};
const userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);
router.post('/api/authenticateuser', (req, res) => {
const val = req.body;
var userData = {
Username: val.value.user, // your username here
Pool: userPool
};
var authenticationData = {
Username: val.value.user, // your username here
Password: val.value.pass, // your password here
};
const authenticationDetails = new AmazonCognitoIdentity.AuthenticationDetails(authenticationData);
const cognitoUser = new AmazonCognitoIdentity.CognitoUser(userData);
cognitoUser.authenticateUser(authenticationDetails, {
onSuccess: function(result) {
console.log('You are now logged in.');
console.log(result);
const accessToken = result.getAccessToken().getJwtToken();
const idToken = result.getIdToken().getJwtToken();
res.json({
accessToken,
idToken
});
},
onFailure: function(err) {
res.json(err);
},
mfaRequired: function(codeDeliveryDetails) {
// console.log("mfa enabled");
// var verificationCode = prompt('Please input verification code' ,'');
// cognitoUser.sendMFACode(verificationCode, this);
// res.json({ MFA:codeDeliveryDetails})
}
});
})

How to send the SMS message to multiple users separately (Not at a time) using nodejs?

I want to send the SMS to multiple users using node.js code.what is the procedure to be followed? I had little bit experience to send the sms to single user. But I don't know how to send the sms to multiple users. I have enclosed the code to send SMS to the single user. But before 6 Months these code works fine. But now it doesn't work. Can anyone provide the solution for this two problem?
var accountSid = 'cnsjs'; // Your Account SID from www.twilio.com/console
var authToken = 'chdcbhh'; // Your Auth Token from www.twilio.com/console
var twilio = require('twilio');
var client = new twilio(accountSid, authToken);
client.messages.create({
body: 'Hello hai I am vignesh Ravi . I sent the message from twilio account',
to: '+121331161616', // Text this number
from: '+18597401144' // From a valid Twilio number
}).then(function(message)
{
console.log("Messages sent to 1213311161616");
});
if you want to send multiple messages at the same time you need to use Promise.all. I have updated your code with something that i think will work for you i created it using bluebird.js because i am familiar with it and it has kickass tools.
tri this:
var accountSid = 'cnsjs'; // Your Account SID from www.twilio.com/console
var authToken = 'chdcbhh'; // Your Auth Token from www.twilio.com/console
var Promise = require('bluebird');
var twilio = require('twilio');
var client = new twilio(accountSid, authToken);
var promises = [];
// add all the different send promises to this array like following
promises.push(
client.messages.create({
body: 'Hello hai I am vignesh Ravi . I sent the message from twilio account',
to: '+121331161616', // Text this number
from: '+18597401144' // From a valid Twilio number
})
)
var result = {
sent: [],
failed: []
};
var finalPromise = Promise.all(promises.map(function (p) {
return Promise.resolve(p).reflect(); // resolve will convert it to bluebird promise and reflect will make it always successful
})).each(function (inspection) {
if (inspection.isFulfilled()) { //this means the send was successful
result.sent.push(inspection.value());
} else { //this means there was an error
result.failed.push(inspection.reason());
}
}).then(function () {
return result;
})
finalPromise.then(function (res) {
console.log(JSON.stringify(res))
})
you might have to fix the code a bit before it starts to work as you intend it
Edit
i made small changes to code where i am calling the collective promise at the end. give it a try and let me know if it works

Resources