【问题标题】:Facebook Messenger bot problemsFacebook Messenger 机器人问题
【发布时间】:2018-10-11 21:22:56
【问题描述】:

我制作了一个 messanager 聊天机器人并第一次尝试部署它,在与各种错误作斗争后,我确实连接了我的页面、应用程序和钩子。

Tough al 似乎在工作,但机器人没有响应。这是我在错误日志中得到的。

我发送“嗨”,但没有回复。当我用谷歌搜索出现的响应错误时,没有适合我的解决方案。

    'use strict'

const 
    express=require('express'),
    bodyParser = require('body-parser'),
    app=express().use(bodyParser.json()); //creates http server

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

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

    if(body.object === 'page'){
        body.entry.forEach(function(entry){

            //Gets the body of the webhook
            let webhook_event=entry.messaging[0];
            console.log(webhook_event);

            //Gets the sender PSID
            let sender_psid=webhook_event.sender.id;
            console.log('Sender PSID: ' + sender_psid);

        });

        res.status(200).send('EVENT_RECEIVED');
    }else{
        res.sendStatus(404);
    }
    if(webhook_event.message){
        handleMessage(sender_psid, webhook_event.message);
    }else if(webhook_event.postback){
        handlePostback(sender_psid, webhook_event.postback);
    }

});
app.get('/', function (req, res) {
    res.send('This is EngiBot Server');
});
app.get('/webhook', (req, res) => {
    let VERIFY_TOKEN = "testbot_verify_token"

    let mode= req.query['hub.mode'];
    let token=req.query['hub.verify_token'];
    let challange = req.query['hub.challange'];

        if (req.query['hub.verify_token'] === VERIFY_TOKEN) {
        res.send(req.query['hub.challenge']);
    } else {
        res.send('Invalid verify token');
    }

    if(mode && token){
        if(mode==='subscribe' && token === VERIFY_TOKEN){

            console.log('WEBHOOK_VERIFIED');
            res.status(200).send(challange);
        }else{
            res.sendStatus(403);
        }
    }
});

function handleMessages(sender_psid, received_message){
    let response;

    if(received_message.text){
        response = {
            "text": 'You sent the message: "${received_message.text}". Now send an image!'
        }
    }else if(received_message.attachments){
        let attachment_url=received_message.attachments[0].payload.url;
        response = {
            "attachment":{
                "type": "template",
                "payload":{
                    "template_type":"generic",
                    "elements": [{
                        "title": "Is this the right picture?",
                        "subtitle": "Tap a button to answer.",
                        "image_url": attachment_url,
                        "buttons": [
                        {
                            "type": "postback",
                            "title": "Yes!",
                            "payload":"yes",
                        },
                        {
                            "type": "postback",
                            "title": "No!",
                            "payload": "no",
                        }
                        ],
                    }]
                }
            }
        }
    }

    callSendAPI(sender.psid, response);
}

function handlePostback(sender_psid, received_postback){
    let response;

    let payload=received_postback.payload;

    if(payload==='yes'){
        response = {"text": "Thanks!"}
    }else if (payload==="no"){
        response ={"text": "Oops, try sending another image."}
    }
    callSendAPI(sender_psid, response);
}

function callSendAPI(sender_psid, response){
    let request_body={
        "recipient": {
        "id": sender_psid
        },
        "message": response
    }
request({
    "uri":"",
    "qs":{"access_token": PAGE_ACCESS_TOKEN},
    "method": "POST",
"json": request_body
}, (err, res, body)=>{
    if(!err){
        console.log('message sent!')
    }else {
        console.error("Unable to send message:" + err);
    }
});
}

【问题讨论】:

  • 嘿,Shaggy,很高兴十年后见到你!好吧,为了让社区更好地理解您的问题 - 请使用代码的相关部分更新您的问题。
  • 需要什么部分? webhhok 类,还是包括机器人在内的所有类?
  • 我想 app/index.js 中的一些代码会有所帮助。
  • 至少显示你的 app/index.js 中的 app.post('/webhook', ????) 长什么样子?
  • index.js 在上面提供:)

标签: javascript node.js facebook chatbot


【解决方案1】:

POST 路由器有问题。 'webhook_event' 在条件块内的 foreach 块内声明,因此其范围在该块的内部。要解决此问题,您应重写代码以匹配范围。这是错误的路由器(我添加了一些 cmets =

app.post('/webhook', (req, res) => {
    let body=req.body; 
        // webhook_event == null -> true

    if(body.object === 'page'){
        body.entry.forEach(function(entry){

            //Gets the body of the webhook
            let webhook_event=entry.messaging[0]; // webhook_event declared // webhook_event == null -> false
            console.log(webhook_event);

            //Gets the sender PSID
            let sender_psid=webhook_event.sender.id;
            console.log('Sender PSID: ' + sender_psid);

        });

        res.status(200).send('EVENT_RECEIVED');
        if(webhook_event.message){ // ReferenceError cause is not defined
        handleMessage(sender_psid, webhook_event.message);
    }else if(webhook_event.postback){ // ReferenceError cause is not defined
        handlePostback(sender_psid, webhook_event.postback);
    }


    }else{
        res.sendStatus(404);
    }

});

【讨论】:

  • 重写评论是什么意思?移动“{”以匹配它内部或在它们外部初始化变量?
  • @ShaggyZG 抱歉,有一个错误现在已修复。
  • 所以让 webhook_event;是否必须在第一个 if 语句的范围之外让正文超出?我可以这样做而不赋予它任何价值吗?我知道它不能为空
  • @Thecave3,因为你的 let webhook_event 在回调函数里面。范围确定 webhook_event 将在哪里活动。在 function(entry){...} 之外,webhook_event 不存在。所以你的 if(webhook_event.message){...} 不起作用。如果你把 if(webhook_event.message){...} 放在 function(entry){...} 里面,它会起作用。
  • 附带说明,let 和 var 的使用对变量的生存有不同的影响。基本上 var 更像是全局的,let 是函数式的(本地的)。或许在网上搜索一下,会有比我更好的解释。
猜你喜欢
  • 1970-01-01
  • 2017-01-28
  • 1970-01-01
  • 2016-08-20
  • 2018-05-18
  • 2016-09-22
  • 2016-08-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多