Save User Input via Slackbot with Twilio Autopilot, Functions, and MongoDB
Tags: twilio, machinelearning, mongodb
Published: 2020-03-05 18:33:54

---
title: Save User Input via Slackbot with Twilio Autopilot, Functions, and MongoDB
published: true
tags: twilio, machine-learning, mongodb
canonical_url: 
---

This step-by-step tutorial will go over how to build a Slackbot using [Twilio Autopilot](https://twilio.com/autopilot)[ ](https://twilio.com/autopilot)and [Twilio Functions](https://www.twilio.com/functions), saving the user's answers to a [MongoDB Atlas](https://www.mongodb.com/cloud/atlas) database. If you haven't seen part one of this two-part blog series yet, [check it out here](https://dev.to/twilio/build-a-slackbot-with-twilio-autopilot-5hnd-temp-slug-9456269) 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](https://www.mongodb.com/cloud/atlas), make a free account. Once logged in, make a new cluster. 

![](https://s3.amazonaws.com/com.twilio.prod.twilio-docs/images/jqy4F9OSxtwa7uj-ZHpum629EHoZTYwWzHT8LcqVmzzNBR.width-500.png)

![](https://s3.amazonaws.com/com.twilio.prod.twilio-docs/images/xnZ-l6J8JHiZdgVVQYsQTvfQoOgCRA5GvKoxF9aEjmX4J-.width-500.png)

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.)

![](https://s3.amazonaws.com/com.twilio.prod.twilio-docs/images/yq9nXtSECRV7m2Xf_44_HvRxI-8E460UpIqHC-yDFFWLI8.width-500.png)

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.

![](https://s3.amazonaws.com/com.twilio.prod.twilio-docs/original_images/O08zyNd9-B4TBkd1ogf2EE1Ezddod0AjteMKnOnou5t3LAxxsJP2rT5GIO7PIkJyFv7Sw_Fg1ntrOZ)

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

![](https://s3.amazonaws.com/com.twilio.prod.twilio-docs/images/T98T5GW5Upe9ns1n9IbaKrWvXblx89mMUfzB9lDZnG73iD.width-500.png)

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.

![](https://s3.amazonaws.com/com.twilio.prod.twilio-docs/images/cHUG84W6mF8C-9Tz_u6codbEGrAil9_b91ZdadmXCKIZ70.width-500.png)

There are three ways to connect to your cluster. For this post, we will be using [MongoDB Compass](https://www.mongodb.com/products/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.

![](https://s3.amazonaws.com/com.twilio.prod.twilio-docs/images/5UDbltAMpyhcY8hlRj_g8aiZAB-zYJU1xAii6f1xgqEYx9.width-500.png)

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.

![](https://s3.amazonaws.com/com.twilio.prod.twilio-docs/images/7FTi4NK8bH0xfvhzdmIf61fZwrzkXZbmb35sIAE2G3DfeW.width-500.png)

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. ![](https://s3.amazonaws.com/com.twilio.prod.twilio-docs/images/AtZFGmszKap_REEpOASdVdZ7GWaB_4n8LBJlPjvL-TlE1F.width-500.png)

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](https://www.twilio.com/console/runtime/functions/configure) of [Twilio Runtime](https://www.twilio.com/console/runtime/overview). 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](https://s3.amazonaws.com/com.twilio.prod.twilio-docs/original_images/letsgo.gif)

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

![unique-path-to-you](https://s3.amazonaws.com/com.twilio.prod.twilio-docs/images/Screen_Shot_2019-05-18_at_12.46.54_AM.width-500.png)

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;
```

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 });
```

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}
```

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();});
```

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);});}
```

This completed Function code can be seen [here on GitHub](https://github.com/elizabethsiegle/twilio-functions/blob/master/mongodb-slackbot-with-autopilot.js) 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".)

![](https://s3.amazonaws.com/com.twilio.prod.twilio-docs/images/XP0epMcjMs3ieSEHIuc6CP0k6zTzQM6ImFqS_6qbFeZPif.width-500.png)

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"}}}]}
```

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

<iframe width="480" height="270" src="https://www.youtube.com/embed/0eEVZAUT8Ow?feature=oembed" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>

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

![](https://s3.amazonaws.com/com.twilio.prod.twilio-docs/images/ysOd8Nj46ZSFjH3CSGP9uD6nOT4I57Zd-sx_Wf34yY5Kqw.width-500.png)

### What's Next

![happy.gif](https://s3.amazonaws.com/com.twilio.prod.twilio-docs/original_images/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.

- Email: [lsiegle@twilio.com](mailto:lsiegle@twilio.com)
- Twitter: [@lizziepika](https://twitter.com/lizziepika)
- GitHub: [elizabethsiegle](https://github.com/elizabethsiegle)