Reputation: 507
I have the following code that gets executed as a lambda trigger for amazon sqs event.
require('dotenv').config()
const client = require('twilio')(process.env.TWILIO_ACCOUNT_SID, process.env.TWILIO_AUTH_TOKEN);
exports.handler = async function (event, context) {
console.info('phoneNumber', event.Records[0].messageAttributes.Phone.stringValue);
console.info('smsContent', event.Records[0].body);
console.info('from phone number', process.env.TWILIO_PHONE_NUMBER);
console.info('TWILIO_ACCOUNT_SID', process.env.TWILIO_ACCOUNT_SID);
console.info('TWILIO_AUTH_TOKEN', process.env.TWILIO_AUTH_TOKEN);
sendMessage(event);
return context.logStreamName;
}
function sendMessage(event) {
client.messages
.create({
body: event.Records[0].body,
from: process.env.TWILIO_PHONE_NUMBER,
to: event.Records[0].messageAttributes.Phone.stringValue
})
.then(message => {
console.info('messageId', message.sid)
}
,
err => {
console.error('delivery error', err);
});
}
I checked in the logs that all the relevant process.env parameters and their values are correct. When sendMessage function gets executes, there is no output. That is as if it is never executed.
I followed their documentations:
https://www.twilio.com/docs/sms/quickstart/node
They are very simple, yet the code fails to execute.
Upvotes: 0
Views: 371
Reputation: 507
This is a solution that worked for me. It was to return a callback.
exports.handler = async function (event, context,callback) {
try {
const message = await sendMessage(event);
console.log('message', message);
callback(null, {result: 'success'});
} catch (error) {
console.log('error', error);
callback("error");
}
// return context.logStreamName;
}
function sendMessage(event) {
return client.messages
.create({
body: event.Records[0].body,
from: process.env.TWILIO_PHONE_NUMBER,
to: event.Records[0].messageAttributes.Phone.stringValue
});
}
Upvotes: 0
Reputation: 4070
You are returning your function without waiting for the promise.
await for sendMessage in your handler: sendMessage(event)
should become await sendMessage(event)
Change your sendMessage method to return the promise: client.messages.create({...
should become return client.messages.create({...
Working version:
exports.handler = async function (event, context) {
await sendMessage(event);
return context.logStreamName;
}
function sendMessage(event) {
return client.messages
.create({
body: event.Records[0].body,
from: process.env.TWILIO_PHONE_NUMBER,
to: event.Records[0].messageAttributes.Phone.stringValue
})
.then(message => {
console.info('messageId', message.sid)
})
.catch(err => {
console.error('delivery error', err);
})
}
Upvotes: 1