Messaging Service with Twilio!

Mahedi Hasan Jisan
3 min readOct 19, 2021
Twilio!

“The Twilio Customer Engagement Platform can be used to build practically any digital experience, using capabilities like SMS, WhatsApp, Voice, Video, email, and even IoT, across the customer journey.”

That being said, let’s create a messaging service using Twilio. You have to create an account in Twilio and it is going to be on the trial version.

→ Take a phone number using the trial version that can be used for messaging.

Trial Version Number!

→ We are going to be using MessagingResponse service from Twilio. In this article, we are going to use our mobile to send a text to that phone number that we got from Twilio. In return, MessagingResponse will return something back as a response. Make sense why it’s called MessagingResponse ?

→Now as a response, we are going to use Beautiful Soup to extract information from IMDB based on marvel movie names!

The Code:

SMS Bot!

→ The endpoint of the app is “/sms” and as you can see from line 15, Twilio will receive a “movie name” from the user which is you.

→ To extract the information from IMDB, we need the unique ID number for each movie, which we set in a dictionary so that we can find it easily using the movie name.

→ Then, we used the requests and BeautifulSoup library to get the page response and page content. Using JSON, the page content can be turned into JSON format, which is easier to find specific information such as movie names and descriptions.

→ Line 27 & 28 were used to create a response object using MessagingResponse() library from Twilio.

→ Line 34: Put the return information in the message object to return it as a string in line 35.

Codes are pretty simple in this example. We have used flask and Twilio to build an SMS chatbox! Well, let’s fire it up!

python bot.py!

The above picture says the server is running on HTTP://127.0.0.1:5000/ which is a local server using port 5000.

How will Twilio communicate with the local server?

The answer is: Ngrok

Ngrok is a cross-platform application that exposes local server ports to the Internet. Public URLs for building webhook integration. Now, since the local server is using port 5000, then we have to expose it to the internet. How?

ngrok HTTP 5000

ngrok!

The above command will expose HTTP://localhost:5000 to the internet using a temporary URL. Copy that URL and save it to the webhook section(Messaging) in Twilio for that specific number!

ngrok URL setup as webhook!

Now, it’s time to test the bot to see if it reply back properly. That being said, if we send “Endgame” as a text msg to the Twilio number, it should return the full movie name along with the movie descriptions. Right?

Voila!!!

It is pretty cool, right? Hopefully, this short article shows you how powerful is Twilio and it can be used for other services as mentioned at the start of this article. Go nuts with Twilio! Cheers! 🙌

--

--