Adrian Twarog
Adrian Twarog

Adrian Twarog

Twilio SMS Messaging Tutorial

Twilio SMS Messaging Tutorial

Twilio is a cloud communications app platform that enables you to build applications that talk to thousands of businesses around the world.

In this tutorial, we are going to check out how to use Twilio together with NodeJs to create SMS messages and receive and respond to them too.

  1. Getting started
  2. Setting up the server
  3. Sending a message
  4. Receiving a message

1. Getting Started

You'll need a Twilio account, which you can get using the following link twilio.com as well as a number that is ready to use.

First, we are going to install the main packages we will use for the nodejs server:

npm install express twilio dotenv --save

These will be used in our first file which will be index.js This file will host our web server.

2. Setting up the server

We are going to configure our server using a dotenv file. This will allow us to use environment variables to configure our server. Create a file named .env and add the following lines to it. Jump into the Twilio Dashboard to get the following details and put them into your env file.

TWILIO_ACCOUNT_SID=
TWILIO_ACCOUNT_AUTH=

We can later access these files in our server. Next, we are going to create a simple express server that listens on port 3000 and replies back with success if a get request is done. This will in in a new file called index.js.

const app = require('express')()
We will apply bodyParser and set the twilio module up next:
app.use(express.json());
app.use(express.urlencoded({
  extended: true
}));
const accountSid = process.env.SIDconst authToken = process.env.AUTHconst client = require('twilio')(accountSid, authToken);
const MessagingResponse = require('twilio').twiml.MessagingResponse

Finally, we will listen to '/' path for any get requests:

app.get('/',(req,res)=>{
res.send('Success!');
})

To run the server we will use node but first we will need to set the port and then listen to it:

const PORT = process.env.PORT || 3000
app.listen(PORT, () => {    console.log('Server listening on port ' + PORT)})

Finally we run the following command in our terminal to listen to the server: node index.js

Then point your browser to localhost:3000

3. Sending a message

Now we are ready to send our first message through the Twil server. I've setup a route using /send-message which will call the client from twilio and create a test message to send.

app.get('/send-message', async (req, res) => {
    let response = await client.messages.create({
        body: "I am testing",
        from: "+61480031902",
        to: "+61477789861",
    })
    res.json({
        success: true,
        message: response
    })
})

We can use Postman to make a request to our server. Perform a get request to this route to ensure it sends the message.

4. Receiving a message

We are going to add a webhook into Twilios backend to get this working. Under the number > manage > active numbers, we will select the number we are using. Near the bottom there is a section for webhooks for Messaging. This webhook will listen to SMS's send to the number and server them back to our express server.

I am using ngork to host my domain for the webhook, but if you have your own domain or URL which is public facing, you can add your own. You can find it ngrok.com so in my case I will add the following:

http://a775605b0374.ngrok.io/sms

Then inside my app, I'll create the code to listen for this webhook, it will be as follows. The message received will be inside req.body.Body which we can console log out, while the output will allow us to send a reply.

app.post('/sms', async (req, res) => {
    console.log(req.body.Body)
    const output = "Testing a reply"
    const twiml = new MessagingResponse();
    const msg = twiml.message(output);
    res.writeHead(200, { 'Content-Type': 'text/xml' })
    res.end(twiml.toString())
})

That's basically it. You can add more features, like a chatbot or something specific inside of this response. I took this to another level, creating a chatbot of shorts which you can check out in the video I created to accompany this tutorial.

It will go into more detail for every single step and how to produce the SMS sending, receiving and communication!

 
Share this