Use facebook messenger bot api on heroku

Recently, Facebook open it’s messenger API, allow developer and business to create bot on messenger.
It has pretty good tutorial and example

I will go through how to create a sample echo bot and deploy to heroku:

1. Register App and facebook page

Follow the process on quickstart guide, create facebook app and connect to facebook page.

2. Create a example app

For a messenger bot, first we need to implement 2 webhook for Facebook API to call us, first is GET request to authenticate messages from facebook API:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import express from 'express'
import bodyParser from 'body-parser'
import request from 'request'

const config = {
VERIFY_TOKEN: process.env.VERIFY_TOKEN || 'token',
PAGE_TOKEN: process.env.PAGE_TOKEN || 'token',
}

const app = express()
const port = (process.env.PORT || 5678)

app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: true}))

app.get('/webhook', (req, res) => {
// checking the request is comming from facebook, receiving the VERIFY_TOKEN we set on facebook
if (req.query['hub.verify_token'] === config.VERIFY_TOKEN) {
// return the challenge token.
res.send(req.query['hub.challenge'])
} else {
res.send('Error, wrong validation token')
}
})

Second is receive actual message, all message have the same struture:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
{
"object":"page",
"entry":[ // array for event data
{
"id":"PAGE_ID",
"time":1458692752478,
"messaging":[ // array for messaging data
{
"sender":{
"id":"user_id"
},
"recipient":{
"id":"recipient_id"
},

...
}
]
}
]
}

app.post('/webhook', (req, res) => {
console.log(req.body)

// checking events
req.body.entry.forEach((entry) => {
// checking messages
entry.messaging.forEach((event) => {
// checking message type
if (event.message) {
// echo data back to server
sendTextMessage({
id: event.sender.id,
text: event.message.text,
})
} else {
console.log('unknown event!!!', event)
}
})
})

res.sendStatus(200)
})

// sending text message back
function sendTextMessage({id, text}) {
request({
url: 'https://graph.facebook.com/v2.6/me/messages',
qs: {
access_token: config.PAGE_TOKEN,
},
method: 'POST',
json: {
recipient: {
id,
},
message: {
text,
}
}
}, (error, response, body) => {
console.log('Error: ', error || response.body.error)
})
}

//start the app
app.listen(port, () => console.log(`listening on port ${port}`))

3. Deploy to heroku with SSL

After the app is done, we can put the code into heroku, you can reference the gist for setting on package.json, ‘.babel.rc’ and foreman

1
2
3
4
heroku apps:creates [bot name]
heroku git:remote
heroku config:set PAGE_TOKEN=[your FB token] VERIFY_TOKEN=[token you set on FB]
git push heroku head

FB only accept webhook with https, which support by default on heroku.

4. Setup webhook

Go to FB developer page, setup webhook to https://[bot name].herokuapp.com/webhook, set VERIFY_TOKEN on FB to whatever you set on heroku

5. Profit!

Now you can go to facebook messenger, look for your example bot and chat with it!

Comments