|
| 1 | +# Description: |
| 2 | +# Real Time Updates router for Facebook and Instagram. |
| 3 | +# |
| 4 | +# Configuration: |
| 5 | +# FACEBOOK_APP_ACCESS_TOKEN |
| 6 | +# REAL_TIME_ROOM |
| 7 | +# WAIT_MINUTES |
| 8 | +# |
| 9 | +# Notes: |
| 10 | +# Set up your Real-Time updates as descried here: https://developers.facebook.com/docs/graph-api/real-time-updates/ |
| 11 | +# And here: https://instagram.com/developer/realtime/ |
| 12 | +# |
| 13 | +# The `verify_token` is "token". |
| 14 | +# |
| 15 | +# Author: |
| 16 | +# adamgross42 |
| 17 | + |
| 18 | +module.exports = (robot) -> |
| 19 | + |
| 20 | + robot.router.get ['/facebook', '/instagram'], (req, res) -> |
| 21 | + if req.param('hub.mode') == 'subscribe' and req.param('hub.verify_token') == 'token' |
| 22 | + res.send req.param('hub.challenge') |
| 23 | + else |
| 24 | + res.send 400 |
| 25 | + |
| 26 | + robot.router.post '/facebook', (req, res) -> |
| 27 | + if req.body.entry[0].changes[0].value.verb == 'add' and req.body.entry[0].changes[0].value.item == 'status' |
| 28 | + res.send 200 |
| 29 | + pageId = req.body.entry[0].id |
| 30 | + postId = req.body.entry[0].changes[0].value.post_id |
| 31 | + robot.http("https://graph.facebook.com/#{pageId}?access_token=" + process.env.FACEBOOK_APP_ACCESS_TOKEN) |
| 32 | + .header('Accept', 'application/json') |
| 33 | + .get() (err, res, body) -> |
| 34 | + body = JSON.parse body |
| 35 | + robot.messageRoom "#{process.env.REAL_TIME_ROOM}", "New post on #{body.name} Page: https://www.facebook.com/#{postId.split('_')[1]}." |
| 36 | + # Wait some time before pulling post stats |
| 37 | + setTimeout () -> |
| 38 | + robot.http("https://graph.facebook.com/#{postId.split('_')[1]}/likes?summary=true&access_token=" + process.env.FACEBOOK_APP_ACCESS_TOKEN) |
| 39 | + .header('Accept', 'application/json') |
| 40 | + .get() (err, res, body) -> |
| 41 | + body = JSON.parse body |
| 42 | + if body.summary |
| 43 | + likes = body.summary.total_count |
| 44 | + else |
| 45 | + likes = 0 |
| 46 | + robot.messageRoom "#{process.env.REAL_TIME_ROOM}", "After #{process.env.WAIT_MINUTES} minutes, the Facebook post https://www.facebook.com/#{postId.split('_')[1]} has #{likes} likes." |
| 47 | + , process.env.WAIT_MINUTES * 60000 |
| 48 | + |
| 49 | + robot.router.post '/instagram', (req, res) -> |
| 50 | + robot.messageRoom "#{process.env.REAL_TIME_ROOM}", "New post on Instagram." |
| 51 | + res.send 200 |
0 commit comments