-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathline.js
More file actions
270 lines (249 loc) · 7.62 KB
/
line.js
File metadata and controls
270 lines (249 loc) · 7.62 KB
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
'use strict';
const lineBot = require('@line/bot-sdk');
//const express = require('express');
const lineException = require('@line/bot-sdk/exceptions');
const events = require('events');
const eventHandler = new events();
var poloniex;
var bitfinex;
var postgres;
// create LINE SDK config from env variables
const config = {
channelAccessToken: process.env.CHANNEL_ACCESS_TOKEN,
channelSecret: process.env.CHANNEL_SECRET,
};
// create LINE SDK client
const client = new lineBot.Client(config);
//// create Express app
//// about Express itself: https://expressjs.com/
//const app = express();
//// register a webhook handler with middleware
//// about the middleware, please refer to doc
//app.post('/webhook', lineBot.middleware(config), (req, res) => {
// Promise
// .all(req.body.events.map(handleEvent))
// .then((result) => res.json(result));
//});
//app.use((err, req, res, next) => {
// if (err instanceof lineException.SignatureValidationFailed) {
// res.status(401).send(err.signature);
// return;
// } else if (err instanceof lineException.JSONParseError) {
// res.status(400).send(err.raw);
// return;
// }
// next(err);
//});
// event handler
function handleEvent(event) {
switch (event.type) {
case 'message':
return handleMessage(event);
break;
case 'follow':
return handleFollow(event);
break;
default:
return Promise.resolve(null);
}
}
function handleFollow(event) {
if (event.type !== 'follow') {
return Promise.resolve(null);
}
const sourceId = resolveSourceId(event);
eventHandler.emit('followReceived', sourceId);
const reply = {
type: 'text',
text: 'follow[' + event.source.type + ',' + sourceId + ']'
}
return client.replyMessage(event.replyToken, reply)
.then(() => {
const notify = {
type: 'text',
text: 'follow[' + event.source.type + ',' + sourceId + ']'
}
// notify owner there has user followed bot
client.pushMessage('U2b1c2b57e07b28577d1fde2f6da0b661', notify);
})
.catch((err) => {
console.log('handleFollow.replyMessage err:', err);
});
}
function handleMessage(event) {
if (event.type !== 'message') {
return Promise.resolve(null);
}
const sourceId = resolveSourceId(event);
var logText = `${sourceId}[${event.source.type}]`;
// build reply message
const reply = {
type: 'text',
text: ''
};
if (event.message.type === 'text') {
console.log(`${logText} text:${event.message.text}`);
eventHandler.emit('textReceived', sourceId, event.message.text);
reply.text = resolveMessageText(sourceId, event.message.text);
}
if (event.message.type === 'sticker') {
reply.text = `sticker[${event.message.packageId},${event.message.stickerId}]`;
}
if (reply.text != undefined && reply.text !== '') {
return client.replyMessage(event.replyToken, reply)
.catch((err) => {
console.log('handleMessage.replyMessage err:', err);
});
}
else {
return Promise.resolve(null);
}
}
function resolveSourceId(event) {
var sourceId;
switch (event.source.type) {
case 'room':
sourceId = event.source.roomId;
break;
case 'group':
sourceId = event.source.groupId;
break;
default:
sourceId = event.source.userId;
}
return sourceId;
}
const users = {};
function loadLineUsers() {
// Preload registed users from postgres database
postgres.getAllUsers((error, data) => {
if (error == null) {
for(let key in data) {
let sourceId = data[key].sourceId;
let hasNotification = data[key].hasNotification;
if (users[sourceId] == undefined) {
users[sourceId] = {};
}
if (users[sourceId].notification == undefined && hasNotification == true) {
users[sourceId].notification = setInterval(pushNotification, 30 * 60 * 1000, sourceId);
users[sourceId].notificationTime = new Date();
}
console.log('Load user:' + sourceId + " has notification:" + hasNotification);
}
} else {
console.log(error);
}
});
}
function resolveMessageText(sourceId, messageText) {
if (sourceId == undefined) {
return undefined;
}
// initialize users for each source id
if (users[sourceId] == undefined) {
users[sourceId] = {};
// access to postgres database
postgres.getUser(sourceId, (error, data) => {
if (error != null && error.code === postgres.errorCode.noData) {
postgres.setUser(sourceId, false, '');
}
});
}
var replyText;
switch (messageText.toLowerCase())
{
case 'zec':
case 'btc':
case 'eth':
case 'bch':
replyText = poloniex.getCurrencyInfo(messageText);
console.log(`get currency info:${replyText}`);
break;
case 'iot':
case 'iota':
replyText = bitfinex.getCurrencyInfo('iot');
console.log(`get currency info:${replyText}`);
break;
case 'notify':
if (users[sourceId].notification == undefined) {
users[sourceId].notification = setInterval(pushNotification, 30 * 60 * 1000, sourceId);
replyText = 'start receiving notification';
replyText += '\n';
replyText += getAllCurrencyInfo();
users[sourceId].notificationTime = new Date();
// Update user setting to database, carefull about writing delay in callback
postgres.setUser(sourceId, true, users[sourceId].notificationTime);
} else {
clearInterval(users[sourceId].notification);
replyText = 'stop receiving notification';
postgres.setUser(sourceId, false, '');
}
console.log(`notification changed:${sourceId}`);
break;
default:
}
return replyText;
}
function getAllCurrencyInfo() {
var text;
// Currently poloniex uses public API get all currency info at one time,
// just makes first currency has timestamp.
text = poloniex.getCurrencyInfo('btc') + '\n';
text += poloniex.getCurrencyInfo('zec', false) + '\n';
text += poloniex.getCurrencyInfo('eth', false) + '\n';
text += poloniex.getCurrencyInfo('bch', false) + '\n';
text += bitfinex.getCurrencyInfo('iot');
return text;
}
function pushNotification(sourceId) {
var notify = {
type: 'text',
text: ''
}
notify.text = getAllCurrencyInfo();
client.pushMessage(sourceId, notify);
users[sourceId].notificationTime = new Date();
}
module.exports = {
eventHandler,
init: (poloniexModule, bitfinexModule, postgresModule, expressApp) => {
poloniex = poloniexModule;
bitfinex = bitfinexModule;
postgres = postgresModule;
// post webhook request for line bot and handle request error
// register a webhook handler with middleware, about the middleware, please refer to doc
expressApp.post('/webhook', lineBot.middleware(config), (req, res) => {
Promise
.all(req.body.events.map(handleEvent))
.then((result) => res.json(result));
});
expressApp.use((err, req, res, next) => {
if (err instanceof lineException.SignatureValidationFailed) {
res.status(401).send(err.signature);
return;
} else if (err instanceof lineException.JSONParseError) {
res.status(400).send(err.raw);
return;
}
next(err);
});
},
start: (port) => {
if (poloniex == undefined || bitfinex == undefined || postgres == undefined) {
console.log('The line module must be done init with valid modules before start');
return;
}
loadLineUsers();
},
};
// Modify to do as module
//// listen on port
//const port = process.env.PORT || 8088;
//app.listen(port, () => {
// console.log(`listening on ${port}`);
// loadAllUsers();
// poloniex.init();
// poloniex.start();
// bitfinex.init();
// bitfinex.start();
//});