Write a simple facebook messenger bot with Go + ngrok

Messenger bots of facebook are quite long. There were many users for my facebook page. This article will guide you to write a bot that automatically responds to the pattern available with Go – for the server and ngrok – to publish localhost out.

This type:

Screen Shot 2016-07-11 at 5.05.46 PM

Things you need to have:

  • A facebook page
  • Enough already

Facebook stuffs

First go to https://developers.facebook.com and select your app.

Screen Shot 2016-07-11 at 5.06.22 PM

On the left tab of you Add Product . Select Webhooks , and New Subscription and select Page in dropdown. A popup like this will appear:

Screen Shot 2016-07-11 at 5.06.44 PM

Here I only select subscription field as messages .

To be able to save this subscription again, you need a Callback URL and a Verify token

Callback URL is the place where the messenger will send data when receiving the message on the facebook page.

Here I will use Go as server, run on localhost. Then use ngrok to publish a https URL (because Callback URL facebook only accepts https)

Verify token, you enter the token that I want to verify again 1 (use in Go server to double check)

Ta da! Leave this popup, switch to writing server.

Go server

Create a main.go file .

Write the function main for it, which serves as the serve at port 8085 a webhook.

Write webhookHandler function

Why are there two GET and POST functions here? GET will be called when you press the Verify and Save button on the popup above. And POST will be called when someone texts on the facebook page. With GET, I only check if I send the correct verificationToken , and log out.

It is important to handle the POST function:

The above function has two functions:

  • getReplyMessage : Here I only see if there is hello, I will return the corresponding greeting message. You can use other advanced techniques.
  • sendTextMessage : This function will send a POST request to facebook endpoint, then facebook will send a message to the recipient (who has just chat on the facebook page).

Running servers go up by shaking main.go. We have a server running on port 8085

Ngrok

You download ngrok here https://ngrok.com/

Run:

Will be like this:

Screen Shot 2016-07-11 at 5.08.10 PM

localhost: 8085 has been ngrok converted to https and published to the outside.

Config

Everything is almost done. You just paste the callback URL that has been forwarded by ngrok into the popup of the Facebook earlier, and the verification token is done.

Screen Shot 2016-07-11 at 5.08.37 PM

So you can pm the facebook page chat try and wait for the response.

Conclusion

Above is a simple sample. Facebook messenger bots have a lot of potential in the area of ​​sales or autoresponder. Those who are not playing can play against it.

ITZone via kipalog

Share the news now