wjc0930

Tutorial code for making Facebook chatbot.

node_modules
+2019/5/25
+mother project : LINEBOT
+new project : 페이스북 메신저 기반 컴공/소융 강의평가 봇
+
var express = require("express");
var request = require("request");
var bodyParser = require("body-parser");
var app = express();
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
app.listen((process.env.PORT || 5000));
// Server index page
app.get("/", function (req, res) {
res.send("Deployed!");
});
// Facebook Webhook
// Used for verification
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);
}
});
// All callbacks for Messenger will be POST-ed here
app.post("/webhook", function (req, res) {
// Make sure this is a page subscription
if (req.body.object == "page") {
// Iterate over each entry
// There may be multiple entries if batched
req.body.entry.forEach(function(entry) {
// Iterate over each messaging event
entry.messaging.forEach(function(event) {
if (event.postback) {
processPostback(event);
}
});
});
res.sendStatus(200);
}
});
function processPostback(event) {
var senderId = event.sender.id;
var payload = event.postback.payload;
if (payload === "Greeting") {
// Get user's first name from the User Profile API
// and include it in the greeting
request({
url: "https://graph.facebook.com/v2.6/" + senderId,
qs: {
access_token: process.env.PAGE_ACCESS_TOKEN,
fields: "first_name"
},
method: "GET"
}, function(error, response, body) {
var greeting = "";
if (error) {
console.log("Error getting user's name: " + error);
} else {
var bodyObj = JSON.parse(body);
name = bodyObj.first_name;
greeting = "Hi " + name + ". ";
}
var message = greeting + "My name is SP Movie Bot. I can tell you various details regarding movies. What movie would you like to know about?";
sendMessage(senderId, {text: message});
});
}
}
// sends message to user
function sendMessage(recipientId, message) {
request({
url: "https://graph.facebook.com/v2.6/me/messages",
qs: {access_token: process.env.PAGE_ACCESS_TOKEN},
method: "POST",
json: {
recipient: {id: recipientId},
message: message,
}
}, function(error, response, body) {
if (error) {
console.log("Error sending message: " + response.error);
}
});
}
This diff is collapsed. Click to expand it.
{
"name": "spbot",
"version": "1.0.0",
"description": "SPBot Server",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node app.js"
},
"author": "WonJun Choi",
"license": "ISC",
"dependencies": {
"body-parser": "^1.19.0",
"express": "^4.17.0",
"mongoose": "^5.5.11",
"request": "^2.88.0"
}
}