Create a gist now

Instantly share code, notes, and snippets.

@Rafe /.babel.rc
Last active Oct 25, 2016

What would you like to do?
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