WikiBot

Build a WhatsApp bot with Twilio APIs, in 30 minutes ๐Ÿ•

jajoosam@jajoosam

A few months ago, I'd started making chatbots on Telegramโ€”I'd seen APIs for WhatsApp but they were unofficial and there was a chance for getting your number blocked ๐Ÿ“ฑ โŒ

A week ago, I saw that Twilio had an official WhatsApp API. 30 minutes later, I made a Wikipedia bot on WhatsApp ๐Ÿ‘‡

Text message describing the term Wikipedia

This is a workshop to help you make a something like this, and make your own chatbots on WhatsApp, in just 30 minutes ๐ŸŽ“

๐Ÿ”‘ Accounts and Keys

First, Sign up for Twilioโ€”it's free and you won't need a credit card ๐Ÿ’ณ

Input fields for signing up for an account

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

Project creation interface showing 4 boxes

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 ๐Ÿ‘‡

Project dashbaord with authorization tokens highlighted

The final stepโ€”set up your WhatsApp Sandboxโ€”choose any number, and join your sandbox following instructions on the page.

Settings page with information on setting up

โ€ฆand 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!) you can use within your browser. Head over here, and wait for a couple of seconds to fork it.

Next, open up server.js and put in your Account SID and Auth Token, on lines 7 and 8

const accountSid = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' // Account SID
const authToken = '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, and put in a webhook URL for incoming messages.

Image of a webhook URL

This URL must be what you see on the preview panel of your repl.it project + /incoming

Code in a code editor

We can now finally read messages that are sent to the bot. Add a simple console.log() in your webhook handler ๐Ÿ‘‡

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.it console ๐Ÿ‘จโ€๐Ÿ’ป

Console output of a program running

Building an Echo bot would look something like this, using twiml to write a message ๐Ÿ‘‡

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, MacBook Pro, Twilio

I spent some time creating a decent parser which usually returns information from this API. Try pasting this code in your repl.it project, and your console should have stuff about Trump in it ๐Ÿ˜›

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

request(base + query, (error, response, body) => {
  body = JSON.parse(body)
  if (body['Abstract'] == '') {
    body['Abstract'] = body['RelatedTopics'][0]['Text']
  }
  const 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

app.post('/incoming', (req, res) => {
  const twiml = new MessagingResponse()
  const base =
    'https://api.duckduckgo.com/?skip_disambig=1&format=json&pretty=1&q='
  const query = req.body.Body

  request(base + query, (error, response, body) => {
    body = JSON.parse(body)

    if (body['Abstract'] == '') {
      body['Abstract'] = body['RelatedTopics'][0]['Text']
    }

    const 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-functioning 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 to see how I did it ๐Ÿ‘จโ€๐Ÿ’ป

๐Ÿ”— 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.

Now, go ahead and share your bot on the #ship channel on the Hack Club Slack!

โšก What's next?

Now that you know how to build a bot on WhatsApp, try sending notifications to yourself, and use different JSON APIs to create bots ๐Ÿค–

Here are some you can play with ๐Ÿ‘‡

All code for my WikiBot is on GitHub, feel free to refer to it โœจ

Edit this page on GitHub