Latest news about Bitcoin and all cryptocurrencies. Your daily crypto news habit.
How to use SMS with a Chat Messaging Service đŹÂ đČ
How to use SMS with a Chat Messaging Service
Communication in our day and age is fragmented. Some of the most popular mediums for communication have gone so far in the direction of catering to a very specific end user and creating a âsecret clubâ that, you could argue, connecting is beginning to become increasingly difficult. We have Facebook Messenger and WhatsApp, Appleâs proprietary iMessage and Googleâs Messages, and then there is also Slack, for like-minded communities and business use-cases, just to name a few.
At Stream, we think it is time to start unifying people again. There are efforts by platforms like Facebook to try to bring a few of the mediums, like text messaging and Facebook Messenger, into one, but the combinations are often awkward and have little traction đŹ (and, letâs be honest, who wants to give Facebook control over even more of our livesâŠ?).
Streamâs Chat Messaging Service was built to be flexible through the use of webhooks, to let YOU decide how you want to bring people together and how your data should flow. With webhooks, a developer is capable of leveraging our messaging service to build just about any communication platform that they can dream up. So, naturally, I thought to myself, âWhat can I dream upâ? đ€
After analyzing my habits, I realized that I often miss important Slack messages simply because the push notifications donât always get my attention (for example, if I have Slack open on my computer, but Iâve walked away from it, I sometimes miss important notifications). On the other hand, itâs common that I check my SMS messages frequently to ensure that Iâm not missing out on the latest and greatest group conversation. đŻââïž
Thatâs when it clicked.
đĄ I wanted to build a bridge between a chat service and SMS. And, through the use of Stream Chatâs webhooks and Twilioâs SMS capabilities, the problem no longer seemed like a challenge, but, rather, a fun puzzle.
In this tutorial, Iâll breakdown how I went about building a two-way chat powered by Twilio and Stream Chat. And, to make it a little exciting, Iâll use quotes from Kanye West (courtesy of https://kanye.rest đ) for the autoresponder bot that I decided to build into the project.
Hereâs a sneak peek into what youâll end up with at the end of the project (web interface on the left and my mobile SMS messenger on the right):
Prerequisites:
- Serverless
- Ngrok
- JavaScript experience
- Node.js (ideally the latest version)
- Yarn or npm
- MongoDB locally or an account with MongoDBÂ Atlas
If you want to skip this tutorial and play around with the service, dubbed âChattyâ, you can do so by visiting https://chatty-kathy.netlify.com on the web and sending an SMS to 702â820â5110 with the message âSTARTâ.
Table of Contents:
- Create a free Stream Chat Trial
- Create a Twilio SMSÂ Account
- Clone the Web Repo from GitHub
- Setup MongoDB
- Clone the Serverless Repo from GitHub
- Ngrok to the rescue
- Starting Our Serverless Lambda
- Configuring the Twilio SMSÂ Web
1. Create a Free Stream Chat Trial đŹ
Stream Chat is generally a paid service; however, Stream offers a 14-day free trial with no credit card required. Weâll use this free trial to build out our application.
Head over to https://getstream.io/chat and click on the âStart Trialâ button near the bottom (just above the UIÂ Kit).
Then, follow the steps to provision your account. Once itâs provisioned, head to the dashboard at https://getstream.io/dashboard and create an applicationâââany name will do, but feel free to have some fun and make it personal!
Once your application is created, click on the application name. The default view is for âFeedsâ, so navigate over to the âChatâ sectionâ by clicking on the link at the top.
Once you are within the chat section of your organization, collect the Key and Secret under the App Access Keys sectionâââyouâll want to hold onto these as youâll need them in later sections.
2. Create a Twilio SMS Account đ±
To keep this section short, Iâm going to leave the Twilio account creation up to you. This link will point you in the right direction. Once youâve provisioned your account, take note of your SID and Auth Token, both of which can be found on the Twilio dashboard.
A trial account is more than enough for this. There is no need to enter your credit card or purchase a number unless you would like to extend this tutorial.
3. Clone the Web Repo from GitHub âš
To get started with Chatty, letâs clone the web repo from GitHub. This will save us quite a few steps in terms of styling, setting up auth, views, etc. Make sure that you are in a working directory and run the following command:
Once cloned, move into the web directory and run yarn:
Now, create your .env file and drop the following contents into your environment file (some variables are filled in but weâll take care of the rest as we go):
4. Setup MongoDBÂ đč
You have two options for this step. If youâre running macOS, the easiest way to install and run MongoDB is to use the following command to install MongoDB with Homebrew:
Followed by this command to fire it up:
When running, you can connect to a database server running locally on the default port:
mongodb://localhost
If you get stuck, MongoDB provides a great set of instructions on their website.
Alternatively, you can create an account with MongoDB Atlas. MongoDB Atlas will handle all of the necessary setup and infrastructure for free. You can sign up for MongoDB Atlas at https://atlas.mongodb.com.
5. Clone the Serverless Repo from GitHub đš
Weâre going to use AWS Lambda for handling incoming webhooks from Stream and Twilio for both chat messages and SMS.
To do this, weâll run an AWS Lambda locally using Serverless. To get started, clone the repo using the following command:
Next, move into the serverless directory and run yarn to install dependencies:
Then, youâll want to address some missing environment variables within your serverless.yml file. Within the serverless directory, open the serverless.yml file and edit the environment block of yaml accordingly:
6. Ngrok to the Rescue đ”
If youâre unfamiliar with ngrok, you should take some time to look over their website at https://ngrok.com. Itâs a truly awesome service that, in a nutshell, opens up your local server (which is behind a firewall) to the public internet.
For example, weâre going to start our Serverless Lambda function locally in the next section. Ngrok will allow us to bind to a port (our particular Lambda will run on port 8000) and kick back a publicly accessible URL. Weâll use this URL to allow incoming webhooks from Stream Chat and Twilio.
If you donât have ngrok installed, you can download it here. Ngrok runs on multiple operating systems, so itâs okay if youâre not running macOS. Once installed, run the following command in your terminal to bind to port 8000:
If all was successful, you should see the following screen with a publicly accessible URL (both HTTP and HTTPS):
Now that youâve started ngrok, it will listen to any incoming connections to port 8000, regardless of whether or not the server is up and running. That said, letâs go ahead and move on so we can start our Lambda locally with Serverless offline.
7. Starting Our Serverless Lambda đ
With the repo cloned into the serverless directory and our dependencies installed, move into the serverless directory (note that you will need to do this in a new tab so that ngrok stays running and listening on port 8000) and run the command yarn start. You should see the output in your terminal that looks something like this:
Your Lambda is now up and running!
Letâs configure our webhooks in the next two sectionsâŠ
8. Configuring the Stream Chat Webhook đŁ
Head back over to https://getstream.io/dashboard and click on the âChatâ tab. Scroll down to the âChat Eventsâ section and set the webhook toggle to âActiveâ.
For the Webhook URL, be sure to drop in your ngrok HTTPS URL with /chat tacked on to the end (for example, my ngrok URL for chat is https://47e41901.ngrok.io/chat). This will ensure that the correct handler picks up your incoming chat messages.
Click the âSaveâ buttonâââtop right.
Next, weâll configure Twilio.
9. Configuring the Twilio SMS Webhook đČ
Because we didnât configure a project, youâll need to do that. Head back over to the Twilio dashboard and click on the âProgrammable SMSâ tab (second down on the left bank).
Next, click on âSMSâ and then create a new project. Mine is called âChattyâ, so I already have one configured. There should be a big red â+â button that sends you in the right direction.
Run through the configuration steps and use Chatbot/Interactive 2-Way for your use-case. Then, under âInbound Settingsâ, specify your ngrok URL with /sms tacked on the end (for example, my ngrok outbound HTTP POST request URL is https://47e41901.ngrok.io/sms).
Make sure that you check the box that says âPROCESS INBOUND MESSAGESâ to enable webhooks.
Thatâs all! Letâs continue onâŠ
10. Web Environment Variable Configuration đ
Now that we have nearly everything we need for configuration in place, letâs go ahead and update our .env file for our web environment variables.
Open the .env file and drop in your Stream, Twilio, and auth route (e.g. https://47e41901.ngrok.io/auth) credentials.
Once complete, you can go ahead and start the app with the yarn start command!
If all went well, you should be greeted by a simple login screen where you can enter your username and phone number. Enter your information and hit âStartâ and you will be shown a chat screen where you can chat away. Kathy, the bot, may even throw back some interesting quotes from Kanye West if you are lucky!
Breaking Down the Architecture đș
Now that weâve gone through all of the steps to get this up and running, youâre probably wondering how the heck all of this works and fits together. The architecture is rather simpleâââeverything flows bi-directionally making the architecture really simple to understand. Hereâs a quick breakdown:
- A user logs in with their username and phone number
- The user data is sent to Stream and the AWS Lambda, for storage, returning a user token back to the web for use
- All interactions on the web are sent to Stream chat directly, and then piped to Lambda via websocket where they are processed and routed
- If there is an @ mention, the user is notified via Twitter on their mobile device
- The user on the mobile device can then reply, sending it back through Twilio, then off to Lambda, and, finally, back through Stream Chat where it will make its way to the userâs web client
Web đŸ
The web consists of two primary filesâââthe first being Login.js (supported by several files) and the second being Chat.js, where all of the chat magic happens.
Login.js handles data collection (email and password). When the user hits the âStartâ button, a POST is sent off to the Lambda where the user is stored in the MongoDB database. A user is then created in Stream Chat, and a Stream generated token is returned along with the user data (ID, name, etc.). Once the token is received by the callback, it is stored in sessionStorage for use within our chat.
Chat.js pulls the user and token data from sessionStorage, where it then starts a new chat for the user. Iâm using our Stream Chat React Components to bring this to life, and, I must say, itâs an easy task.
The Lambda đ§ââïž
The Lambda consists of three primary functions as well as an additional helper function to store MongoDB connection stateâââall of which are stored in a single file called handler.js.
Connect establishes and stores the MongoDB connection state. This is helpful because Lambda caches for a bit of time, and itâs good practice to reuse a connection when possible.
Auth takes in a name and email as POST parameters. From there, it establishes a database connection and creates a user in Stream Chat. Once a user is created, a token is generated and both the user object as well as the token are returned back to the client.
SMS handles incoming webhooks from Twilio, processing the message and forwarding it over to the Stream Chat channel. The user can respond with âSTOPâ at any point in time to turn off the messages.
Create has a little bit more logic going on within it. This particular function accepts webhooks from Stream Chat and sends a user an SMS anytime they are @ mentioned. The whole idea behind this is to keep the user updated on direct messages, but avoid noisy chat messages from coming through.
Final Thoughts đ€
In this post, weâve learned the inner workings of building a messaging service with Stream Chat and Twilio SMS. The frontend is built with React using the Stream Chat React Components, whereas the backend is entirely built in an AWS Lambda powered by Serverless.
If youâre looking to take this project to the next level, adding a few things such as MMS support would be a great idea. You could also learn how to launch Serverless on AWS, which we did not cover in this tutorial, as we hooked up the communication between services using ngrok.
I hope you found this tutorial helpful and encourage you to drop any thoughts or questions in the comments below. If youâd like to learn more about Stream Chat, youâll enjoy our API Tour at https://getstream.io/chat/get_started/.
Happy coding! â
How to use SMS with a Chat Messaging Service was originally published in Hacker Noon on Medium, where people are continuing the conversation by highlighting and responding to this story.
Disclaimer
The views and opinions expressed in this article are solely those of the authors and do not reflect the views of Bitcoin Insider. Every investment and trading move involves risk - this is especially true for cryptocurrencies given their volatility. We strongly advise our readers to conduct their own research when making a decision.