如何防止我的Nodejs应用发布两个请求

时间:2018-11-28 11:18:22

标签: node.js request facebook-send-api

我正在用Node.js编写一个Facebook Messenger机器人应用程序。我将代码中的大多数功能分离到单独的js文件中,然后使用导出将功能公开给其他文件。该代码不会产生错误,但是,当我每次向它发送消息时运行它时,它都会使用两条消息进行回复,如下图所示。 enter image description here

单独文件的代码如下所示

index.js的代码

'use strict'

const express = require('express')
const bodyParser = require('body-parser')
const request = require('request')
const receivers = require('./sources/messageReceivers.js')

const cool = require('cool-ascii-faces')

const app = express()

const PORT = process.env.PORT || 5000

app.set('port', (PORT));
console.log("running on port "+PORT);
app.use(bodyParser.urlencoded({extended: false}))

app.use(bodyParser.json())

//ROUTES
app.get('/', function(req, res){
    res.send("Hie I am a faceboook messenger chatbot, please use messenger to converse with me.")
})

// for facebook
app.get('/webhook', function(req, res){
    if (req.query['hub.verify_token']==="mrfishbot") {
        res.status(200).send(req.query['hub.challenge'])
        console.log("verify token verified");
    }else{
        res.status(403).end()
        res.send("Wrong token")
    }
})

//Post event

app.post('/webhook', (req, res) =>{
    var orderItem = "null"
    var userPhone = "null"
    if(req.body.object === 'page'){
        let messaging_events = req.body.entry[0].messaging
        for (let i = 0; i < messaging_events.length; i++){
            let event = messaging_events[i]
            let sender = event.sender.id

            console.log("Now we are on event number %d", i)
            //console.log("You texted that***** %s",msgTxt)
            console.log(event)

            if (event.postback) {
                orderItem = receivers.receivedPostBack(event)
            }else if(event.message){
                if(event.message.text){
                    userPhone = receivers.receivedMessage(event)
                }else if (event.message.quick_reply) {
                    userPhone = receivers.receivedMessage(event)
                }
            }   
        }
        res.status(200).end()
    }
})

messageReceivers.js的代码

const fbservices = require('./fbservices.js')

exports.receivedMessage = function (event){
    console.log("received message method fired")
    var senderId = event.sender.id
    var message = event.message

    var value = "null"

    var greeting = ["hello", "hi", "hie", "HI", "HELLO", "HIE", "hey", "HEY", "Hey", "Hello", "Hi"]

    console.log(event)

    if(message.quickReply){
        var quickReplyPayload = message.quickReply.payload

        return "null"
    }else if (message.text) {
        console.log("The message was a text message")

        if (is_in_array(message.text, greeting)) {
            console.log("Message is a greeting")

        fbservices.sendText(senderId, "Hello to you too")

        }

    }

}

function is_in_array(s,your_array) {
    for (var i = 0; i < your_array.length; i++) {
        if (your_array[i].toLowerCase() === s.toLowerCase()) return true
    }
    //return false
}

fbservices.js的代码

const request = require('request')
const bodyParser = require('body-parser')

let PAGE_ACCESS_TOKEN = "XXXXXXXXXXXX"
let FB_RESPONSE_URI = "https://graph.facebook.com/v2.6/me/messages"

//Responsible for sending the actual message to facebook
exports.sendText = function (sender, textM){
    let messageData = "{text: text}"
    console.log("The reply is: %s",textM)
    request({
        "url": FB_RESPONSE_URI,
        "qs": {"access_token": PAGE_ACCESS_TOKEN},
        "method": 'POST',
        "json": {
            message_type:"RESPONSE",
            recipient: {id: sender},
            message: {text: textM.substring(0, 100)}
        }
    }, function(error, response, body){
        if(error){
            console.log("sending error")
        }else if(response.body.error){
            console.log("response body error")
            console.log(response)
        }
    })
}

非常感谢您的帮助。

0 个答案:

没有答案