Links

Custom App to Twilio

Overview

In this example, we’re going to use the Buildable SDK to send data from an internal app to Twilio in 2 easy steps:
  1. 1.
    Emit a message from our internal app
  2. 2.
    Transact the Message using Twilio
For this example, you'll need a few things:
  • A Buildable account and Buildable Secret Key
  • A Twilio account and API Key

Step 1: Emit a Message from your app

To emit a custom message from your app, follow these steps:
Install the Buildable Node SDK
> npm install @buildable/messages
Create an Environment Variable
Add your Buildable Secret Key values in a .env file
Emit your Message
We want to emit a message when an error occurs in our app. To do so, we’ll emit a message in the catch block of a try/catch statement.
const { createClient } = require('@buildable/messages');
const client = createClient(process.env.MY_BUILDABLE_SECRET);
async function myLogic() {
try {
// Throw an error for example purposes
throw new Error("Failed to run some logic...");
} catch (error) {
// Emit an event named my-app.error
client.emit('my-app.error', {
message: error?.message
});
console.log("An error occurred. Message sent to Buildable Messages.");
}
}
myLogic().then();
Ready to test?
If you run this code, you’ll notice a message in your Buildable Messages feed, which will look something like this:

Step 2: Transact the Message using Twilio

Create your Listener
Grab the my-app.error message from Buildable and send an SMS to notify a phone number of an error that has occurred.
const { createClient } = require('@buildable/messages');
const axios = require("axios");
const client = createClient(process.env.MY_BUILDABLE_SECRET);
const TO_PHONE_NUMBER = "1234567890"; // Your phone number
const TWILIO_ACCOUNT_SID = process.env.TWILIO_ACCOUNT_SID;
const TWILIO_AUTH_TOKEN = process.env.TWILIO_AUTH_TOKEN;
// Listen on my-app.error
client.on('my-app.error', async ({ event, payload }) => {
const smsBody = payload.message;
// Transact on Message using Twilio
await axios({
method: "post",
url: `https://api.twilio.com/2010-04-01/Accounts/${TWILIO_ACCOUNT_SID}/Messages.json`,
headers: {
"Content-Type": "application/x-www-form-urlencoded"
},
auth: {
username: TWILIO_ACCOUNT_SID,
password: TWILIO_AUTH_TOKEN
},
data: qs.stringify({
To: to,
body: smsBody
}),
});
}, {
platform: "custom",
label: "demo" // Secret key name
});
When the listener receives the my-app.error message, it will run the logic inside to send an SMS using the Twilio API with text passed in from the incoming message.

Ready to test?

Copy and paste the code into your system to emit your message!