Facebook Messenger,如果用户订阅,则手动发送消息

时间:2017-05-12 02:55:55

标签: facebook-messenger

我正在制作一个机器人,让我的学生可以获得学校餐点菜单。我希望在午餐时间前10分钟向学生发送一份菜单清单。 我应该如何在JavaScript中为此创建代码? 我遇到的主要问题是如何检查时间,以便我的机器人可以在那时发送消息。 我也想知道它的代码是否总是在Facebook服务器上运行,所以我可以使用while循环来检查时间。 我很感激你的建议。 (我使用MongoDB和节点)

var express = require("express");
var request = require("request");
var bodyParser = require("body-parser");

var hey = ["Yeah! "]
var reply;

var app = express();
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
app.listen((process.env.PORT || 5000));

app.get("/", function (req, res) {
  res.send("Deployed!");
});

app.get("/webhook", function (req, res) {
  if (req.query["hub.verify_token"] === process.env.VERIFICATION_TOKEN) {
    console.log("Verified webhook");
    res.status(200).send(req.query["hub.challenge"]);
  } else {
    console.error("Verification failed. The tokens do not match.");
    res.sendStatus(403);
  }
});

app.post('/webhook', function (req, res) {
  var data = req.body;

  if (data.object === 'page') {

    if(d.getHours() === 10 && d.getMinutes() === 5)
      sendTextMessage(senderID, "Success!"); 

    data.entry.forEach(function(entry) {
      var pageID = entry.id;
      var timeOfEvent = entry.time;

      entry.messaging.forEach(function(event) {
        if (event.message) {
          receivedMessage(event);
        } else if(event.postback){
          receivedPostback(event);
        }
        else {
          console.log("Webhook received unknown event: ", event);
        }
      });
    });

    res.sendStatus(200);
  }
});


function receivedMessage(event) {
  var senderID = event.sender.id;
  psid = senderID; 
  var recipientID = event.recipient.id;
  var timeOfMessage = event.timestamp;
  var message = event.message;

  console.log("Received message for user %d and page %d at %d with message:", 
    senderID, recipientID, timeOfMessage);
  console.log(JSON.stringify(message));

  var messageId = message.mid;

  var messageText = message.text;
  var messageAttachments = message.attachments;


  if (messageText) {
    switch (messageText) {

      case 'Check': 
        sendTextMessage(senderID, "isSub: " + isSub);
        sendTextMessage(senderID, "gamerNumber: " + gamerNumber);
        sendTextMessage(senderID, "psid: " + senderID);
        break; 

----(and more)

    function sendGenericMessage(recipientId, payload) {
  var titlee
  var subs
  var image
  switch(payload){
    case "pmorning":
      titlee = "Breakfast"
      subs = //***this is the part where the db value goes in.*** 
      image = "https://cdn.arstechnica.net/wp-content/uploads/sites/3/2016/10/Oculus-Rift-vs-HTC-Vive-vs-PlayStation-VR-1.jpg"
      break;
   ---and more
            }]
          }]
        }
      }
    }
  };  
  sendTypingOn(recipientId);
  callSendAPI(messageData);
}

1 个答案:

答案 0 :(得分:1)

查看node-cron,这样您就可以安排作业在特定时间运行,由CRON expression

指定