Twilio SMS Messaging Tutorial

Search for a command to run...

This course will help you learn Framer as a beginner if you're looking to get into Web Design. I go into how to start using Framer with Stacks, Rows, Framers, I cover components, effects and responsiv

I decided to build a SaaS last month called Enhance AI, using OpenAI with GPT-3 to perform some interesting applications of AI to help programmers save time coding. I needed to pick a good database for this SaaS. As the title suggests, I ended up pic...

Introduction Storytelling is a very important skill in life. It is something that everyone does in their own way. When I first started my youtube and blogging journey, I had no idea that a good story would be the key to success. And I don't just mean...

In this article, I wanted to document my journey of building one as a developer over a short period, what technology I used, and how I did it, with a demo of the full product at the end! This article was also writing using the AI tools developed as p...

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.
You'll need a Twilio account, which you can get using the following link https://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.
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 http://localhost:3000
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.
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 https://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!