Twilio No Errors shown for Programmable Message - node.js

I am following Twilio's API for sending outbound messages.
I've followed their short code implementation using Nodejs.
Dependencies
"dependencies": {
"express": "^4.17.1",
"read-excel-file": "^4.0.6",
"twilio": "^3.0.0"
}
Code
const accountSid = '[account sid]';
const authToken = '[account authtoken]';
var client = require('twilio')(accountSid, authToken);
client.messages.create({
body: 'Hello from Node',
from: '[usa number]',
to: '[singapore number]'
})
.then((message) => console.log(message.sid));
i run the code with node index.js
but nothing comes out. I've tried changing vars to const and const to vars but nothing works.
Console shows nothing at all.

It looks like your promise is being rejected, at a .catch, to see what the error is. You can check to see if SMS Geographic permissions are set appropriately.
Something like:
const accountSid = '[account sid]';
const authToken = '[account authtoken]';
var client = require('twilio')(accountSid, authToken);
client.messages.create({
body: 'Hello from Node',
from: '[usa number]',
to: '[singapore number]'
})
.then((message) => console.log(message.sid))
.catch(err => console.log(err));

Related

twilio isn't sending sms nodejs

I use twilio to send sms after a order is placed, but it isn't sending any sms and also not console logging anything.
Code: npm i twilio
const accountSid = process.env.TWILIO_ACCOUNT_SID;
const authToken = process.env.TWILIO_AUTH_TOKEN;
const client = require("twilio")(accountSid, authToken);
exports.createOrder = (req, res) => {
const { orders, status, details } = req.body;
const order = new Order({
orders: orders,
status: status,
details: details,
});
order.save((error, order) => {
if (error) return res.status(400).json(error);
if (order) {
// if (res.status === 201) {
client.messages
.create({
body: "This is the ship that made the Kessel Run in fourteen parsecs?",
from: "+xxxxxxxxx",
to: "+xxxxxxxxxx",
})
.then((message) => console.log(message.sid));
// }
return res.status(201).json({ order });
}
});
};
LINK TO DOC (where I took the code) : https://www.twilio.com/docs/sms/quickstart/node
Twilio developer evangelist here.
There is likely an issue in sending your message, but the code you have is dropping errors, so you can't see what is going on. Try updating it to this:
client.messages
.create({
body: "This is the ship that made the Kessel Run in fourteen parsecs?",
from: "+xxxxxxxxx",
to: "+xxxxxxxxxx",
})
.then((message) => console.log(message.sid))
.catch(error => console.error(error));
Once you see what the error is, you will be able to fix it. My guess is that you have either configured your Account Sid and Auth Token incorrectly, or you are using a trial account and trying to send a message to a number you haven't verified yet, or you are trying to send a message to a country that isn't enabled.

Modify Twilio sample code to attach voicemail recoding and send by email

The following post from Twilio explains how to write and implement a function for sending the link of a recorded message to email.
https://www.twilio.com/blog/forward-voicemail-recordings-to-email
I want to attach to the voicemail recording rather than just send the link. Here is my attempt at modifying their code. Unfortunately it's causing a 500 error. I'm not very experience with NodeJS so perhaps you can help.
Dependencies for SendGrid and FS are included and this function worked perfectly until I modified it with FS, pathToAttachment, attachment variables and the attachments array.
//Initialize SendGrid Mail Client
const sgMail = require('#sendgrid/mail');
//FileSystem
const fs = require("fs");
// Define Handler function required for all Twilio Functions
exports.handler = function(context, event, callback) {
pathToAttachment = `${event.RecordingUrl}`;
attachment = fs.readFileSync(pathToAttachment).toString("base64");
// Build SG mail request
sgMail.setApiKey(context.SENDGRID_API_SECRET);
// Define message params
const msg = {
to: context.TO_EMAIL_ADDRESS,
from: context.FROM_EMAIL_ADDRESS,
fromname: 'Voicemail',
text: `URL is: ${event.RecordingUrl}`,
subject: `${event.From} (${event.country} / ${event.lang})`,
attachments: [
{
content: attachment,
filename: "Voicemail.wav",
disposition: "attachment"
}
]
};
// Send message
sgMail.send(msg)
.then(response => {
console.log("Neat.")
callback();
})
.catch(err => {
console.log("Not neat.")
callback(err);
});
};
This is how you modify the code from the Twilio blog:
Forward Voicemail Recordings to Email w/ Studio, Functions, & SendGrid
https://www.twilio.com/blog/forward-voicemail-recordings-to-email
.. to attach the email recording instead of link to it and how to add a from name as well as a from email address.
const request = require('request');
const sgMail = require('#sendgrid/mail');
exports.handler = function(context, event, callback) {
const fileUrl = event.RecordingUrl;
// Build SG mail request
sgMail.setApiKey(context.SENDGRID_API_SECRET);
request.get({ uri: fileUrl, encoding: null }, (error, response, body) => {
const msg = {
to: context.TO_EMAIL_ADDRESS,
from: {
"email": context.FROM_EMAIL_ADDRESS,
"name": `My company`
},
text: `Attached voicemail from ${event.From}.`,
subject: `${event.From}`,
attachments: [
{
content: body.toString('base64'),
filename: `MyRecording.wav`,
type: response.headers['content-type']
}
]
};
// Send message
sgMail.send(msg)
.then(response => {
console.log("Neat.")
callback();
})
.catch(err => {
console.log("Not neat.")
callback(err);
});
});
};
This is how you modify the code from

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?

Twilio return self._qs.unescape error

when i use Twilio to send SMS it return
TypeError: self._qs.unescape is not a function
packaje.json :
"dependencies": {
"twilio": "^2.11.1",
"typescript": "^2.8.3",
},
"devDependencies": {
"#types/lodash": "^4.14.108",
"#types/node": "^9.6.6",
"#types/twilio": "0.0.9"
}
And My Code :
var twilio = require('twilio');
var ACCOUNT_SID = "***";
var AUTH_TOKEN = "***";
TwilioClient.messages.create({
body: 'Welcome ',
to: '+*****'
from: '+****' // From a valid Twilio number
}).then((message) => console.log(message.sid));
and returned :
Exception in delivering result of invoking 'Register': TypeError: self._qs.unescape is not a function
you need to initiate the twilio client and then use it :
var client = new twilio(ACCOUNT_SID, AUTH_TOKEN);
client.messages.create({
body: 'Welcome ',
to: '+*****'
from: '+****' // From a valid Twilio number
}).then((message) => console.log(message.sid));
In Meteor, I should connect to the Twilio API from the server.
When I requested from the client, I got the error.

How to add verified caller ID's using twilio 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);
});

Resources