DEV Community

Cover image for Create a Free WhatsApp Binance Bot in a Few Minutes with Serverless in Lolo
Lolo Code
Lolo Code

Posted on

Create a Free WhatsApp Binance Bot in a Few Minutes with Serverless in Lolo

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

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. You can create a free account on the same page if Lolo is new to you.

Image description

Add the Lolo/WhatsApp Trigger to your application.

Image description

Save and Run your application.

Image description

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

Image description

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

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.

{
  "from":"",
  "id":"",
  "timestamp":"1671457845",
  "text": { 
    "body":"incoming text here" 
  },
  "type":"text"
}
Enter fullscreen mode Exit fullscreen mode

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

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.

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;
  }
};
Enter fullscreen mode Exit fullscreen mode

Here we are setting the naming to btc (as we will be checking Bitcoin pricing) but you can change this later.

Image description

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

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

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

More information about what streams are available and what they contain can be found in the Binance docs.

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.

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

Enter fullscreen mode Exit fullscreen mode

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

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

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.

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

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

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

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

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

Image description

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

Image description

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

Image description

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

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

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

Image description

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

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

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

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

Top comments (0)