forked from minh164/chatbot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
246 lines (225 loc) · 8.58 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
// const {Storage} = require('@google-cloud/storage');
// const storage = new Storage({
// projectId: 'my-project-1534652034762',
// credentials: {
// private_key: process.env.GOOGLE_PRIVATE_KEY.replace(/\\n/g, '\n'),
// client_email: process.env.GOOGLE_CLIENT_EMAIL
// }
// // credentials: JSON.parse(process.env.GCS_KEYFILE)
// });
// // Makes an authenticated API request.
// storage
// .getBuckets()
// .then((results) => {
// const buckets = results[0];
// console.log('Buckets:');
// buckets.forEach((bucket) => {
// console.log(bucket.name);
// });
// })
// .catch((err) => {
// console.error('ERROR:', err);
// });
// console.log(JSON.parse(process.env.GCS_KEYFILE).project_id);
// const GoogleAuth = require('google-auth-library');
// function authorize() {
// return new Promise(resolve => {
// const authFactory = new GoogleAuth();
// const jwtClient = new authFactory.JWT(
// process.env.GOOGLE_CLIENT_EMAIL, // defined in Heroku
// process.env.GOOGLE_PRIVATE_KEY, // defined in Heroku
// ['https://www.googleapis.com/auth/calendar']
// );
// jwtClient.authorize(() => resolve(jwtClient));
// });
// }
var logger = require('morgan');
var http = require('http');
var bodyParser = require('body-parser');
var express = require('express');
var router = express();
const dialogflow = require('dialogflow');
const uuid = require('uuid');
var app = express();
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false
}));
var server = http.createServer(app);
var request = require("request");
app.get('/', (req, res) => {
res.send("Home page. Server running okay.");
});
// Đây là đoạn code để tạo Webhook
app.get('/webhook', function(req, res) {
console.log(2);
if (req.query['hub.verify_token'] === 'chatbot') {
res.send(req.query['hub.challenge']);
}
res.send('Error, wrong validation token');
});
// Xử lý khi có người nhắn tin cho bot
app.post('/webhook', function(req, res) {
console.log(req.body);
var entries = req.body.entry;
for (var entry of entries) {
var messaging = entry.messaging;
for (var message of messaging) {
var senderId = message.sender.id;
if (message.message) {
// If user send text
if (message.message.text) {
var text = message.message.text;
// console.log(text); // In tin nhắn người dùng
sendMessage(senderId, "Tui là bot đây: " + text);
request.get('https://bots.dialogflow.com/facebook/f11dde88-e067-458b-82f9-a933af52a05d/webhook?hub.verify_token=bot', function(error, response, body){
console.log(body);
});
request.post({url:'https://bots.dialogflow.com/facebook/f11dde88-e067-458b-82f9-a933af52a05d/webhook', form: req}, function(err,res,body){
console.log(req);
});
/**
* Send a query to the dialogflow agent, and return the query result.
* @param {string} projectId The project to be used
*/
// async function runSample(projectId = 'my-project-1534652034762') {
// // A unique identifier for the given session
// const sessionId = uuid.v4();
// // Create a new session
// const sessionClient = new dialogflow.SessionsClient();
// const sessionPath = sessionClient.sessionPath(projectId, sessionId);
// // The text query request.
// const request = {
// session: sessionPath,
// queryInput: {
// text: {
// // The query to send to the dialogflow agent
// text: text,
// // The language used by the client (en-US)
// languageCode: 'en-US',
// },
// },
// };
// console.log('đây là:'+sessionId);
// // Send request and log result
// const responses = await sessionClient.detectIntent(request);
// console.log('Detected intent');
// const result = responses[0].queryResult;
// console.log('Query: ${result.queryText}');
// console.log('Response: ${result.fulfillmentText}');
// if (result.intent) {
// console.log('Intent: ${result.intent.displayName}');
// } else {
// console.log('No intent matched.');
// }
// }
// runSample();
}
}
}
}
res.status(200).send("OK");
});
//tự động gửi tin nhắn đến user
// autoMessage();
// function autoMessage(){
// app.get('https://graph.facebook.com/2382560798445202?fields=gender&access_token=EAAH17oX3IIIBAAIDNngmB8FSiZB5I43LswJO5gty40efd6BSV72HhqojNdpACllH1vna5JZBDVkhxxaNaZBLHQgDPdLlG7kw7KSZCLtqyI8ZBvfUd5tMSUiRt9oQNcVNNhIZCQ9U7KdOtNe8JawiiY2LJJTYl8ocfPmmqO156sILLhq1hJZAmZAZB', function(res){
// console.log(res);
// sendMessage(2382560798445202, "hello babe!");
// });
// }
// Gửi thông tin tới REST API để trả lời
function sendMessage(senderId, message) {
request({
url: 'https://graph.facebook.com/v2.6/me/messages',
qs: {
access_token: "EAAH17oX3IIIBAAIDNngmB8FSiZB5I43LswJO5gty40efd6BSV72HhqojNdpACllH1vna5JZBDVkhxxaNaZBLHQgDPdLlG7kw7KSZCLtqyI8ZBvfUd5tMSUiRt9oQNcVNNhIZCQ9U7KdOtNe8JawiiY2LJJTYl8ocfPmmqO156sILLhq1hJZAmZAZB",
},
method: 'POST',
json: {
recipient: {
id: senderId
},
message: {
text: message
},
}
});
}
app.set('port', process.env.PORT || 5000);
app.set('ip', process.env.IP || "0.0.0");
server.listen(app.get('port'), app.get('ip'), function() {
console.log("Chat bot server listening at %s:%d ", app.get('ip'), app.get('port'));
});
// // # SimpleServer
// // A simple chat bot server
// // var logger = require('morgan');
// var http = require('http');
// var bodyParser = require('body-parser');
// var express = require('express');
// var router = express();
//
// var app = express();
// app.use(logger('dev'));
// app.use(bodyParser.json());
// app.use(bodyParser.urlencoded({
// extended: false
// }));
// var server = http.createServer(app);
// var request = require("request");
//
// app.get('/', (req, res) => {
// res.send("Home page. Server running okay.");
// });
//
// // Đây là đoạn code để tạo Webhook
// app.get('/webhook', function(req, res) {
// if (req.query['hub.verify_token'] === 'chatbot') {
// res.send(req.query['hub.challenge']);
// }
// res.send('Error, wrong validation token.');
// });
//
// // Xử lý khi có người nhắn tin cho bot
// app.post('/webhook', function(req, res) {
// var entries = req.body.entry;
// for (var entry of entries) {
// var messaging = entry.messaging;
// for (var message of messaging) {
// var senderId = message.sender.id;
// if (message.message) {
// // If user send text
// if (message.message.text) {
// var text = message.message.text;
// console.log(text); // In tin nhắn người dùng
// sendMessage(senderId, "Tui là bot đây: " + text);
// }
// }
// }
// }
//
// res.status(200).send("OK");
// });
//
//
// // Gửi thông tin tới REST API để trả lời
// function sendMessage(senderId, message) {
// request({
// url: 'https://graph.facebook.com/v2.6/me/messages',
// qs: {
// access_token: "EAAH17oX3IIIBAAIDNngmB8FSiZB5I43LswJO5gty40efd6BSV72HhqojNdpACllH1vna5JZBDVkhxxaNaZBLHQgDPdLlG7kw7KSZCLtqyI8ZBvfUd5tMSUiRt9oQNcVNNhIZCQ9U7KdOtNe8JawiiY2LJJTYl8ocfPmmqO156sILLhq1hJZAmZAZB",
// },
// method: 'POST',
// json: {
// recipient: {
// id: senderId
// },
// message: {
// text: message
// },
// }
// });
// }
// # SimpleServer
// A simple chat bot server