I'm using Twilio Functions as a webhook to send Slack messages anytime an error occurs. The error message is successfully sent to Slack. However, this triggers Error code 504 (runtime application timed out) in Twilio. From the Twilio documentation, it seems I'm not properly implementing the callback method. Is there something I'm missing?
const https = require("https");
// Make sure to declare SLACK_WEBHOOK_PATH in your Environment
// variables at
// https://www.twilio.com/console/runtime/functions/configure
exports.handler = function(context, event, callback) {
const { AccountSid } = event;
const message = `New error for Twilio Account ${AccountSid}.`
const slackBody = JSON.stringify({
channel: "#channel",
icon_emoji: ":test_tube:",
username: "Twilio Alert",
attachments: [{
fallback: "twilio alert",
color: "#d00000",
pretext: "",
text: message
}]
});
// Form our request specification
const options = {
host: "hooks.slack.com",
port: 443,
path: context.SLACK_WEBHOOK_PATH,
method: "POST",
headers: {
"Content-Type": "application/json",
"Content-Length": slackBody.length
}
};
// send the request
const post = https.request(options, res => {
// only respond once we're done, or Twilio's functions
// may kill our execution before we finish.
res.on("end", () => {
// respond with an empty message
return callback(null);
});
});
post.on('error', (e) => {
console.log(e);
});
post.write(slackBody);
post.end();
}
Related
When I Hit ms graph API with my Nodejs code to send the email, an email is sent with no error displayed but the email is received in the outlook sent email which I'm using
I have proper accessToken what happing behind this please help here
Code below
const sendNotification = async (from, message) => {
const access_token = await getAuthToken();
try {
const response = await axios({
url: `${GRAPH_ENDPOINT}/v1.0/users/${from}/sendMail`,
method: "POST",
headers: {
Authorization: `Bearer ${access_token}`,
"Content-Type": "application/json",
},
data: JSON.stringify(message),
});
console.log("sendNotification status", response.statusText);
} catch (error) {
console.log(error);
}
};
I am using Twilio to create an 'attendance line' where employees can provide information about why they will be absent and then Twilio will send separate, curated messages to supervisors and human resources.
To do this, I've created a Flow in Twilio Studio and I would like to use a Twilio Function to handle sending the mass SMS messages notifying users of a new absence.
I am passing parameters to the function like name, dept, shift, reason, etc with the intent to then share these values via SMS.
I am having the hardest time getting all of these different values properly into the body of the message.
exports.handler = function(context, event, callback) {
// Create a reference to the user notification service
const client = context.getTwilioClient();
const service = client.notify.services(
context.TWILIO_NOTIFICATION_SERVICE_SID
);
const notification = {
toBinding: JSON.stringify({
binding_type: 'sms', address: '+1XXXXXXXXXX',
binding_type: 'sms', address: '+1XXXXXXXXXX',
}),
body: 'New Attendance Notification',
event.question_name,
event.question_dept,
event.question_reason,
event.contactChannelAddress,
};
console.log(notification);
// Send a notification
return service.notifications.create(notification).then((message) => {
console.log('Notification Message',message);
callback(null, "Message sent.");
}).catch((error) => {
console.log(error);
callback(error,null);
});
};
Now I know the 'body' of the message above will not work but I'm a bit lost...
The text below is how I would like my SMS message to read out when sent.
New Attendance Notification
Name: event.Name
Dept: event.Dept
Reason: event.Reason
Contact: event.ContactChannelAddress
Is what I am trying to accomplish even possible?
Something like this...
exports.handler = function(context, event, callback) {
// Create a reference to the user notification service
const client = context.getTwilioClient();
const service = client.notify.services(
context.TWILIO_NOTIFICATION_SERVICE_SID
);
const bindings = [
'{ "binding_type": "sms", "address": "+14071234567" }',
'{ "binding_type": "sms", "address": "+18021234567" }'
];
const notice = `New Attendance Notification\nName: ${event.question_name}\nDept: ${event.question_dept} \nReason: ${event.question_reason}\nContact: ${event.contactChannelAddress} \n`;
// Send a notification
service.notifications.create({ toBinding: bindings, body: notice }).then((message) => {
console.log('Notification Message',message);
callback(null, "Message sent.");
})
.catch((error) => {
console.log(error);
callback(error,null);
});
};
I am using Twilio Studio for to collect messages for our small church. When someone records a voicemail, I am using a function to send the recording URL to the group members. Here is what that function looks like currently:
var groupmembers = [
{
name: 'Person1',
number: '+11111111111'
},
{
name: 'Person2',
number: '+11111111111'
}
];
exports.handler = function(context, event, callback) {
let twiml = new Twilio.twiml.MessagingResponse();
groupmembers.forEach(function(member) {
// Now, forward on the message to the group member, using the sender's name
twiml.message(`Text from ${event.senderFrom}: ${event.senderMessage}`, {
to: member.number
});
})
callback(null, twiml);
};
This gives me a '12200 Schema validation warning' with the detail: Invalid content was found starting with element 'Message'. One of '{Play
I'm fairly sure the issue is because I am trying to send an SMS during a call but I am not sure how to update my TWIML or Studio flow to accommodate for this.
Any help is appreciated!
you need the REST API rather then TwiML in this case. You could use code similar to what is shown below to do this.
Make sure to check the box below, under Function Config for your Function,
exports.handler = function(context, event, callback) {
const twilioClient = context.getTwilioClient();
let groupMembers = [
{
name: 'Person1',
number: '+14701111111'
},
{
name: 'Person2',
number: '+18082222222'
},
{
name: 'Person3',
number: '+18021111111'
}
];
function sendSMS(member) {
return twilioClient.messages.create({
from: '+13054444444',
to: member.number,
body: 'Hello World!'
});
}
let promises = [];
groupMembers.forEach((member) => {
console.log(member);
promises.push(sendSMS(member));
});
Promise.all(promises)
.then((values) => {
console.log(values);
callback(null,"Success");
})
.catch(error => {
console.log(error);
callback("Failure");
});
};
Is there a way to send email from Twilio function? I understand that we can use sendgrid. I am looking a simpler solution.
Twilio evangelist here. 👋
As of now, you can use SendGrid from within a Twilio Function. The code below does the job for me and I just sent an email via a function
exports.handler = function(context, event, callback) {
const sgMail = require('#sendgrid/mail');
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
const msg = {
to: 'sjudis#twilio.com',
from: 'test#example.com',
subject: 'Sending with SendGrid is Fun',
text: 'and easy to do anywhere, even with Node.js',
html: '<strong>and easy to do anywhere, even with Node.js</strong>',
};
sgMail.send(msg)
.then(() => {
callback(null, 'Email sent...');
})
.catch((e) => {
console.log(e);
})
};
The above email will most like end up in spam as test#example.com is not a very trust worthy email address. If you want to send emails from your own domains additional configuration is needed.
To run the code inside of the function, you have to make sure to install the sendgrid/mail mail dependency and provide the sendgrid token in the function configuration.
If you want to use this function to power e.g. messages you have to make sure that your return valid TwiML. :) When you create a new function you will get examples showing on how to do that.
Hope that helps. :)
Another way is to use the SendGrid API
const got = require('got');
exports.handler = function(context, event, callback) {
const requestBody = {
personalizations: [{ to: [{ email: context.TO_EMAIL_ADDRESS }] }],
from: { email: context.FROM_EMAIL_ADDRESS },
subject: `New SMS message from: ${event.From}`,
content: [
{
type: 'text/plain',
value: event.Body
}
]
};
got.post('https://api.sendgrid.com/v3/mail/send', {
headers: {
Authorization: `Bearer ${context.SENDGRID_API_KEY}`,
'Content-Type': 'application/json'
},
body: JSON.stringify(requestBody)
})
.then(response => {
let twiml = new Twilio.twiml.MessagingResponse();
callback(null, twiml);
})
.catch(err => {
callback(err);
});
};
};
Source: https://www.twilio.com/blog/2017/07/forward-incoming-sms-messages-to-email-with-node-js-sendgrid-and-twilio-functions.html
I'm trying to send e-mails with MS Graph 1.0 and I have not any get any result or response. E-Mails haven't been sent and sendMail method don't return any error o message... it only says "null".
My code is based on this example https://github.com/microsoftgraph/msgraph-sdk-javascript#post-and-patch and looks like this:
// Initialize Graph client
const client = graph.Client.init({
authProvider: (done) => {
done(null, accessToken);
}
});
try {
// construct the email object
var mail = {
subject: "Microsoft Graph JavaScript Sample",
toRecipients: [{
emailAddress: {
address: "mail#domain.com"
}
}],
body: {
content: "<h1>MicrosoftGraph JavaScript Sample</h1>Check out https://github.com/microsoftgraph/msgraph-sdk-javascript",
contentType: "html"
}
};
client
.api('/me/sendMail')
.post({message: mail}, (err, res) => {
console.log("---> " + res);
});
console.log("Try ends");
} catch (err) {
parms.message = 'Error retrieving messages';
parms.error = { status: `${err.code}: ${err.message}` };
parms.debug = JSON.stringify(err.body, null, 2);
res.render('error', parms);
}
I guess mail var needs a header, but anyway, API should return me something, right? And, obviously, which is the problem with the email sending?
I finally added rawResponse to .post call and look at err log...
client
.api('/me/sendMail')
.header("Content-type", "application/json")
.post({message: mail}, (err, res, rawResponse) => {
console.log(rawResponse);
console.log(err);
});
... and I could see that I had problem with my authentication token. So, I was using the api correctly and code from the question is ok.