Skip to main content

One post tagged with "twilio"

View All Tags

· 8 min read

A programmer can code for days continously without a break. I have done it when I started my career as a programmer. In IT field, it gets worse if you continously work without taking 5 minutes break every 30 minutes. In this blog I will explain how you can find yourself to remind someone to get up and take that mandatory break.

PreRequisites:

Sign up Twilio

In order to yse Twilio, you need to sign up and purchase a voice enabled phone number. If you’re new user to Twilio, you can start with a free trial.

Sign up Azure:

In order to deploy your Azure function, you need to have Azure subscription. You can create a FREE Azure subscription to setup your Azure function. The free trial will provide you with 12 months of free services.

Steps to Create the Function:

Step 1 : Create the Function app

Let's start off by creating an app for our requirement. In the Azure portal, click + Create a Resource

When the Azure Marketplace  appears and in the list, click Compute. In the Featured list, click Function App (note: if Function App does not appear, then click See all).

Then you need to fill the function app settings, you can follow the image to setup your funciton,

Step 2 : Add Function

We just completed creating the function app and we need to add a function that provides the capability of alerting the user that is configured with a trigger. The trigger will start the function which sends the Twilio SMS message. We’ll be using a Timer trigger for this tutorial.

In the left menu, click Resource groups and select the resource group you created in the last step.

Click on the App Service which is highlighted. Once the page loads, click the + button next to Functions to create a new function.

Add a Function

On the next screen, you’ll need to choose a development environment. Since we’ll be creating the function in the Azure Portal, select In-Portal and Continue.

Select In Portal

Since we want to create a Timer trigger, you’ll need to select Timer and click Create.

You should now see TimerTrigger1 listed under Functions in the left menu.

Step 3 : Integrate with Twilio SMS

As the next step we need to integrate Twilio SMS with the function App we created. Under TimerTrigger1 click Integrate

Integrate Function

under Outputs, click + New Output and select Twilio SMS.

When you click on that, you will get a warning saying Extensions not installed. You’ll need to install the Mirosoft.Azure.WebJobs.Extensions.Twilio extension. You can do so by clicking Install. This process can take up to 20 minutes so just give it a moment to complete installation.

While the function extensions are getting installed, you need to update the values in the relevant fields, the values can be obtained from your Twilio dashboard as shown below,

and fill them in the environment variables after you installed the extension, you need to set the environment variables which will be used within the function.

Step 4: Set Environment variables

It's ok to hardcode the Twilio credentials in the output environment variables. However, if you are running this app in production you should always use environment variables so that you dont expose the credentials to others. As you obtained the values from the Twilio dashboard, copy and save those values,

You can create environment variables in the Azure Portal by going to the Overview tab for your function and click Configuration.

Add the environment variables one by one,

KeyValue
TWILIO_SIDACXXXXXXXXXXX
TWILIO_TOKENAuth token obtained from the Twilio dashboard
SENDER_NUMBERYour twilio number +94 77 330 XXXXX
RECIPIENT_NUMBERPhone number that recieves the message

Environment variables

You can create the first envrionment variable by clicking on the New Application Setting and repeat the same for rest of those variables as shown above,

New appsettings Configuration

Add the first setting TWILIO_SID

TWILIO_SID Environment Variable

Once you are done with each setting value click OK. When you are adding both SENDER_NUMBER and RECIPIENT_NUMBER be extra careful as it can be tricky and make sure to use the E.164 format referenced above. After all environment variables have been added click Save to save the updates that were made to the Application Settings.

Step 5 : Timer settings

Whenever you create a timer function, By default, Azure sets your function to trigger the text message every 5 minutes. You can change how frequent the timer triggers by going to the Integrate and updating the values in Timer trigger.

Goto your function and select on Integrate and then you need to update the value of the interval as you need. The Schedule field contains a sequence that using CRON expressions. For the purpose of testing the function, change the number 5 to the number 2 and click Save. You can later change the frequency after you confirm that the function works properly.

CRON Expression

If you're creating the Function App using Visual Studio code, follow this sample app to create a timer function which is more easier with Visual Studio Code.

Step 6: Modify function.json File

As we are done with all the configuration steps, now we need to update the function.json within our TimerTrigger1 function.  Go back over to the function app and click TimerTrigger1. On the far-right side of the screen, click View Files.

