Below is my code running on nodeJS server, I am trying to send an SMS message as soon as the 'child_added'
event is triggered
// Twilio Credentials
var accountSid = '<AccountSid>';
var authToken = '<authToken>';
var twilio = require("twilio");
var client = new twilio.RestClient(accountSid, authToken);
// TWILIO Function
client.messages.create({
to: "+12432056980", // This need to be obtained from firebase
from: "+14352058756",
body: "Hey There! Good luck on the bar exam!"
}, function(err, message) {
console.log(message.sid);
});
Below is the event that is triggered as soon as a child is added to firebase database, I would like to call the TWILIO Function (shown above) as soon as as the below event is triggered and also pass it the mobile number variable from the below function.
ref.limitToFirst(1).on('child_added', function(snapshot) { // This function triggers the event when a new child is added
var userDetails = snapshot.val();
var mobileNumber = userDetails.mobileNumber;
//*** I would like to call the TWILIO CODE at this point and pass it the 'mobileNumber' parameter
});
If the two operations are within the same file you can just wrap the Twilio
call in a function and call it from within the Firebase
operation like so...
function sendSMS(dest, msg) {
client.messages.create({
to: dest,
from: "+14352058756",
body: msg
}, function(err, message) {
console.log(message.sid);
});
}
ref.limitToFirst(1).on('child_added', function(snapshot) {
var userDetails = snapshot.val();
var mobileNumber = userDetails.mobileNumber;
sendSMS(mobileNumber, "Hey There! Good luck on the bar exam!");
});
If the Twilio
operation is in a different file, you can export it and require where you use Firebase
//twiliofile.js
module.exports.sendSMS = function(dest, msg) {
client.messages.create({
to: dest,
from: "+14352058756",
body: msg
}, function(err, message) {
console.log(message.sid);
});
}
-
//firebasefile.js
var sms = require('./twiliofile.js');
ref.limitToFirst(1).on('child_added', function(snapshot) {
var userDetails = snapshot.val();
var mobileNumber = userDetails.mobileNumber;
sms.sendSMS(mobileNumber, "Hey There! Good luck on the bar exam!");
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With