Create a Free WhatsApp Binance Bot in a Few Minutes with Serverless in Lolo
Tags: javascript, programming, tutorial, blockchain
Published: 2023-01-31 12:19:39

## For anyone keen to set up their own WhatsApp bots and stream real-time cryptocurrency data from Binance in a few minutes with minimal code with a Serverless app.

For this article we’ll help you go through the entire process of setting up a Facebook app that allows a bot user to receive and send messages. Then we’re setting up a Lolo application (i.e. a Serverless event-driven app) to receive and send messages to WhatsApp via a few triggers (library functions).

We’re also learning how to quickly set up a Binance data stream to get continuous updates on btc. You can choose which cryptocurrency you’d like. You’ll also be able to chose any trade steam. This is just a demo for something simple. We thank Jesper on our team for setting most of this up so it will go smoothly.

The process will look like this.

1. Get Credentials from Facebook
2. Create a Lolo Application
3. Configure Webhooks
4. Process Messages
5. Set up a Binance stream to receive price updates for BTC
6. Send back a reply to WhatsApp

Facebook or Meta does make us jump through a few hoops for credentials here but once you’ve set this up once it will be easier the next time. And isn’t learning how to create WhatsApp bots pretty essential?

### Get Credentials from Meta for WhatsApp
Log into developer.facebook and create a new app. If you don’t have a developer account do open one.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lfz6pr1iw7pqcxw0c81g.png)

Go to settings → basic to get your app secret.

We’re done here for now but do keep the tab open because we’re coming back to set up a webhook in a bit.

### Create a Lolo Application to set up a Webhook
Create a new application in [Lolo Code.](https://console.lolo.co/) You can create a free account on the same page if Lolo is new to you.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/38gwcn3vn8n66v89e3u6.png)

Add the Lolo/WhatsApp Trigger to your application.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qe2k0h1mny9h6lop6m1i.png)

Save and Run your application.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dzz3steytgazltssvo08.png)

Go to docs to find your callback url as we’ll need it in a bit.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/32c80jnbtzn9amepx7jf.png)

### Configure Webhooks in Facebook to Create a WhatsApp Bot that can Receive Messages
Go back to Facebook’s developer dashboard and find Products → webhooks.

Choose WhatsApp Business Account and then click ”subscribe to this object.” Here you’ll paste in your callback url that we got from Lolo as well as the verification string we put into our WhatsApp trigger in Lolo, i.e. itisme.

Once you’re done you should see choices to subscribe to, what you’re looking for is Messages. Click subscribe.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i4927elphfq43goqqu8i.png)

Now navigate to Get Started under WhatsApp just under Webhooks, here you’ll need to add your phone number of your WhatsApp account. You’ll get a verification code to your whatsApp account to verify it.

You’ll also want to save the phone number that Facebook gives you as well, because it’ll be your bot’s number.

### Process Messages Coming From WhatsApp
If you try to message the number of our new bot we’ll get a payload from Whatsapp with something like the JSON below. Right now we’re not logging anything in the Lolo app but just to demonstrate what the payload will look like.

```json
{
  "from":"",
  "id":"",
  "timestamp":"1671457845",
  "text": { 
    "body":"incoming text here" 
  },
  "type":"text"
}
```


So to access the text of the message in a connecting node via the event (ev) object that is accessible in the event handler we would use ev.text.body. To do this, create a new raw function in your Lolo app.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bryx4r6166a17hb19p5x.png)

Double click it to change its code. We get a bunch of default code in the handler that we need to replace. Right now it would just be logging the event object to the Logs. So, remove the default text and copy the text below to paste it into its handler.

```javascript
exports.handler = async(ev, ctx) => {
  const { route, log } = ctx;

  // access text of whatsapp payload
  log.info(ev.text.body)

  // route the messages to the right port
  if (ev.text && ev.text.body === 'btc') {
    route(ev, 'btc');
    return;
  }
};
```
Here we are setting the naming to btc (as we will be checking Bitcoin pricing) but you can change this later.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x5dhh6keykmgh1l30s6c.gif)

As you can see in the code above, we are routing the message to btc here. To route this to a port called btc, we need to create it. So, go to the Settings and then look for the tab called Ports.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8bmkkjrfzucz2kjed9w1.gif)

We can also rename the function to Handle Messages and connect the two nodes.

What we’ve done so far is to set up a webhook that we’ve given Facebook so it will be triggered when a WhatsApp message comes in via the Bot’s number. When a message is sent to this number, the Lolo app will recieve an event with a payload of data. We then process the message by accessing ev.text.body in another node to see if the message is equal to `btc` and if so we’ll route the message further via the outport btc.

Now we’ll start streaming Binance data.

### Set up a Binance Stream to Receive Price Updates for BTC
Go look for the Lolo/Binance Trigger in your menu palette, it should be available there.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uum6cu57urzryyyrhht8.png)

Click it to add it to your application and then double click it to configure it. It may take 20 seconds for the params to show so do wait for them.

Configuring the trigger is real easy. Just select the kind of data stream you’re interested in. Depending on the stream some additional data might be required, but all options are just simple drop down menus.

In this case we’re interested in the ticker for the price of Bitcoin in USD.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/32ljgafwbn6klzjisr6n.png)

