DEV Community

Cover image for Build a WhatsApp Bot, fast โšก
Samarth Jajoo
Samarth Jajoo

Posted on • Updated on

Whatsapp Bot API Build a WhatsApp Bot, fast โšก

A few months ago, I'd started making chatbots on Telegram - 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 had an official WhatsApp API. 30 minutes later, I made a Wikipedia bot on WhatsApp ๐Ÿ‘‡

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 - it's free and you won't need a credit card ๐Ÿ’ณ

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

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

The final step - setup your WhatsApp Sandbox here - choose any number, and join your sandbox following instructions on the page.

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

Next, create a .env file - and put in your Account SID and Auth Token, on lines 1 and 2

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, and put in a webhook URL for incoming messages.

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

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

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

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 Air, 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 ๐Ÿ˜›

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

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

โšก 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 to message through too!

All code for my WikiBot is on Github โฌ‡๏ธ

GitHub logo jajoosam / wikibot

A WikiPedia bot for WhatsApp

WhatsApp WikiBot

Powered by Twilio WhatsApp API and DuckDuckGo Instant Search API ๐Ÿค–

\ ใ‚œoใ‚œ)ใƒŽ

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 ๐Ÿ“ง

Top comments (20)

Collapse
 
ben profile image
Ben Halpern

Sweet second post Samarth!

Collapse
 
jajoosam profile image
Samarth Jajoo

๐Ÿ™Œ More coming very soon!

Collapse
 
ben profile image
Ben Halpern

Heck yeah!

Collapse
 
bitsrfr profile image
Joseph

I wasn't familiar with Repl.it so it took me a minute to find .env. Just in case anyone else is wondering about that, here is Repl.it's guide.

Collapse
 
jajoosam profile image
Samarth Jajoo

Just added this in the tutorial - thanks for the suggestion :)

Collapse
 
dyanibergh profile image
Dyani Bergh

I am stuck. I need a whatsapp bot that blocks links from being posted on my group, except for links that is in an exception list. Can you help please. This is for users all over my country so I don't think they can join other platforms

Collapse
 
bitsrfr profile image
Joseph

Great tutorial! Well written, short and to the point.

Collapse
 
bauripalash profile image
Palash Bauri ๐Ÿ‘ป • Edited

Aren't you growing?๐Ÿ˜‰

BTW, amazing post! โค

Collapse
 
lkreimann profile image
Lea Reimann ๐Ÿฆ„

Sooooo cool! Thanks for writing this post :)))

Collapse
 
maurycyszmurlo profile image
Maurycy Szmurlo

Nice post! I'll try ASAP.

Collapse
 
dipeshwalte profile image
dipeshwalte

Thanks a lot Samarth!! This will be really useful in my edtech project

Collapse
 
diek profile image
diek

Wow, i will really follow this guide soon, i have always wanted a whatsapp bot to make silly shits in group chats.

Collapse
 
kn_neeraj profile image
Neeraj Kumar

HI Samarth, great post!
However when I send some query, the bot doesn't reply anything.

Collapse
 
jajoosam profile image
Samarth Jajoo

Yeah - looks like my instance is down. The guide should still work tho!

Collapse
 
kn_neeraj profile image
Neeraj Kumar

Your chatbot still isn't working for me. Is there something I am missing?

Thread Thread
 
caballodeverdad profile image
CaballodeVerdad

It didn't work for me either, did you find a solution?

Collapse
 
marwan_kandeel profile image
๏ฎผู…ุฑูˆุงู†ุŒู‚ู†ุฏูŠู„

Hi Samarth,

Can you please help me building my bot?

Collapse
 
lporras profile image
Luis Porras

Thanks amazing work!

Collapse
 
slobos profile image
slobos

Great tutorial!!
Thanks for sharing this information!

Some comments may only be visible to logged-in visitors. Sign in to view all comments.