김예미

Use Callback function

......@@ -29,7 +29,7 @@ app.get("/webhook", function (req, res) {
// Creates the endpoint for our webhook
app.post('/webhook', (req, res) => {
let body = req.body;
var body = req.body;
if (body.object === 'page') {
......@@ -38,11 +38,11 @@ app.post('/webhook', (req, res) => {
// Gets the message. entry.messaging is an array, but
// will only ever contain one message, so we get index 0
let webhook_event = entry.messaging[0];
var webhook_event = entry.messaging[0];
console.log(webhook_event);
// Get the sender PSID
let sender_psid = webhook_event.sender.id;
var sender_psid = webhook_event.sender.id;
console.log('Sender PSID: ' + sender_psid);
......@@ -63,4 +63,3 @@ app.post('/webhook', (req, res) => {
}
});
......
let request = require('request'),
template = require('./template');
var request = require('request');
var template = require('./template.js');
// Handles message events
exports.handleMessage = (sender_psid, received_message) => {
let response;
if(received_message.text === "처음으로"){
response = template.goToGreetTemplate(received_message);
exports.handleMessage=function(sender_psid, received_message) {
var response;
var text = received_message.text;
if(text === "처음으로"){
template.greetingTemplate(function(result, res){
if(result==true){
console.log(res);
response=res;
}
});
callSendAPI(sender_psid, response);
}else{
response = template.choiceLectProfTemplate(received_message);
template.choiceLectProfTemplate(text, function(result, res){
if(result==true){
response=res;
}
});
}
callSendAPI(sender_psid, response);
}
exports.handlePostback = (sender_psid, received_postback) => {
let response;
exports.handlePostback =function(sender_psid, received_postback) {
var response;
// Get the payload for the postback
let payload = received_postback.payload;
var payload = received_postback.payload;
var firstchoice = payload.substr(0,14);
// Set the response based on the postback payload
if(payload === 'Greeting'){
response = template.greetingTemplate();
console.log('Greeting');
template.greetingTemplate(function(result, res){
if(result==true){
console.log(res);
response=res;
}
});
callSendAPI(sender_psid, response);
}else if(payload.substr(0,14)=== 'CHOICE_BY_PROF'){
}else if(firstchoice === 'CHOICE_BY_PROF'){
handlePostback_choiceByProf(sender_psid, received_postback);
}else if(payload.substr(0,14)=== 'CHOICE_BY_LECT'){
handlePostback_choiceByLect(sender_psid, recieved_postback);
}else if(payload.substr(0,14) ==='CHOICE_BY_HELP'){
handlePostback_help(sender_psid, recieved_postback);
}else if(firstchoice === 'CHOICE_BY_LECT'){
handlePostback_choiceByLect(sender_psid, received_postback);
}else if(firstchoice === 'CHOICE_BY_HELP'){
handlePostback_help(sender_psid, received_postback);
}else if(payload.substr(0,8) === 'MoreRate'){
response = template.moreRateTemplate(received_postback);
template.moreRateTemplate(payload, function(result, res){
if(result==true){
console.log(res);
response=res;
}
});
callSendAPI(sender_psid, response);
}
}
const handlePostback_choiceByProf = (sender_psid, received) => {
let response;
let stat = received.payload.substr(14,6);
const handlePostback_choiceByProf = function(sender_psid, received){
var response;
var payload = received.payload;
var stat = payload.substr(14,6);
if(stat === 'stat_0'){
response = template.getProfNameTemplate(received);
template.getProfNameTemplate(function(result, res){
if(result==true){
console.log(res);
response=res;
}
});
}else if(stat === 'stat_2'){
response = template.moreProfTemplate(received);
template.moreProfTemplate(payload,function(result, res){
if(result==true){
console.log(res);
response=res;
}
});
}else if(stat === 'stat_3'){
response = template.rateTemplate(received);
template.rateTemplate(payload,function(result, res){
if(result==true){
console.log(res);
response=res;
}
});
}
callSendAPI(sender_psid, response);
}
const handlePostback_choiceByLect = (sender_psid, recieved) => {
let response;
let stat = recieved.payload.substr(14,6);
const handlePostback_choiceByLect = function(sender_psid, received){
var response;
var payload = received.payload;
var stat = payload.substr(14,6);
if(stat === 'stat_0'){
response = template.getLectNameTemplate(received);
template.getLectNameTemplate(function(result, res){
if(result==true){
console.log(res);
response=res;
}
});
}else if(stat === 'stat_2'){
response = template.moreLectTemplate(received);
template.moreLectTemplate(payload,function(result, res){
if(result==true){
console.log(res);
response=res;
}
});
}else if(stat === 'stat_3'){
response = template.rateTemplate(received);
template.rateTemplate(payload,function(result, res){
if(result==true){
console.log(res);
response=res;
}
});
}
callSendAPI(sender_psid, response);
}
const handlePostback_help = (sender_psid, received) => {
let response;
let stat = received.payload.substr(14);
const handlePostback_help = function(sender_psid, received) {
var response;
var payload = received.payload;
var stat = payload.substr(14,6);
if(stat === 'stat_0'){
response = template.howToTemplate(received);
template.howToTemplate(function(result, res){
if(result==true){
console.log(res);
response=res;
}
});
}
callSendAPI(sender_psid, response);
}
// Sends response messages via the Send API
const callSendAPI = (sender_psid, response, cb = null) => {
const callSendAPI = (sender_psid, response, cb=null) => {
console.log('response:'+response);
// Send the HTTP request to the Messenger Platform
request({
......@@ -88,7 +146,9 @@ const callSendAPI = (sender_psid, response, cb = null) => {
message: response
}
}, (err, res, body) => {
if (err) {
if (!err) {
console.log('message sent!')
} else {
console.error("Unable to send message:" + err);
}
});
......
const mysql = require('mysql');
const db_config = require('./config/db-config.json');
let db;
function connectDB() {
if (!db) {
db = mysql.createConnection(db_config);
db.connect(function(err) {
if (!err) {
console.log('Database is connected');
} else {
console.log('Error: ', err);
}
});
}
return db;
}
module.exports = connectDB();
const db = require('./db');
var db=require('./db.js');
let greetingText = "안녕하세요! 컴공/소융 강의평가 봇이에요. 아래에 버튼 3개를 눌러주세요."; // 인사말
let greetingTitle = ["교수명으로 검색", "강의명으로 검색", "HELP"];
var greetingText = "안녕하세요! 컴공/소융 강의평가 봇이에요. 아래에 버튼 3개를 눌러주세요."; // 인사말
var greetingTitle = ["교수명으로 검색", "강의명으로 검색", "HELP"];
exports.greetingTemplate = () => {
return {
exports.greetingTemplate = function(cb){
var text={
"attachment":{
"type":"template",
"payload":{
......@@ -30,191 +30,232 @@ exports.greetingTemplate = () => {
]
}
}
}
};
cb(true, text);
}
//stat_0
exports.getProfNameTemplate = (received) => {
return {
exports.getProfNameTemplate = function(cb){
var text={
"attachment":{
"type":"template",
"payload":{
"template_type":"button",
"text": "교수명을 입력하세요.",
"buttons":[
"text": "교수명을 입력하세요.",
"buttons":[
{
"type":"postback",
"title":"처음으로",
"payload":'Greeting'
}
]
"type":"postback",
"title":"처음으로",
"payload":"Greeting"
}
]
}
}
}
};
cb(true, text);
}
exports.getLectNameTemplate = (received) => {
return {
exports.getLectNameTemplate = function(cb){
var text={
"attachment":{
"type":"template",
"payload":{
"template_type":"button",
"text": "강의명을 입력하세요.",
"buttons":[
"text": "강의명을 입력하세요.",
"buttons":[
{
"type":"postback",
"title":"처음으로",
"payload":'Greeting'
}
]
"type":"postback",
"title":"처음으로",
"payload":"Greeting"
}
]
}
}
}
};
cb(true, text);
}
//stat_1
exports.choiceLectProfTemplate = (received) => {
let message = received.text;
db.query('SELECT * FROM reviews WHERE lecturename LIKE ? OR proname LIKE ?', [message,message], function(error,results){
if (err){
console.log(err);
exports.choiceLectProfTemplate=function(message,cb) {
var sqlquery = 'SELECT * FROM reviews WHERE lecturename = ? OR proname = ?';
var par = [message,message];
db.query(sqlquery, par, function(error,results){
if (error){
console.log(error);
res.render('error');
}
if(results==0){
return {text: "검색 결과가 없습니다. 검색어를 다시 입력해주세요."}
if(results.length==0){
cb(true, {text: "검색 결과가 없습니다. 검색어를 다시 입력해주세요."});
}else if(results.length<=2){
return LectProfList(results,0,results.length,false,'0',message);
LectProfList(results,0,results.length,false,'0',message, function(result, text){
if(result==true){
cb(true, text);
}
});
}else if(results.length>2){
return LectProfList(results,0,2,true,'1',message);
LectProfList(results,0,2,true,'1',message, function(result, text){
if(result==true){
cb(true, text);
}
});
}
});
}
const LectProfList = (results,start,length,ismore,morecount,message) => {
const LectProfList = function(results,start,length,ismore,morecount,message,cb){
if(length==1){
return {
"attachment":{
"type":"template",
"payload":{
"template_type":"button",
"text": "검색 결과입니다. 평가를 조회할 강의를 선택하세요.",
"buttons":[
{
"type":"postback",
"title":results[start].lecturename+results[start].proname,
"payload":'CHOICE_BY_PROFstat_3'+results[start].idreviews
}
var title=results[start].lecturename+results[start].proname;
var payload='CHOICE_BY_PROFstat_3'+results[start].idreviews;
var text={
"attachment":{
"type":"template",
"payload":{
"template_type":"button",
"text": "검색 결과입니다. 평가를 조회할 강의를 선택하세요.",
"buttons":[
{
"type":"postback",
"title":title,
"payload":payload
}
]
}
}
}
};
cb(true, text);
}else if((length == 2)&&(!ismore)){
return {
"attachment":{
"type":"template",
"payload":{
"template_type":"button",
"text": "검색 결과입니다. 평가를 조회할 강의를 선택하세요.",
"buttons":[
var title=[results[start].lecturename+results[start].proname, results[start+1].lecturename+results[start+1].proname];
var payload=['CHOICE_BY_PROFstat_3'+results[start].idreviews, 'CHOICE_BY_PROFstat_3'+results[start+1].idreviews];
var text={
"attachment":{
"type":"template",
"payload":{
"template_type":"button",
"text": "검색 결과입니다. 평가를 조회할 강의를 선택하세요.",
"buttons":[
{
"type":"postback",
"title":results[start].lecturename+results[start].proname,
"payload":'CHOICE_BY_PROFstat_3'+results[start].idreviews
"title":title[0],
"payload":title[0]
},
{
"type":"postback",
"title":results[start+1].lecturename+results[start+1].proname,
"payload":'CHOICE_BY_PROFstat_3'+results[start+1].idreviews
}
]
"title":title[1],
"payload":payload[1]
}
]
}
}
}else if((length == 2)&&(ismore)){
return {
"attachment":{
"type":"template",
"payload":{
"template_type":"button",
"text": "검색 결과입니다. 평가를 조회할 강의를 선택하세요. 원하는 강의가 없다면 [더보기]를 눌러주세요.",
"buttons":[
};
cb(true, text);
}else if((length == 2)&&(ismore)){
var title=[results[start].lecturename+results[start].proname, results[start+1].lecturename+results[start+1].proname];
var payload=['CHOICE_BY_PROFstat_3'+results[start].idreviews, 'CHOICE_BY_PROFstat_3'+results[start+1].idreviews, 'CHOICE_BY_PROFstat_2'+message+'/'+morecount];
var text={
"attachment":{
"type":"template",
"payload":{
"template_type":"button",
"text": "검색 결과입니다. 평가를 조회할 강의를 선택하세요. 원하는 강의가 없다면 [더보기]를 눌러주세요.",
"buttons":[
{
"type":"postback",
"title":results[start].lecturename+results[start].proname,
"payload":'CHOICE_BY_PROFstat_3'+results[start].idreviews
"title":title[0],
"payload":payload[0]
},
{
"type":"postback",
"title":results[start+1].lecturename+results[start+1].proname,
"payload":'CHOICE_BY_PROFstat_3'+results[start+1].idreviews
"title":title[1],
"payload":payload[1]
},
{
"type":"postback",
"title":"더보기",
"payload":'CHOICE_BY_PROFstat_2'+message+'/'+morecount
}
]
"payload":payload[2]
}
]
}
}
};
cb(true, text);
}
}
//stat_2
exports.moreProfTemplate = (received) => {
let ms=received.payload.substr(20).split('/');
let more=1*(ms[0]); //to Number
let message=ms[1];
exports.moreProfTemplate = function(payload,cb){
var ms=payload.substr(20).split('/');
var more=1*(ms[0]); //to Number
var message=ms[1];
db.query('SELECT * FROM reviews WHERE lecturename LIKE ? OR proname LIKE ?', [message,message], function(error,results){
if (err){
console.log(err);
var sqlquery='SELECT * FROM reviews WHERE lecturename = ? OR proname = ?';
var par=[message,message];
db.query(sqlquery, par, function(error,results){
if (error){
console.log(error);
res.render('error');
}
if((results.length-2*(more+1))<=0){
return LectProfList(results,2*more,results.length-2*n,false,'0',message);
LectProfList(results,2*more,results.length-2*n,false,'0',message, function(result, text){
if(result==true){
cb(true, text);
}
});
}else{
return LectProfList(results,2*more,2,true,""+(more+1),message);
LectProfList(results,2*more,2,true,""+(more+1),message, function(result, text){
if(result==true){
cb(true, text);
}
});
}
});
}
exports.moreLectTemplate= (received) => {
let ms=received.payload.substr(20).split('/');
let more=1*(ms[0]);
let message=ms[1];
exports.moreLectTemplate= function(payload,cb){
var ms=payload.substr(20).split('/');
var more=1*(ms[0]);
var message=ms[1];
db.query('SELECT * FROM reviews WHERE lecturename LIKE ? OR proname LIKE ?', [message,message], function(error,results){
if (err){
console.log(err);
var sqlquery='SELECT * FROM reviews WHERE lecturename = ? OR proname = ?';
var par=[message,message];
db.query(sqlquery, par, function(error,results){
if (error){
console.log(error);
res.render('error');
}
if((results.length-2*(more+1))<=0){
return LectProfList(results,2*more,results.length-2*n,false,'0',message);
LectProfList(results,2*more,results.length-2*n,false,'0',message, function(result, text){
if(result==true){
cb(true, text);
}
});
}else{
return LectProfList(results,2*more,2,true,""+(more+1),message);
LectProfList(results,2*more,2,true,""+(more+1),message, function(result, text){
if(result==true){
cb(true, text);
}
});
}
});
}
//stat_3
exports.rateTemplate= (received) => {
let id = received.payload.substr(20);
exports.rateTemplate= function(payload,cb){
var id = payload.substr(20);
db.query('SELECT * FROM reviews WHERE idreviews LIKE ?', [id], function(error,results){
if (err){
console.log(err);
var sqlquery='SELECT * FROM reviews WHERE idreviews = ?';
var par=[id];
db.query(sqlquery, par, function(error,results){
if (error){
console.log(error);
res.render('error');
}
let proname=results[0].proname;
let lecname=results[0].lecname;
let reviews=results[0].review.split(',');
let review=reviews[0];
let rate=results[0].avg_rate;
let botsay=[];
let randNum=0;
var proname=results[0].proname;
var lecname=results[0].lecname;
var reviews=results[0].review.split(',');
var review=reviews[0];
var rate=results[0].avg_rate;
var botsay=[];
var randNum=0;
if(rate != 0){
Math.floor((Math.random() * (3-0+1))+0);
}
......@@ -229,82 +270,67 @@ db.query('SELECT * FROM reviews WHERE idreviews LIKE ?', [id], function(error,re
botsay=["무조건 들어요!","갓갓 교수님의 갓갓 수업","안 들으면 후회해요ㅠㅠ", "수강신청 1순위!"];
}
return {
var payload='MoreRate'+id;
var text={
"attachment":{
"type":"template",
"payload":{
"template_type":"button",
"text": proname+" 교수님의 강의 ["+lecname+"]의 강의평입니다.\n **평균 평점: "+rate+"\n **봇의 한줄평: "+botsay[randNum]+"\n **학우의 한줄평: "+reivew,
"buttons":[
"text": proname+" 교수님의 강의 ["+lecname+"]의 강의평입니다.\n **평균 평점: "+rate+"\n **봇의 한줄평: "+botsay[randNum]+"\n **학우의 한줄평: "+reivew,
"buttons":[
{
"type":"postback",
"title":"자세한 강의평 보기",
"payload":'MoreRate'+id
}
]
"type":"postback",
"title":"자세한 강의평 보기",
"payload":payload
}
]
}
}
}
};
cb(true, text);
});
}
exports.moreRateTemplate = (received) => {
let id = received.payload.substr(8);
let total_review="";
exports.moreRateTemplate = function(payload,cb){
var id = payload.substr(8);
var total_review="";
db.query('SELECT * FROM reviews WHERE idreviews LIKE ?', [id], function(error,results){
if (err){
console.log(err);
var sqlquery='SELECT * FROM reviews WHERE idreviews = ?';
var par=[id];
db.query(sqlquery, par, function(error,results){
if (error){
console.log(error);
res.render('error');
}
let reviews=results[0].review.split(',');
var reviews=results[0].review.split(',');
for(var review in reviews){
total_review+=review+"\n";
}
return {text:total_review}
cb(true,{text:total_review});
});
//payload:MoreRate(강의식별번호)
//포스트백 핸들 moreRateTemplate에서 해당 강의의 자세한 평 출력
}
//payload === 'HELP'
exports.howToTemplate= (received) => {
return {
"attachment":{
"type":"template",
"payload":{
"template_type":"button",
"text": "안녕하세요. 경희대학교 컴공/소융 강의평가봇입니다. \n 자세한 사용방법은 아래를 참고하세요. \n\n 1. [교수명으로 검색], [강의명으로 검색] 중 하나를 선택한다. \n 2. 찾고자하는 강의의 교수명/강의명을 입력한다. \n 3. 입력하신 정보에 일치하는 강의/교수 목록 버튼 중 하나를 선택한다. \n 4. 강의/교수 버튼을 선택하면 해당 강의의 강의평가가 제공된다. \n 4-1. 더보기 버튼을 선택하면 해당 조건의 강의를 더 볼 수 있다. \n 5. [자세한 평보기] 버튼을 눌러 학우들의 생생한 강의평가를 자세히 본다. \n\n *언제든지 \"처음으로\"를 입력하면 첫 화면으로 돌아갑니다. \n 그럼 아래 버튼을 눌러 강의평가를 조회해보세요.",
"buttons":[
{
"type":"postback",
"title":"처음으로",
"payload":'Greeting'
}
]
}
}
}
}
exports.goToGreetTemplate = (received) => {
return {
//payload === 'HELP'
exports.howToTemplate = function(cb){
var helptext="안녕하세요. 경희대학교 컴공/소융 강의평가봇입니다. \n\n 1. [교수명으로 검색], [강의명으로 검색] 중 하나를 선택한다. \n 2. 찾고자하는 강의의 교수명/강의명을 입력한다. \n 3. 입력하신 정보에 일치하는 강의/교수 목록 버튼 중 하나를 선택한다. \n 4. 강의/교수 버튼을 선택하면 해당 강의의 강의평가가 제공된다. \n 4-1. 더보기 버튼을 선택하면 해당 조건의 강의를 더 볼 수 있다. \n 5. [자세한 평보기] 버튼을 눌러 학우들의 생생한 강의평가를 자세히 본다. \n\n *언제든지 \"처음으로\"를 입력하면 첫 화면으로 돌아갑니다. \n\n 그럼 아래 버튼을 눌러 강의평가를 조회해보세요.";
var text={
"attachment":{
"type":"template",
"payload":{
"template_type":"button",
"text": "",
"buttons":[
"text": helptext,
"buttons":[
{
"type":"postback",
"title":"처음으로",
"payload":'Greeting'
}
]
"type":"postback",
"title":"처음으로",
"payload":"Greeting"
}
]
}
}
}
};
cb(true,text);
}
......