Build a Facebook Messenger bot with Go and Messenger API
In this first tutorial of the “ChatOps” series , I will show you quickly how to create a Facebook Messenger Bot in Golang. All the code used in this demo can be found on my Github.
1 – Messenger bot
We will start by creating a dummy web server with one endpoint to print a hello world message ✌. I’ll use “
We first need to install “” library:
Shell1 | go getgithub.com/gorilla/mux |
Then, create a file called
123456789101112131415161718192021 | packagemainimport("fmt""log""net/http""github.com/gorilla/mux")funcHomeEndpoint(whttp.ResponseWriter,r *http.Request){fmt.Fprintln(w,"Hello from mlabouardy :)")}funcmain(){r:=mux.NewRouter()r.HandleFunc("/",HomeEndpoint)iferr:=http.ListenAndServe(":8080",r);err!=nil{log.Fatal(err)}} |
So basically, we have a main function which create a new route “/”, and associate to this path a HomeEndpoint function that use ResponseWrite reference to print a message. Then it start a HTTP server on port 8080.
To verify that things are working, start your local server with:
Shell1 | go run app.go |
Then in your browser, visit and you should see:
Now that you’ve got your first endpoint working, we will need to expose 2 endpoints to make it work with Facebook platform:
1.1 – Verification Endpoint: (GET /webhook)
Go123456789101112 | funcVerificationEndpoint(whttp.ResponseWriter,r *http.Request){challenge:=r.URL.Query().Get("hub.challenge")token:=r.URL.Query().Get("hub.verify_token")iftoken==os.Getenv("VERIFY_TOKEN"){w.WriteHeader(200)w.Write([]byte(challenge))}else{w.WriteHeader(404)w.Write([]byte("Error, wrong validation token"))}} |
It simply looks for the Verify Token and responds with the challenge sent in the verification request.
1.2 – Messages Handler Endpoint: (POST /webhook)
Go12345678910111213141516 | funcMessagesEndpoint(whttp.ResponseWriter,r *http.Request){varcallback Callbackjson.NewDecoder(r.Body).Decode(&callback)ifcallback.Object=="page"{for_,entry:=rangecallback.Entry{for_,event:=rangeentry.Messaging{ProcessMessage(event)}}w.WriteHeader(200)w.Write([]byte("Got your message"))}else{w.WriteHeader(404)w.Write([]byte("Message not supported"))}} |
It serialize the request body into Callback object , then it parse it and fetch the message object and pass it as an argument to ProcessMessage function that will use Facebook Graph API to send the response to the user (in this case we will send an image):
Go123456789101112131415161718192021222324252627282930 | funcProcessMessage(event Messaging){client:=&http.Client{}response:=Response{Recipient:User{ID:event.Sender.ID,},Message:Message{Attachment:&Attachment{Type:"image",Payload:Payload{URL:IMAGE,},},},}body:=new(bytes.Buffer)json.NewEncoder(body).Encode(&response)url:=fmt.Sprintf(FACEBOOK_API,os.Getenv("PAGE_ACCESS_TOKEN"))req,err:=http.NewRequest("POST",url,body)req.Header.Add("Content-Type","application/json")iferr!=nil{log.Fatal(err)}resp,err:=client.Do(req)iferr!=nil{log.Fatal(err)}deferresp.Body.Close()} |
Our local server url (http://localhost:8080) is not available to all the other people in the internet and doesn’t support HTTPS which is necessary for Facebook Messenger bot. Therefore, we need to expose it to the public.
2 – Deployment
Note: You could also use a tool like ngrok. It basically creates a secure tunnel on your local machine along with a public URL you can use for browsing your local server. Keep in mind, to use your bot in production, you need to use a real IaaS like AWS, Heroku, Clever Cloud …etc
In this tutorial I will choose CleverCloud as IaaS provider, it deploys your Go application for free and offer you extra add ons like monitoring, logs, scaling, continuous delivery …
In order to deploy to CleverCloud you’ll need a CleverCloud user account. . After signing up:
We click on “Add an application”, then you can either upload your app code from local repository or from Github:
Next, We choose GO as our server side language. Then, we click on “Next”
We left all fields as default, and we click on “Create”
Our server does not use any external resources (MySQL, Redis …) so we will simply skip this part by clicking on “I don’t need any add-on”
Congratulations ! You have successfully deployed your server.
Note: The app URL is :
ID is the string on the bottom right of the dashboard,
3 – Facebook Setup
3.1 – Create Facebook Page
If you don’t already have one, you need to that we will use to connect our bot to.
Just give it a name, and that’s it now you have created a Facebook page for you Bot
3.2 – Create Facebook App
Once the page was created, we will which will be connected your webhook server and your public page: which works as middleware that connects your Webhook (APP URL) and your public page.
You need to give your app a name then click on “Skip and Create App ID”
After creating an app, we need to add Messenger as a platform. So we click on “Add Product” then select Messenger as a product
Now you’re in the Messenger settings. There are few things in here you’ll need to fill out in order to get your chatbot wired up to the server endpoint we set up earlier.
3.2.1 – Generate a Page Access Token
Using the page we created earlier, you’ll get a random “Page Access Token”
You need to copy the token to your clipboard. We’ll need it as an environment variable (PAGE_ACCESS_TOKEN) for our server.
3.2.2 – Setup subscription
Next, we click on “Setup webhook” button on “Webhooks” section, a new popup will show up:
- Callback URL : Clever Cloud we set up earlier
- Verify Token: A secret token that will be sent to your bot, in order to verify the request is coming from Facebook, Make sure to remember the value because we will need it as a second environment variable (VERIFY_TOKEN) for the server
- Subscription Fields: represents which events you want Facebook to notify your webhook about, in this case, we will choose “messages”
After you’ve configure your subscription, you’ll need to subscribe to the specific page, you want to receive message notification for
3.2.3 – Set environment variables
Once you’ve gotten your PAGE_ACCESS_TOKEN and VERIFY_TOKEN, make sure you add those two as environment variables for the server on clever cloud dashboard
Then restart the application and you should be good to go !
4 – Test the Bot
Go to your Facebook Page and send a message to it. You should see a gif back to you
5 – Customize your Bot’s behavior
In this quick tutorial I showed you how to build a simple & dumb bot for facebook messenger, to make it smarter and have more interactions with the user. We need to use a NLP backend like api.ai (Google), wit.ai (Facebook) or motion.ai. And that will be the subject of my upcoming tutorial ❤
Related
Comments
comments
相關推薦
Build a Facebook Messenger bot with Go and Messenger API
In this first tutorial of the “ChatOps” series , I will show you quickly how to create a Facebook Messenger Bot in Golang. All the code used in this de
Building a Slack Bot with Go and Wit.ai @ Alex Pliutau's Blog
Building a Slack Bot with Go and Wit.ai We will build a simple Slack Bot with NLU functionality to get some useful information from Wolfr
Building a banking voice bot with Dialogflow and KOOKOO.
Building a banking voice bot with Dialogflow and KOOKOO.Dialogflow allows you to “Build natural and rich conversational experiences”. KOOKOO provides you a
Build a Decentralized Chat App with Knockout and IPFS
Build a Decentralized Chat App with Knockout and IPFSHow to build a fully decentralized chat app in under an hour with <100 lines of codeThe final produ
Managing a Spotify Library with Go and AWS Lambda
Managing a Spotify Library with Go and AWS LambdaSpotify exposes a robust API that can be used to manage your (or someone elses) music library and do all s
Writing a Frontend Web Framework with WebAssembly And Go
JavaScript Frontend frameworks have undoubtedly helped to push the boundaries of what was previously possible in the context of a browser. Ever mor
A temperature controlled fan, with XinaBox and Zerynth Studio
We came across a wonderful Zerynth-powered DIY fan tutorial on hackster.io and we wanted to share it with you. It features most of the xChips from
How I built an HR Slack Bot with Node and Botkit
Why create a Slack Bot ?I am an HR professional. More specifically I am a Human Resources Information System (HRIS) Consultant. I work with Application Tra
SDN實戰: Build a mini-lab environment and practice SDN-IP/ONOS with GNS3, Mininet and VMware
sdn-ip onos mininet gns3 vmwareSDN IN ACTION: Build a mini-lab environment and practice SDN-IP/ONOS with GNS3, Mininet and VMware 薛國鋒 [email protect
Build a task app with Hapi, MongoDB and Vue.js
The idea for this tutorial is we’re going to build a task app with Node.js, MongoDB and Vue.js. Users will be able to read, create and delete tasks from th
Tutorial: Build a .NET Bot with AWS
The .NET core chatbot application code allows you to order flowers using a Chatbot powered by Amazon Lex, AWS Lambda, and Amazon Cognito Identi
使用ConstraintLayout構建響應式UI(Build a Responsive UI with ConstraintLayout)
垂直 邊緣 ddn style 元素 package ext tle font 原文:https://weiyf.cn/2017/03/10/Build%20a%20Responsive%20UI%20with%20ConstraintLayout/ 原文:http://w
3% of users browse with IE9 and 14% of users have a disability. Why do we only cater for the former?
我的網站 作品 form 我不 post ability img gpo 想要 我想要用一個否定聲明來開始我的文章:對於怎樣創造一個易於用戶體驗的站點,我也不是了解非常多。 讓作為一個資深開發人員的我操心的是,我在並沒有獲得太多關於這個主題(指怎樣創造一個
2014 ACM-ICPC - A:Built with Qinghuai and Ari Factor
http://codeforces.com/gym/100548/attachments Time limit 1000 ms Memory limit 262144 kB Description DISCLAIMER: All names, incidents, char
How to detect and extract forest areas in a aerial image map with the knowledge of DIP
Signal processing is a common subject in electrical engineering, communication engineering and mathematics that deals with analysis and processing
A feasibility study on SSVEP-based interaction with motivating and immersive virtual and augmented r
A feasibility study on SSVEP-based interaction with motivating and immersive virtual and augmented reality 基於SSVEP的互動與刺激和沉浸式虛擬和增強現實的可行性研究
[Algorithms] Build a Binary Tree in JavaScript and Several Traversal Algorithms
A binary tree is a tree where each node may only have up to two children. These children are stored on the leftand right properties of each
【文藝學生】Learning with exploration, and go ahead with learning. Let's progress together! :)
文藝學生 Learning with exploration, and go ahead with learning. Let's progress together! :)
android Failed to allocate a 16 byte allocation with 232 free bytes and 232B until OOM; failed due to fragmentation (required co
測試上傳超大影片檔案,結果Android APP crash 掉,錯誤訊息是: Failed to allocate a 16 byte allocation with 232 free bytes and 232B until OOM; failed due to fragmentation (requi
Build a virtual assistant for iOS with Watson
Summary Create an application that understands natural language and responds to customers in human-like conversation – in multiple la