Save User Input via Slackbot with Twilio Autopilot, Functions, and MongoDB

Lizzie Siegle - Mar 5 '20 - - Dev Community

This step-by-step tutorial will go over how to build a Slackbot using Twilio Autopilot and Twilio Functions, saving the user's answers to a MongoDB Atlas database. If you haven't seen part one of this two-part blog series yet, check it out here and make sure you have your Autopilot Slackbot and Function set up before continuing below.

Setup MongoDB

Let's receive and save the data the user gave us. On the MongoDB Cloud Atlas homepage, make a free account. Once logged in, make a new cluster.

Under Cloud Provider & Region, select a cloud provider. For this post, I decided to use Azure. Then select a region (one with a free tier may be preferable.)

For Cluster Tier, you can then select "M0 Sandbox"--your account will only be able to have one cluster at this level. Now you can scroll to the bottom and click the green "Create Cluster" button. This can take 7-10 minutes, so you have time to make a cup of tea and stretch.

Now on the Clusters page underneath Cluster0 which you just made, click "Connect".

You will need to whitelist an IP address, and because it's hard for Twilio Functions' IP address to predict, we must let your Cluster accept the whole internet: you must whitelist 0.0.0.0.

There are three ways to connect to your cluster. For this post, we will be using MongoDB Compass which provides a GUI for MongoDB so click the third option as shown below and follow those instructions. They will give you download links in the next step.

If you don't have Compass downloaded already, you'll need to download the right version for your machine. Compass provides a nice interface that lets us easily query, manipulate, and explore our data. Next copy that connection string they give you for the next part to receive and save input from Autopilot.

Edit the URL to include your username and password and copy that. When you open the MongoDB Compass Community with that modified URL copied, it will recognize you have a connection string and then fill out some of the New Connection data for you.

Click "yes" and then scroll down to click the green "Connect" button. As long as you can connect without errors, we can move on to receiving and saving input from the Slackbot.

Receive and Save Input from Autopilot With Twilio Functions

Go to the Configure Functions section of Twilio Runtime. Under Environmental Variables, click the red "+" button. Name the key something like MONGO_CONNECTION_STRING and for the value, paste in the MongoDB Connection String from the last section. This can now be referenced from any of your Twilio Functions with context.MONGO_CONNECTION_STRING.

Now under Dependencies click the red "+" button to add an npm module. In the name box, type "mongodb" and you can ignore the version box, getting the most recent stable version. Click "Save" and you're good to go!

letsgo.gif

Next, create a Twilio Function called "Slackbot." Add "/slackbot" to the path, which will be unique to you.

unique-path-to-you

Now replace the following code in your Function with this in order to save user input to variables.

exports.handler = function(context, event, callback) {let memory = JSON.parse(event.Memory);let event\_name = memory.twilio.collected\_data.event\_sponsorship.answers.event\_name.answer;let devangel\_name = memory.twilio.collected\_data.event\_sponsorship.answers.devangel\_name.answer;let user\_email = memory.twilio.collected\_data.event\_sponsorship.answers.user\_email.answer;let event\_start\_date = memory.twilio.collected\_data.event\_sponsorship.answers.event\_start\_date.answer;let anticipated\_developers\_num = memory.twilio.collected\_data.event\_sponsorship.answers.anticipated\_developers\_num.answer;let alcohol = memory.twilio.collected\_data.event\_sponsorship.answers.alcohol.answer;let event\_location = memory.twilio.collected\_data.event\_sponsorship.answers.event\_location.answer;
Enter fullscreen mode Exit fullscreen mode

Next, we're going to create our Mongo client and pass it the connection string we saved when setting up MongoDB Compass.

const MongoClient = require('mongodb').MongoClient;const uri = context.MONGO\_CONNECTION\_STRING;const client = new MongoClient(uri, { useNewUrlParser: true });
Enter fullscreen mode Exit fullscreen mode

Now it's time to connect to the client and create a database called "events". eventObj is the JSON object containing the input from the user that spoke with the Slackbot that will be saved to the events database.

 MongoClient.connect(uri, function(err, db){if (err) console.log(err);var dbo = db.db("events");var eventObj = {"event\_name ": event\_name,"devangel\_name ": devangel\_name,"user\_email ": user\_email,"event\_location ": event\_location,"event\_start\_date ": event\_start\_date,"anticipated\_developers\_num ": anticipated\_developers\_num,"alcohol ": alcohol}
Enter fullscreen mode Exit fullscreen mode

Right below that last curly bracket, we create a new collection called events_list and insert the eventObj into it as a document. Finally, we close the database.

dbo.collection("events\_list").insertOne(eventObj, function(err, res) {if (err) console.log(err);console.log("1 doc inserted");db.close();});
Enter fullscreen mode Exit fullscreen mode

Lastly, we want to tell the user speaking with the Slackbot that their input was received.

const response ={ actions: [{say: "Slackbot has received the input for " + event\_name + "!"}]};callback(null, response);});}
Enter fullscreen mode Exit fullscreen mode

This completed Function code can be seen here on GitHub too.

Update your Autopilot Assistant to Redirect to your Twilio Function

In the last post, the Autopilot Slackbot would redirect to the Hello_world task after asking all the questions, starting over. Now that we want to save the user's answers to MongoDB, we must replace the function URL at the end. Go to your Twilio Function and copy the Function URL you made above (the one that ends with "/slackbot".)

Paste that URL back in your Autopilot task JSON:

{"actions": [{"collect": {"name": "event\_sponsorship","questions": [{"question": {"say": "What is the event name?"},"name": "event\_name"},{"question": {"say": "What evangelist would you like there?"},"name": "devangel\_name","type": "Twilio.FIRST\_NAME"},{"question": {"say": "What's your email?"},"name": "user\_email","type": "Twilio.EMAIL"},{"question": {"say": "What's the event website?"},"name": "event\_website"},{"question": {"say": "What is the event start date?"},"name": "event\_start\_date","type": "Twilio.DATE"},{"question": {"say": "What is the event end date?"},"name": "event\_end\_date","type": "Twilio.DATE"},{"question": {"say": "Link to the sponsorship prospectus please!"},"name": "event\_prospectus\_link"},{"question": {"say": "What city is the event located?"},"name": "event\_location","type": "Twilio.CITY"},{"question": {"say": "What is the anticipated number of developers?"},"name": "anticipated\_devs\_num","type": "Twilio.NUMBER"},{"question": {"say": "Will there be alcohol at the event?"},"name": "alcohol","type": "Twilio.YES\_NO"}],"on\_complete": {"Redirect":"https://YOUR-FUNCTION-URL.twil.io/SLACKBOT"}}}]}
Enter fullscreen mode Exit fullscreen mode

Let's save and rebuild the model. If you speak with the Slackbot, it may look something like this:

If you visit your MongoDB Atlas Cluster, it should contain a saved document like your eventObj:

What's Next

happy.gif

Autopilot makes it so easy to build a bot once and then deploy on multiple platforms--you could make a few configurations and have this Slackbot running via SMS, Voice, Messenger, and more! Let me know in the comments or online what Slackbots you want to build next, or what your preferred database is.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player