wjc0930

Split codes to 4 Parts.

1. app.js
- API Endpoint ( Receive requests from Facebook page and start to make request to Facebook Graph API )
- Open port ( app.listen(PORT_NUMBER) ), Perform verification ( app.get('/webhook') )
- Use/Call Handler function from controller.js

2. controller.js
- Handle Message or Postback
- Use/Call model.js / template.js to make response
- Make request to Facebook's Graph API ( Messaging Platform ) using response, sender_psid

3. template.js
- Make JSON format using data given from controller.js
- Return JSON format ( to be  'response' object in controller.js )

4. models.js
- Get data from database.
- Give data required by controller.js.
+2019/5/25
+mother project : LINEBOT
+new project : 페이스북 메신저 기반 컴공/소융 강의평가 봇
+
### mother project : LINEBOT
최근 수정일 : 2019/5/31<br>
new project : 페이스북 메신저 기반 컴공/소융 강의평가 봇<br>
Description : Everytime 강의 평가 및 과 홈페이지를 기반으로 함.
\ No newline at end of file
......
......@@ -2,9 +2,8 @@
let express = require("express"),
bodyParser= require("body-parser"),
app = express(),
request = require('request'),
config = require('config'),
images = require("./pics");
controller = require('./controller');
app.use(bodyParser.urlencoded({ extended : false}));
app.use(bodyParser.json());
......@@ -20,7 +19,7 @@ app.get('/', (req, res) => res.send('Hello World!'));
app.get('/webhook', (req, res) => {
// Your verify token, Should be a random string.
let VERIFY_TOKEN = "2016104171";
let VERIFY_TOKEN = config.get('facebook.page.verify_token');
// Parse the query params
let mode = req.query['hub.mode'];
......@@ -67,151 +66,17 @@ app.post('/webhook', (req, res) => {
// Check if the event is a message or postback and
// pass the event to the appropriate handler function
if (webhook_event.message) {
handleMessage(sender_psid, webhook_event.message);
controller.handleMessage(sender_psid, webhook_event.message);
} else if (webhook_event.postback) {
handlePostback(sender_psid, webhook_event.postback);
controller.handlePostback(sender_psid, webhook_event.postback);
}
});
// 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
// Returns a '404 Not Found' if event is ninteliot from a page subscription
res.sendStatus(404);
}
});
// Views - handle Message, handle Postback
// Handles message events
const handleMessage = (sender_psid, received_message) => {
let response;
if(received_message.text){
// Create the payload for a basic text message
response = askTemplate()
}
// Sends the reponse message
callSendAPI(sender_psid, response;
}
const handlePostback = (sender_psid, received_postback) => {
let response;
// Get the payload for the postback
let payload = received_postback.payload;
// Set the response based on the postback payload
if (payload === 'CAT_PICS') {
response = imageTemplate('cats', sender_psid);
callSendAPI(sender_psid, response, function(){
callSendAPI(sender_psid, askTemplate('Show me more'));
});
} else if (payload === 'DOG_PICS') {
response = imageTemplate('dogs', sender_psid);
callSendAPI(sender_psid, response, function(){
callSendAPI(sender_psid, askTemplate('Show me more'));
});
} else if(payload === 'GET_STARTED'){
response = askTemplate('Are you a Cat or Dog Person?');
callSendAPI(sender_psid, response);
}
// Send the message to acknowledge the postback
}
const askTemplate = (text) => {
return {
"attachment":{
"type":"template",
"payload":{
"template_type":"button",
"text": text,
"buttons":[
{
"type":"postback",
"title":"Cats",
"payload":"CAT_PICS"
},
{
"type":"postback",
"title":"Dogs",
"payload":"DOG_PICS"
}
]
}
}
}
}
// Sends response messages via the Send API
const callSendAPI = (sender_psid, response, cb = null) => {
// Construct the message body
let request_body = {
"recipient": {
"id": sender_psid
},
"message": response
};
// Send the HTTP request to the Messenger Platform
request({
"uri": "https://graph.facebook.com/v2.6/me/messages",
"qs": { "access_token": config.get('facebook.page.access_token') },
"method": "POST",
"json": request_body
}, (err, res, body) => {
if (!err) {
if(cb){
cb();
}
} else {
console.error("Unable to send message:" + err);
}
});
}
const imageTemplate= (type, sender_id) => {
return {
"attachment":{
"type":"image",
"payload":{
"url": getImage(type, sender_id),
"is_reusable":true
}
}
}
}
let users = {};
const getImage= (type, sender_id) => {
// create user if doesn't exist
if(users[sender_id] === undefined){
users = Object.assign({
[sender_id] : {
'cats_count' : 0,
'dogs_count' : 0
}
}, users);
}
let count = images[type].length, // total available images by type
user = users[sender_id], // // user requesting image
user_type_count = user[type+'_count'];
// update user before returning image
let updated_user = {
[sender_id] : Object.assign(user, {
[type+'_count'] : count === user_type_count + 1 ? 0 : user_type_count + 1
})
};
// update users
users = Object.assign(users, updated_user);
console.log(users);
return images[type][user_type_count];
}
......
let request = require('request'),
template = require('./template'),
config = require('config');
// Views - handle Message, handle Postback
// Handles message events
exports.handleMessage = (sender_psid, received_message) => {
let response;
if(received_message.text){
// Create the payload for a basic text message
response = template.askTemplate()
}
// Sends the reponse message
callSendAPI(sender_psid, response);
}
exports.handlePostback = (sender_psid, received_postback) => {
let response;
// Get the payload for the postback
let payload = received_postback.payload;
// Set the response based on the postback payload
if (payload === 'CAT_PICS') {
response = template.imageTemplate('cats', sender_psid);
callSendAPI(sender_psid, response, function(){
callSendAPI(sender_psid, template.askTemplate('Show me more'));
});
} else if (payload === 'DOG_PICS') {
response = template.imageTemplate('dogs', sender_psid);
callSendAPI(sender_psid, response, function(){
callSendAPI(sender_psid, template.askTemplate('Show me more'));
});
} else if(payload === 'GET_STARTED'){
response = template.askTemplate('Are you a Cat or Dog Person?');
callSendAPI(sender_psid, response);
}
// Send the message to acknowledge the postback
}
// Sends response messages via the Send API
const callSendAPI = (sender_psid, response, cb = null) => {
// Construct the message body
let request_body = {
"recipient": {
"id": sender_psid
},
"message": response
};
// Send the HTTP request to the Messenger Platform
request({
"uri": "https://graph.facebook.com/v2.6/me/messages",
"qs": { "access_token": config.get('facebook.page.access_token') },
"method": "POST",
"json": request_body
}, (err, res, body) => {
if (!err) {
if(cb){
cb();
}
} else {
console.error("Unable to send message:" + err);
}
});
}
File mode changed
let images = require("./pics");
exports.askTemplate = (text) => {
return {
"attachment":{
"type":"template",
"payload":{
"template_type":"button",
"text": text,
"buttons":[
{
"type":"postback",
"title":"Cats",
"payload":"CAT_PICS"
},
{
"type":"postback",
"title":"Dogs",
"payload":"DOG_PICS"
}
]
}
}
}
}
exports.imageTemplate= (type, sender_id) => {
return {
"attachment":{
"type":"image",
"payload":{
"url": getImage(type, sender_id),
"is_reusable":true
}
}
}
}
let users = {};
const getImage= (type, sender_id) => {
// create user if doesn't exist
if(users[sender_id] === undefined){
users = Object.assign({
[sender_id] : {
'cats_count' : 0,
'dogs_count' : 0
}
}, users);
}
let count = images[type].length, // total available images by type
user = users[sender_id], // // user requesting image
user_type_count = user[type+'_count'];
// update user before returning image
let updated_user = {
[sender_id] : Object.assign(user, {
[type+'_count'] : count === user_type_count + 1 ? 0 : user_type_count + 1
})
};
// update users
users = Object.assign(users, updated_user);
console.log(users);
return images[type][user_type_count];
}