More information about what streams are available and what they contain can be found in the [Binance docs.](https://docs.binance.us/?shell#market-data-streams)

Now you have created a data stream with BTC pricing, this will produce an event every second. You can log the event in another function to see the events being produced but we’ll skip that here.

You can probably think of other things to do with this I imagine. Maybe setting up a an if statement that looks for abnormalities and then pushes a message to WhatsApp when the price falls below or above your given thresholds. This would be easier than this article.

In any case, we’re doing something different here.

### Get Current BTC Price When the WhatsApp Message Comes Through
Right, so when we ask for btc in WhatsApp we need to somehow get the current price that has been streamed by the Binance trigger. So, we need a way to store the latest price so that we can retrieve it when the btc command is received.

To do this we add another raw function in the bottom right corner. Remove the default code in its handler and insert the code below.

```javascript
let latest_price = undefined;

exports.handler = async(ev, ctx) => {
  if (ctx.input === 'update') {
    latest_price = ev.c;
  } else if (ctx.input === 'get') {
    ctx.route({ev, latest_price});
  }
};

```

The above lines of code stores the price in the latest_price variable if the incoming port is update (i.e. comes from the streaming Binance data trigger), and if the port coming in is get (i.e. comes from the WhatsApp event), it routes the latest_price that the variable has stored to the out port.

For this function we then need two input ports (update & get) and one output port. To configure ports for a function navigate to Settings and then to the Ports tab. Look below on what this should look like.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/igxvmh2enj44l0kko9gf.png)

You can rename the function to Store as well.

If this is confusing, just keep going. It’ll be less so once you’re done.

We also need to connect the right ports. Remember when an event is hit data flows from one node to another via the ports. So make sure your ports are connected like the picture below.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ic6mwon40hb6xhlcbb5m.png)

The get port should be connected to Handle Messages (coming from WhatsApp) and the update port should be connected to the Binance Stream Trigger.

Craft a Reply to Send to WhatsApp
Now we need to send back a reply to the WhatsApp message but first we need to just structure the event object correctly to be proccessed by the library function.

You can probably do this in the function above but let’s do it separately.

Create a new additional function in Lolo, remove the default code and paste in the code below into its handler.

```javascript
exports.handler = async({latest_price, ev: {from}}, ctx) => {
  ctx.route({to: from, text: `The latest price of BTC is \$${latest_price}.`});
};
```

This code is setting up the event object so it can be processed by the WhatsApp Send function in a bit. It’s another library function like the Binance Trigger and has been set up by Lolo so it’ll be easy to use.

Rename the function to Reply. You can connect it to the Store function’s output port as well.

The last thing we have to do now is send a message back to WhatsApp.

### Send Back BTC Pricing to WhatsApp
Search for another function called Lolo/WhatsApp Send in your Lolo Application.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3dlf4d0louair15vsjc1.png)

Once you’ve found it, you can add it to your application. Double click it to configure it.

Here we need to add a few things. And here is also where you need to spend a bit more time as Meta is difficult about sending messages to WhatsApp so we’ll need a few more credentials.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mfxq6awjpent1k78tbbc.png)

Go back to your Facebook Dashboard and navigate to WhatsApp again and then Getting Started. Here you can find your Phone Number ID. Remember it is the phone number ID we’re looking for and not phone number.

You can paste that ID into the second input.

For getting a META access token we’ll have to go through a few more hoops. The reason is that META would like you to create a so called system user with correct privileges. But you only have to do this once, after this you can use this bot user for other things.

To create a system user, go to business.facebook.com. You should land on a page that looks like this. For you this will be a personal account, for us it the our Lolo Business account. We never really use Facebook but we do have an account there hehe.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ueo9dc009e0uhz8cije9.png)

Press the Settings button and then find Business Settings to press that too.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vlxicc7x5dn9yb8ne3ic.png)

This should bring you to a page like this where you can add system users.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h2zxfrvcqhporri2d3pg.png)

You can click Add and then name the user whatever you’d like. Choose Employee as well.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/aa7q0j7x1qw39z4dd5f1.png)

When it has been generated for you, click Add Assets. Then go to Apps, choose your App where you’ve set up WhatsApp and then tick Access to Develop app.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/usvv1lavyr21b8bj8zp5.png)

Hit save. Now the our created system user need to be given access to the WhatsApp account. To do that, in business settings, navigate to Accounts → WhatsApp-Account.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3kcuuv679abfz20vfu0h.png)

Click the add people button. A dialog pops up. Select the system user, and toggle partial access.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5w3u1z3iday98ltv1ufg.png)

Hit save.

We now need to generate an access token for this system user. Go back to the page system users settings page and click Generate Token.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wbssh63cyvvrggppezrn.png)

A dialog will pop up asking you to choose an app. Once you’ve choosen your app you will have to set Permissions. We are looking for whatsapp_business_messaging.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j5vf3jw4u1rxez4glr30.png)

Scroll down the bottom of the dialog and hit the button that says generate. You’ll see a new dialog with the generated token. We finally got it!

Go back to your Lolo app and paste in the token in the Lolo/WhatsApp Send node.

### Test it Out
Use the phone number we got from the Facebook App and then send it btc it should send you back the current Bitcoin price.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lwzui7sn2bt97mlp3dna.gif)

It goes without saying that you can create more complex stuff than this. It is just a demo of the WhatsApp and Binance Library Functions we got available.

❤ Lolo