You will see two files:

  • function.json
  • index.js

Click function.json to open the file. Since the file is currently missing the “to”: “RECIPIENT_NUMBER”, we’ll need to add this to our file.

Now we need to add the logic to create the message and send the message using the Twilio to the relevant reciever.

Navigate to my Github repo and grab the code for this file. You’ll want to replace the existing code in the function.json file with the new code that you just copied from GitHub.

{
"bindings": [
{
"name": "myTimer",
"type": "timerTrigger",
"direction": "in",
"schedule": "0 */2 * * * *"
},
{
"type": "twilioSms",
"name": "message",
"accountSidSetting": "REPLACE_WITH_YOUR_ACCOUNT_SID",
"authTokenSetting": "REPLACE_WITH_YOUR_AUTH_TOKEN",
"from": "SENDER_NUMBER",
"to": "RECIPIENT_NUMBER",
"direction": "out"
}
]
}

Step 7 : Let's Add logic to the index.js file

When Azure creates a function, it adds default code to help setup your function. We will the code for the Twilio SMS message to this code.

In the View Files menu, click the index.js file. You’ll want to replace the existing code in the index.js file with the code below.

const twiAccountSid = process.env.TWILIO_SID;
const twiAuthToken = process.env.TWILIO_TOKEN;
const client = require('twilio')(twiAccountSid, twiAuthToken);
module.exports = async function (context, myTimer) {
var timeStamp = new Date().toISOString();
if (myTimer.IsPastDue)
{
context.log('JavaScript is running late!');
}
client.messages
.create({ from: process.env.SENDER_NUMBER,
body: "Time to have cofee and take a break for 5 minutes!",
to: process.env.RECIPIENT_NUMBER
})
.then(message => {
context.log("Message sent");
context.res = {
body: 'Text successfully sent'
};
context.log('JavaScript timer trigger done!', timeStamp);
context.done();
}).catch(err => {
context.log.error("Twilio Error: " + err.message + " -- " + err.code);
context.res = {
status: 500,
body: `Twilio Error Message: ${err.message}\nTwilio Error code: ${err.code}`
};
context.done();
});
}

Step 8 : Install the dependencies (Twilio)

As you can see the first line of the code is required to use twilio helper library. We’ll need to install the twilio-node from npm so that it’s available to our function. To do so, we’ll need to first add a new file to our function.

Add package.json file

In the View Files window, click Add. Type the file name package.json and click enter. You will see an empty content page in the middle of the screen.

Add Package.json

Add the code below to the package.json file.

{
"name": "doc247",
"version": "1.0.0",
"description": "Alert an employee with an SMS to take a break",
"main": "index.js",
"scripts": {
"test": "echo \"No tests yet...\""
},
"author": "Sajeetharan",
"dependencies": {},
"devDependencies": {
"twilio": "^3.0.0"
}
}

Now we have added Twilio as a dependency to the package.json file , as the next step we need to install it as a dependency on the environment itself. As you are aware you can install the dependencies using the deploy command as well as you can install it using the Kudu.

Note : Make sure to stop the Function app before you head over to Kudu.

Click on the Platform Features tab. Under Development Tools, click Advanced tools (Kudu). Kudu will open on it’s own in a new window.

Navigate to Kudu from the function app

In the top menu of the Kudu Console, click Debug Console and select CMD

Kudu Debug Console

In the command prompt, we’ll want to navigate to D:\home\site\wwwroot. You can do so by using the command cd site\wwwroot and press enter on your keyboard. Once you’re in wwwroot, run the command npm i twilio to install the package.

Install Dependencies Twilio

You will also notice a new node_modules folder added to the file structure. Back in the Overview tab for the function app, click Start.

node_modules Folder

Step 9 : Run and Test the Function

Back in the Overview tab for the function app, click Start. App and click TimerTrigger1. Make sure that you’re in the index.js file. Click Test next to View Files (far right-side of the screen). At the top of the index.js file, click Run

If everything was successful, the personshould receive a text message after 20 minutes with your message!

You can change the frequency for your timer by heading back to Integrate and changing the Schedule field. Be sure to read up on CRON expressions before entering a new frequency.

If you’re curious to learn more about Azure Functions, I would suggest taking this Microsoft Learn module. You can access complete source code from here. If you want to learn more on Azure visit http://azure360.info/ .Happy Coding!