forked from remixz/messenger-bot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
140 lines (114 loc) · 3.5 KB
/
index.js
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
'use strict'
const url = require('url')
const qs = require('querystring')
const EventEmitter = require('events').EventEmitter
const request = require('request')
const crypto = require('crypto')
class Bot extends EventEmitter {
constructor (opts) {
super()
opts = opts || {}
if (!opts.token) {
throw new Error('Missing page token. See FB documentation for details: https://developers.facebook.com/docs/messenger-platform/quickstart')
}
this.token = opts.token
this.app_secret = opts.app_secret || false
this.verify_token = opts.verify || false
}
getProfile (id, cb) {
if (!cb) cb = Function.prototype
request({
method: 'GET',
uri: `https://graph.facebook.com/v2.6/${id}`,
qs: {
fields: 'first_name,last_name,profile_pic',
access_token: this.token
},
json: true
}, (err, res, body) => {
if (err) return cb(err)
if (body.error) return cb(body.error)
cb(null, body)
})
}
sendMessage (recipient, payload, cb) {
if (!cb) cb = Function.prototype
request({
method: 'POST',
uri: 'https://graph.facebook.com/v2.6/me/messages',
qs: {
access_token: this.token
},
json: {
recipient: { id: recipient },
message: payload
}
}, (err, res, body) => {
if (err) return cb(err)
if (body.error) return cb(body.error)
cb(null, body)
})
}
middleware () {
return (req, res) => {
// we always write 200, otherwise facebook will keep retrying the request
res.writeHead(200, { 'Content-Type': 'application/json' })
if (req.url === '/_status') return res.end(JSON.stringify({status: 'ok'}))
if (this.verify_token && req.method === 'GET') return this._verify(req, res)
if (req.method !== 'POST') return res.end()
let body = ''
req.on('data', (chunk) => {
body += chunk
})
req.on('end', () => {
// check message integrity
if (this.app_secret) {
let hmac = crypto.createHmac('sha1', this.app_secret)
hmac.update(body)
if (req.headers['x-hub-signature'] !== `sha1=${hmac.digest('hex')}`) {
this.emit('error', new Error('Message integrity check failed'))
return res.end(JSON.stringify({status: 'not ok', error: 'Message integrity check failed'}))
}
}
let parsed = JSON.parse(body)
this._handleMessage(parsed)
res.end(JSON.stringify({status: 'ok'}))
})
}
}
_handleMessage (json) {
let entries = json.entry
entries.forEach((entry) => {
let events = entry.messaging
events.forEach((event) => {
// handle inbound messages
if (event.message) {
this._handleEvent('message', event)
}
// handle postbacks
if (event.postback) {
this._handleEvent('postback', event)
}
// handle message delivered
if (event.delivery) {
this._handleEvent('delivery', event)
}
// handle authentication
if (event.optin) {
this._handleEvent('authentication', event)
}
})
})
}
_verify (req, res) {
let query = qs.parse(url.parse(req.url).query)
if (query['hub.verify_token'] === this.verify_token) {
return res.end(query['hub.challenge'])
}
return res.end('Error, wrong validation token')
}
_handleEvent (type, event) {
this.emit(type, event, this.sendMessage.bind(this, event.sender.id))
}
}
module.exports = Bot