Build a WhatsApp Bot, fast ⚡
Tags: twilio, replit, whatsapp, chatbot
Published: 2019-01-12 04:34:35

---
title: Build a WhatsApp Bot, fast ⚡
published: true
description: Build a 🤖 that sends WikiPedia summaries to WhatsApp
tags: twilio, replit, whatsapp, chatbot
cover_image: https://i.imgur.com/XQ4FhRA.png
---


A few months ago, I'd started making chatbots on [Telegram](https://t.me) - I'd seen some APIs for WhatsApp but they were unoffical and there was a chance for getting your number blocked 📱 ❌ 

A while ago, I saw that [Twilio](https://twilio.com) had an official WhatsApp API. 30 minutes later, I made a [Wikipedia bot on WhatsApp](https://wikibot.4ty2.fun) 👇

![](https://wikibot.surge.sh/Untitled-b9da3f92-94c0-4f97-8afb-787110d8a9d3.png)

This is a tutorial to help you make a something like this, your own chatbots on WhatsApp - these bots are immediately available to over 2 billion users, and there are so many things possible 🎓

I can't wait to see what you make! Now, let's get started 🏃‍♂️

## 🔑  Accounts and Keys

First, Sign up for [Twilio](https://www.twilio.com/try-twilio) - it's free and you won't need a credit card 💳

![](https://wikibot.surge.sh/screely-1535885763017-fc654067-9557-4bf7-98b5-4337911ff4ba.png)

Once you're done verifying your phone number, select Procuts > Programmable SMS and then continue to name your project. 

![](https://wikibot.surge.sh/screely-1535885937977-c5a924ec-8cc3-4430-9345-9b5e1dc74ef3.png)

Feel free to skip steps for adding teammates - you won't need that for now.

You must now take note of some authentication keys you'll need for building the WhatsApp bot 👇

![](https://wikibot.surge.sh/screely-1535886250966-f68b6cfb-c104-4adf-80e7-4e3f9bd15b5b.png)

The final step - setup your WhatsApp Sandbox [here](https://www.twilio.com/console/sms/whatsapp/sandbox) - choose any number, and join your sandbox following instructions on the page.

![](https://wikibot.surge.sh/screely-1535886798623-1dac1ba9-c362-4e49-87ab-7bbb6138e8c7.png)

Aaaaaand you're done with credential setup! Don't worry, that was the toughest part of this tutorial 😛

## 🚀  Getting Started

So that we don't spend too much time on setup, I've created an environment (with [repl.it](https://repl.it)!) you can use within your browser. Head over [here](https://repl.it/@jajoosam/wikibot-start), and wait for a couple of seconds to fork it.

Next, [create a `.env` file](https://repl.it/site/docs/repls/secret-keys) -  and put in your Account SID and Auth Token, on lines `1` and `2`

```bash
SID=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX # Account SID
KEY=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX # Auth Token
```

You can see, this environment already has dependencies installed, and an `express` server set up. We still need to give Twilio a URL to send incoming messages to, though 🔗

Let's go back to the [WhatsApp Sandbox](https://www.twilio.com/console/sms/whatsapp/sandbox), and put in a webhook URL for incoming messages.

![](https://wikibot.surge.sh/Untitled-3ed5263b-c6d8-492b-ba08-b4644ab502cf.png)

This URL must be what you see on the preview panel of your [repl.it](http://repl.it) project + `/incoming`

![](https://wikibot.surge.sh/Untitled-1779b21f-9100-4942-b732-320dc48c5f76.png)

We can now finally read messages that are sent to the bot. Navigate to `index.js` and then add a simple `console.log()` in your webhook handler 👇

```javascript
app.post('/incoming', (req, res) => {
  console.log(req.body)
});
```

When you send a message to your bot, you should be able to see something like this in your repl console 👨‍💻

![](https://wikibot.surge.sh/Untitled-163eb09e-e6ab-4910-badb-d8aa0aa789f7.png)

Building an echo bot would look something like this, using `twiml` to write a message 👇

```javascript
app.post('/incoming', (req, res) => {
	const twiml = new MessagingResponse();
	twiml.message(req.body.Body);
	res.writeHead(200, {'Content-Type': 'text/xml'});
  res.end(twiml.toString());
});
```

But, since we're actually trying to build a useful bot - let's use informative APIs!

## 🌐  Fetching Information

DuckDuckGo has an amazing, free instant answer API. It takes in a query and returns back a summary from WikiPedia and more.

A few examples 👉  [WikiPedia](https://api.duckduckgo.com/?skip_disambig=1&format=json&pretty=1&q=WikiPedia), [Macbook Air](https://api.duckduckgo.com/?skip_disambig=1&format=json&pretty=1&q=MacBook%20Air), [Twilio](https://api.duckduckgo.com/?skip_disambig=1&format=json&pretty=1&q=Twilio)

I spent some time creating a decent parser which usually returns information from this API. Try pasting this code in your [repl.it](http://repl.it) project, and your [console](https://dsh.re/f7477c) should have stuff about Trump in it 😛

```javascript
var base = 'https://api.duckduckgo.com/?skip_disambig=1&format=json&pretty=1&q=';
var query = 'Donald Trump';

request(base + query, function (error, response, body) {
    body = JSON.parse(body)    
    if(body["Abstract"] == ""){
	    body["Abstract"]= body["RelatedTopics"][0]["Text"]
	  }   
    var msg = body["Heading"]+"\n\n"+body["Abstract"];
  console.log(msg)
  });
```

Pretty straight forward, right? 😄

## 🛠️  Putting it all together

To make our actual bot, all we need to do is get the query from our request - which we can get as `req.body.Body` - and use `twmil` to send across the data we collected in `msg`

```javascript
app.post('/incoming', (req, res) => {
	const twiml = new MessagingResponse();
	var base = 'https://api.duckduckgo.com/?skip_disambig=1&format=json&pretty=1&q=';
	var query = req.body.Body;
	
	request(base + query, function (error, response, body) {
	    body = JSON.parse(body)  
  
	    if(body["Abstract"] == ""){
		    body["Abstract"]= body["RelatedTopics"][0]["Text"]
		  }   

	    var msg = twiml.message(body["Heading"]+"\n\n"+body["Abstract"]);
			res.writeHead(200, {'Content-Type': 'text/xml'});
		  res.end(twiml.toString());
	  });

});
```

You now have a fully functionaing WhatsApp bot! Send anything you want to know about your bot 🤖  and you should see it respond super fast 💬 ⚡

Adding welcome messages and a little formatting is quite simple, look at the final [repl](https://repl.it/@jajoosam/wikibot) to see how I did it 👨‍💻

{% replit @jajoosam/wikibot %}


## 🔗  Sharing the bot

For others to use this bot, they'll need to join your sandbox first - and send a message just like you did earlier 👉  `join <two-words>` 

You can create links with this text too - For example this link lets you join my bot 👇

```
https://wa.me/14155238886?text=join ultramarine-tapir
```

`14155238886` is my bot's number, while `ultramarine-tapir` is the sandbox phrase.

## ⚡ What's next?

Now that you know how to build a bot on WhatsApp, try sending notifications to yourself, and building more useful tools! Twilio has loads of [other mediums](https://www.twilio.com/channels) to message through too!

All code for my WikiBot is on [Github](https://github.com/jajoosam/wikibot) ⬇️
{% github jajoosam/wikibot %}

I'm a 15 year old maker 👨‍💻  For more cool things to make and to stay updated with my progress, sign up for [my newsletter 📧](https://buttondown.email/jajoosam)