forked from astider/messenger_bot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patholdserver.js
349 lines (266 loc) · 9.75 KB
/
oldserver.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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
/**
* Module dependencies
*/
require('dotenv').config();
const Botmaster = require('botmaster')
const express = require('express');
const https = require('https');
const http = require('http');
const fetch = require('node-fetch')
const port = process.env.PORT || 3002;
const app = express();
let weatherAPI = require('./app/apis/weather.api.js')
let messengerProfileAPI = require('./app/apis/messenger_profile.api.js')
let userMgt = require('./app/controllers/userManagement.controller.js')
let database = userMgt.database
//let firebase = require('firebase')
/*
let firebaseConfig = {
apiKey: process.env.firebaseAPIKey,
authDomain: "messengerchatbot-f6775.firebaseapp.com",
databaseURL: "https://messengerchatbot-f6775.firebaseio.com",
storageBucket: "messengerchatbot-f6775.appspot.com",
messagingSenderId: "524406259822"
}
firebase.initializeApp(firebaseConfig)
let database = firebase.database()
*/
app.listen(port, () => {
console.log('Express app started on port ' + port);
});
const messengerSettings = {
credentials: {
verifyToken: process.env.vToken,
pageToken: process.env.pageToken,
fbAppSecret: process.env.appSecret,
},
webhookEndpoint: process.env.hookPlace,
// botmaster will mount this webhook on https://Your_Domain_Name/messenger/webhook1234
};
const botsSettings = [{
messenger: messengerSettings
}];
const botmasterSettings = {
botsSettings,
app
};
const botmaster = new Botmaster(botmasterSettings);
const messengerBot = new Botmaster.botTypes.MessengerBot(messengerSettings);
botmaster.addBot(messengerBot)
let onMemStatus = []
userMgt.getAllSubscribedID((err, ids) => {
if(err) console.log(err);
else {
ids.forEach((id) => {
onMemStatus[id] = { 'subscription': true }
})
console.log('onMem size: ' + Object.keys(onMemStatus).length);
}
})
let _users = database.ref('users')
_users.on('child_changed', (childSnapshot, prevChildKey) => {
console.log('child changed!');
let newSubscription = childSnapshot.val().subscribed
if(onMemStatus[childSnapshot.key]) {
console.log('found onemem index');
if(!onMemStatus[childSnapshot.key].subscription) {
console.log('onmem index has bool');
onMemStatus[childSnapshot.key].subscription = newSubscription
}
else {
console.log('onemem index has no bool');
onMemStatus[childSnapshot.key] = { 'subscription': newSubscription }
}
} else {
console.log('no onmem index found');
onMemStatus[childSnapshot.key] = { 'subscription': newSubscription }
}
console.log('onmem @ id = ' + onMemStatus[childSnapshot.key].subscription);
console.log('onmem size = ' + Object.keys(onMemStatus).length);
})
botmaster.on('update', (bot, update) => {
console.log('enter update event');
console.log('onmem users: ' + Object.keys(onMemStatus).length);
let user = onMemStatus[update.sender.id]
if(!user || user == null) {
onMemStatus[update.sender.id] = { 'subscription': false }
user = onMemStatus[update.sender.id]
}
//---------------- check subscription status -------------------
if(!user.subscription &&
update.message.text != 'ไม่ต้องการ Subscribe' && update.message.text != 'ต้องการ Subscribe' ) {
console.log('no sub info recorded');
let a = Promise.resolve(userMgt.checkIfSubscribed(update.sender.id))
a.then(function(isSub){
if(!isSub) {
//bot.sendTextMessageTo('', update.sender.id)
onMemStatus[update.sender.id] = { 'subscription': false }
bot.sendTextMessageTo('คุณยังไม่ได้ subscribe บอท', update.sender.id)
let answer = ['ต้องการ Subscribe', 'ไม่ต้องการ Subscribe']
setTimeout( () => {
bot.sendDefaultButtonMessageTo(answer, update.sender.id, 'Subscribe บอทของเราเพื่อใช้งานฟีเจอร์เพิ่มเติม')
}, 100)
}
else {
onMemStatus[update.sender.id] = { 'subscription': true }
messengerProfileAPI.getUserInfo(update.sender.id, (err, info) => {
bot.sendTextMessageTo(`สวัสดีคุณ ${info.first_name}`, update.sender.id)
})
}
})
.catch(function(err){
console.log('error promise checking subscription ' + err);
})
} else console.log('sub status of ' + update.sender.id + ' is ' + user.subscription);
//------------------- end checking ---------------
if (!user.subscription &&
(update.message.text == 'ต้องการ Subscribe' || update.message.text == 'ไม่ต้องการ Subscribe') ) {
if(update.message.text == 'ต้องการ Subscribe') {
// change subsribe to true
if(!userMgt.checkDupID(update.sender.id)) {
userMgt.recordNewUserID(update.sender.id)
onMemStatus[update.sender.id].subscription = true
} else {
userMgt.setSubscription(update.sender.id, true)
onMemStatus[update.sender.id].subscription = true
}
console.log(`status: ${onMemStatus[update.sender.id].subscription}`);
bot.sendTextMessageTo('จัดไป ;)', update.sender.id);
bot.sendTextMessageTo(`ระบบ Subscribe ข้อมูลของคุณเรียบร้อยแล้ว`, update.sender.id)
} else {
bot.reply(update, 'สนใจก็บอกมานะ');
}
}
//---------------------------------------------
// subscribed features
if(onMemStatus[update.sender.id].subscription) {
//---- greeting with kitties
if (update.message.text === 'ดี' ||
update.message.text === 'หวัดดี' ||
update.message.text === 'นี่' ||
update.message.text.indexOf('สวัสดี') > -1 )
{
fetch('http://random.cat/meow')
.then( (res) => { return res.json() })
.then(function(json){
let att = {
'type': 'image',
'payload':{
'url': json.file
}
}
bot.sendAttachmentTo(att, update.sender.id)
}).catch(function(err){
console.log('fetch error');
console.log(err)
})
}
// weather report
else if (update.message.text.indexOf('อุณหภูมิเท่าไร') > -1 ||
update.message.text.indexOf('สภาพอากาศ') > -1 ||
update.message.text.indexOf('ร้อน') > -1) {
console.log('weather reporting!');
weatherAPI.getReport(function(err, result){
if(err) console.log(err);
else bot.sendTextMessageTo(result, update.sender.id);
})
}
else if (update.message.text === '777778547') {
let uid = update.sender.id
// checkDupID(uid, function(err, isDup){
// if(!isDup) recordNewUserID(uid)
// else console.log('dup id found');
// })
}
else if (update.message.text === 'aaa1414s1') {
//readDB()
userMgt.getAllID(function(err, list){
if(err) console.log(err);
else if(list) {
console.log(list);
list.map((a)=>{
bot.sendTextMessageTo('text', a);
})
}
})
}
else if(user.subscription && !(update.message.text == 'ต้องการ Subscribe' || update.message.text == 'ไม่ต้องการ Subscribe')) {
const messages = ['บอทยังไม่เข้าใจข้อความของคุณ',
'เรากำลังพัฒนาบอทให้มีความสามารถสูงขึ้น เพื่อเข้าใจคำพูดของคุณ']
bot.sendTextCascadeTo(messages, update.sender.id)
}
}
});
console.log('started');
let nodeSchedule = require('node-schedule');
let rerunner = nodeSchedule.scheduleJob('*/5 * * * *', function(){
console.log('running');
//if(testSubjectID != "" && botIdentifier != null)
//messengerBot.sendIsTypingMessageTo(testSubjectID);
//messengerBot.sendTextMessageTo("YOLO", testSubjectID)
//console.log('I can spam this : ' + testSubjectID);
});
//heroku server timezone is gmt+0.00
/*
let quiz = nodeSchedule.scheduleJob('1 30 9 * * *', function(){
userMgt.getAllSubscribedID(function(err, list){
if(err) console.log(err);
else if(list) {
console.log(list);
list.map((a)=>{
let quiz = database.ref('quiz').once('value')
.then(function(snapshot){
let quizObject = snapshot.val()
console.log(quizObject);
})
})
}
})
})
*/
let quiz = database.ref('quiz').once('value')
.then(function(snapshot){
let quizObject = snapshot.val()
console.log('quiz here');
console.log(quizObject);
console.log(quizObject.length);
for(let i = 0; i < quizObject.length; i++) {
console.log(quizObject[i].q);
console.log(`choices: ${quizObject[i].0}, ${quizObject[i].1}`);
}
})
let weatherReporter = nodeSchedule.scheduleJob('0 0 5,11,17,23 * * *', function(){
userMgt.getAllID(function(err, list){
if(err) console.log(err);
else if(list) {
console.log(list);
list.map((a)=>{
weatherAPI.getReport(function(err, result){
if(err) console.log(err);
else messengerBot.sendTextMessageTo(result, a);
})
})
}
})
})
/*
messengerProfileAPI.getUserInfo('1432315113461939', function(err, info){
messengerBot.sendTextMessageTo('bot started!', '1432315113461939');
messengerBot.sendTextMessageTo(`สวัสดี ${info.first_name}`, '1432315113461939');
})
*/
userMgt.getAllSubscribedID(function(err, ids){
if(err) console.log(err);
else console.log('success');
})
/*
getAllID(function(err, list){
if(err) console.log(err);
else if(list) {
console.log(list);
list.map((a)=>{
messengerBot.sendTextMessageTo('bot started!', a);
})
}
})
*/