Skip to content

Instantly share code, notes, and snippets.

@Rafe
Last active June 25, 2018 11:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Rafe/4a6cb3deaf1f23397e7bf294ffea9983 to your computer and use it in GitHub Desktop.
Save Rafe/4a6cb3deaf1f23397e7bf294ffea9983 to your computer and use it in GitHub Desktop.
Facebook bot example
{
"presets": [
"es2015",
"stage-0"
]
}
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) => {
if (req.query['hub.verify_token'] === config.VERIFY_TOKEN) {
res.send(req.query['hub.challenge'])
} else {
res.send('Error, wrong validation token')
}
})
app.post('/webhook', (req, res) => {
console.log(req.body)
req.body.entry.forEach((entry) => {
entry.messaging.forEach((event) => {
if (event.message) {
sendTextMessage({
id: event.sender.id,
text: event.message.text,
})
} else {
console.log('unknown event!!!', event)
}
})
})
res.sendStatus(200)
})
app.listen(port, () => console.log(`listening on port ${port}`))
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)
})
}
{
"name": "fbbot",
"version": "0.0.1",
"description": "facebook bot example",
"main": "src/index.js",
"scripts": {
"build": "./node_modules/.bin/babel index.js -d dist",
"start": "node ./index.js"
},
"author": "Jimmy Chao",
"license": "ISC",
"dependencies": {
"body-parser": "^1.15.2",
"express": "^4.14.0",
"request": "^2.75.0"
},
"devDependencies": {
"babel-cli": "^6.16.0",
"babel-core": "^6.17.0",
"babel-preset-es2015": "^6.16.0",
"babel-preset-stage-0": "^6.16.0",
"foreman": "^2.0.0"
}
}
web: npm start
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment