Skip to content
This repository has been archived by the owner on Sep 5, 2020. It is now read-only.

Integration: Facebook Messenger

Oskred400 edited this page Nov 29, 2018 · 8 revisions

Facebook Messenger Integration

Proof of Concept

TODO

Integration Notes

//this is a node.js file for creating webhook. the default port is 5000. using the express as server.

//contents of index.js files for webhook programming //to create a webhook for facebook messenger api

'use strict';

const
  express=require('express'),
  bodyparser=require('body-parser'),
  app=express().use(bodyparser.json());

//set up server port at 5000

app.listen(process.env.PORT||5000, ()=> console.log("webhook listening"));

//now put webhook end point get method

app.get('/webhook', (req, res) => {

  // Your verify token. Should be a random string.
  let VERIFY_TOKEN = "Oskred"

  // Parse the query params
  let mode = req.query['hub.mode'];
  let token = req.query['hub.verify_token'];
  let challenge = req.query['hub.challenge'];

  // Checks if a token and mode is in the query string of the request
  if (mode && token) {

    // Checks the mode and token sent is correct
    if (mode === 'subscribe' && token === VERIFY_TOKEN) {

      // Responds with the challenge token from the request
      console.log('WEBHOOK_VERIFIED');
      res.status(200).send(challenge);

    } else {
      // Responds with '403 Forbidden' if tokens do not match
      res.sendStatus(403);
    }
  }
});

//now put up a webhook endpoint post method

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

  let body = req.body;

  // Checks an event from page
  if (body.object === 'page') {

    // Iterates over each entry - there may be multiple if batched
    body.entry.forEach(function(entry) {

      // Gets the message. entry.messaging is an array, but
      // will only ever contain one message, so we get index 0
      let webhook_event = entry.messaging[0];
      console.log(webhook_event);
    });

    // Returns a '200 OK' response to all requests
    res.status(200).send('EVENT_RECEIVED');
  } else {
    // Returns a '404 Not Found' if event is not from a page subscription
    res.sendStatus(404);
  }


})

//commands to be executed after // 1. node index.js // 2. curl -X GET "localhost:5000/webhook?hub.verify_token=Oskred&hub.challenge=CHALLENGE_ACCEPTED&hub.mode=subscribe" // 3. curl -H "Content-Type: application/json" -X POST "localhost:5000/webhook" -d '{"object": "page", "entry": [{"messaging": [{"message": "Hello World"}]}]}'

//Not a part of code: Something i found in Stack Overflow Regarding webhook integration and Callback URLs:

"Once upon a time, there was an authorize callback. So, your question is perfectly reasonable.

Facebook has removed it from the app settings form. So probably it is gone for good, but I have not seen any "official" word on the matter. (i.e. zero heads up that the feature is going away.)" I'll see of any other possibility

//This is a python code.

#import packages

import requests
import json

#import the request, route and all packages required for http end point

from bottle import debug, request, route, run

#define the required verify token, page token and Graph_Url for FB

GRAPH_URL = "https://graph.facebook.com/v2.6"
VERIFY_TOKEN = 'Oskred'
PAGE_TOKEN = 'PAGE_TOKEN'

#requests to messenger

def send_to_messenger(ctx):

    url = "{0}/me/messages?access_token={1}".format(GRAPH_URL, PAGE_TOKEN)
    response = requests.post(url, json=ctx)

#creating the HTTP endpoint

@route('/webhook/', method=["GET","POST"])
def bot_endpoint():
    if request.method.lower()=="get":
            #Facebook requires hub.verify_token and hub.challenge
        verify_token=request.GET.get('hub.verify_token')
        challenge=request.GET.get('hub.challenge')
        if verify_token== VERIFY_TOKEN :
            url= "{0}/me/subscribed_apps?access_token={1}".format(GRAPH_URL, PAGE_TOKEN)
            response=requests.post(url)
            return challenge

    else:
        body = json.loads(request.body.read())
        user_id = body['entry'][0]['messaging'][0]['sender']['id']
        page_id = body['entry'][0]['id']
        message_text = body['entry'][0]['messaging'][0]['message']['text']
            # we just echo to show it works
            
        if user_id != page_id:
            ctx = {
                'recipient': {
                    'id': user_id,
                },
                'message': {
                'text': message_text,
                }
            }
        response = send_to_messenger(ctx)
    return ''


debug(True)
run(reloader=True, port=8088)

This is a node.js code using node package messenger-bot. Run: npm install messenger-bot in project directory and the required node modules would be installed. The functionality of the code is yet to be confirmed. However, it creates an HTTP end point at '/'.

// this is another javascript file using package messenger-bot

'use strict'

const http=require('http')
const bot1=require('messenger-bot')

//declaring variables for bot

let bot = new bot1(
    {
        token: '<Your_Page_Token>',
        verify: 'Oskred'
    }
) 

bot.on('error', (err) => {
    console.log(err.message)
  })
  
  bot.on('message', (payload, reply) => {
    let text = payload.message.text
  
    bot.getProfile(payload.sender.id, (err, profile) => {
      if (err) throw err
  
      reply({ text }, (err) => {
        if (err) throw err
  
        console.log(`Echoed back to ${profile.first_name} ${profile.last_name}: ${text}`)
      })
    })
  })
  
  http.createServer(bot.middleware()).listen(3000) //Listen at port 3000

TODO