-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdeno-linebot.js
567 lines (510 loc) Β· 16.2 KB
/
deno-linebot.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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
'use strict'
import EventEmitter from "https://deno.land/x/[email protected]/mod.ts";
import debug from "https://deno.land/x/[email protected]/debug.ts";
import { Buffer } from "https://deno.land/x/[email protected]/mod.ts";
import { hmac } from "https://deno.land/x/[email protected]/mod.ts";
const debuglog = debug('linebot');
class LineBot extends EventEmitter {
constructor(options) {
super();
this.options = options || {};
this.options.channelId = options.channelId || '';
this.options.channelSecret = options.channelSecret || '';
this.options.channelAccessToken = options.channelAccessToken || '';
if (this.options.verify === undefined) {
this.options.verify = true;
}
this.headers = {
Accept: 'application/json',
'Content-Type': 'application/json',
Authorization: 'Bearer ' + this.options.channelAccessToken
};
this.endpoint = 'https://api.line.me/v2/bot';
this.dataEndpoint = 'https://api-data.line.me/v2/bot';
}
/**
* --- Basic ---
*/
verify(rawBody, signature) {
const hash = hmac('sha256', this.options.channelSecret, rawBody, 'utf8', 'base64');
// Constant-time comparison to prevent timing attack.
if (hash.length !== signature.length) {
return false;
}
let res = 0;
for (let i = 0; i < hash.length; i++) {
res |= (hash.charCodeAt(i) ^ signature.charCodeAt(i));
}
return res === 0;
}
parse(body) {
const that = this;
if (!body || !body.events) {
return;
}
body.events.forEach(function (event) {
debuglog('%O', event);
event.reply = function (message) {
return that.reply(event.replyToken, message);
};
if (event.joined) {
let joinedMemberIds = [];
event.joined.profiles = function () {
if (event.type === 'memberJoined') {
for (let i = 0; i < event.joined.members.length; i++) {
joinedMemberIds.push(event.joined.members[i].userId);
}
if (event.source.type === 'group') {
return that.getGroupMemberProfile(event.source.groupId, joinedMemberIds);
}
if (event.source.type === 'room') {
return that.getRoomMemberProfile(event.source.roomId, joinedMemberIds);
}
}
};
}
if (event.left) {
let leftMemberIds = [];
event.left.profiles = function () {
if (event.type === 'memberLeft') {
for (let i = 0; i < event.left.members.length; i++) {
leftMemberIds.push(event.left.members[i].userId);
}
return that.getUserProfile(leftMemberIds);
}
};
}
if (event.source) {
event.source.profile = function () {
if (event.source.type === 'group') {
return that.getGroupMemberProfile(event.source.groupId, event.source.userId);
}
if (event.source.type === 'room') {
return that.getRoomMemberProfile(event.source.roomId, event.source.userId);
}
return that.getUserProfile(event.source.userId);
};
event.source.member = function () {
if (event.source.type === 'group') {
return that.getGroupMember(event.source.groupId);
}
if (event.source.type === 'room') {
return that.getRoomMember(event.source.roomId);
}
};
}
if (event.message) {
event.message.content = function () {
return that.getMessageContent(event.message.id);
};
}
queueMicrotask(function () {
that.emit(event.type, event);
});
});
}
// Opine middleware
parser(json) {
const parser = json({
verify: function (req, res, buf, encoding) {
req.rawBody = Buffer.from(buf).toString(encoding);
}
});
return (req, res) => {
parser(req, res, () => {
const verify_options = this.options.verify;
const verify_get = this.verify(req.rawBody, req.get('X-Line-Signature'));
if (verify_options && !verify_get) {
return res.sendStatus(400);
}
this.parse(req.body);
return res.json({});
});
};
}
static createMessages(message) {
if (typeof message === 'string') {
return [{
type: 'text',
text: message
}];
}
if (Array.isArray(message)) {
return message.map(function (m) {
if (typeof m === 'string') {
return {
type: 'text',
text: m
};
}
return m;
});
}
return [message];
}
get(path) {
const url = this.endpoint + path;
const options = {
method: 'GET',
headers: this.headers
};
return fetch(url, options);
}
getData(path) {
const url = this.dataEndpoint + path;
const options = {
method: 'GET',
headers: this.headers
};
return fetch(url, options);
}
post(path, body) {
const url = this.endpoint + path;
const options = {
method: 'POST',
headers: this.headers,
body: JSON.stringify(body)
};
return fetch(url, options);
}
static yesterday() {
const tempDate = new Date();
tempDate.setDate(tempDate.getDate() - 1);
const yday = tempDate.toLocaleString('en-US', {
timeZone: 'Asia/Tokyo',
day: '2-digit',
month: '2-digit',
year: 'numeric'
});
return yday.substr(6, 4) + yday.substr(0, 2) + yday.substr(3, 2);
}
/**
* --- Message ---
*/
// Message - Reply message
reply(replyToken, message) {
const url = '/message/reply';
const body = {
replyToken: replyToken,
messages: LineBot.createMessages(message)
};
debuglog('POST %s', url);
debuglog('%O', body);
return this.post(url, body).then(res => res.json()).then((result) => {
debuglog(result);
return result;
});
}
// Message - Send push message
push(to, message) {
const url = '/message/push';
if (Array.isArray(to)) {
return Promise.all(to.map(recipient => this.push(recipient, message)));
}
const body = {
to: to,
messages: LineBot.createMessages(message)
};
debuglog('POST %s', url);
debuglog('%O', body);
return this.post(url, body).then(res => res.json()).then((result) => {
debuglog('%O', result);
return result;
});
}
// Message - Send multicast message
multicast(to, message) {
const url = '/message/multicast';
const body = {
to: to,
messages: LineBot.createMessages(message)
};
debuglog('POST %s', url);
debuglog('%O', body);
return this.post(url, body).then(res => res.json()).then((result) => {
debuglog('%O', result);
return result;
});
}
// γ TO BE IMPLEMENTED γ
// Message - Send narrowcast message
// γ TO BE IMPLEMENTED γ
// Message - Get narrowcast message status
// Message - Send broadcast message
broadcast(message) {
const url = '/message/broadcast';
const body = {
messages: LineBot.createMessages(message)
};
debuglog('POST %s', url);
debuglog('%O', body);
return this.post(url, body).then(res => res.json()).then((result) => {
debuglog('%O', result);
return result;
});
}
// Message - Get content
getMessageContent(messageId) {
const url = `/message/${messageId}/content`;
debuglog('GET %s', url);
return this.getData(url).then(res => res.arrayBuffer()).then((buffer) => {
const result = Buffer.from(buffer).toString('hex');
debuglog(result);
return result;
});
}
// Message - Get the target limit for additional messages
getQuota() {
const url = '/message/quota';
debuglog('GET %s', url);
return this.get(url).then(res => res.json()).then((result) => {
debuglog('%O', result);
return result;
});
}
// Message - Get number of messages sent this month
getTotalSentMessagesThisMonth() {
const url = '/message/quota/consumption';
debuglog('GET %s', url);
return this.get(url).then(res => res.json()).then((result) => {
debuglog('%O', result);
return result;
});
}
// Message - Get number of sent reply messages
getTotalReplyMessages(date) {
return this.getTotalMessages(date, 'reply');
}
// Message - Get number of sent push messages
getTotalPushMessages(date) {
return this.getTotalMessages(date, 'push');
}
// Message - Get number of sent multicast messages
getTotalMulticastMessages(date) {
return this.getTotalMessages(date, 'multicast');
}
// Message - Get number of sent broadcast messages
getTotalBroadcastMessages(date) {
return this.getTotalMessages(date, 'broadcast');
}
// γ TO BE IMPLEMENTED γ
// Message - Retrying an API request
// Message - Get number of sent reply messages
getTotalMessages(date, type) {
if (date == null) {
date = LineBot.yesterday();
}
const url = `/message/delivery/${type}?date=${date}`;
debuglog('GET %s', url);
return this.get(url).then(res => res.json()).then((result) => {
debuglog('%O', result);
return result;
});
}
/**
* --- Managing Audience ---
*/
// γ TO BE IMPLEMENTED γ
// Managing Audience - includes many APIs
/**
* --- Insight ---
*/
// Insight - Get number of message deliveries
getTotalMessagesInsight(date) {
if (date == null) {
date = LineBot.yesterday();
}
const url = `/insight/message/delivery?date=${date}`;
debuglog('GET %s', url);
return this.get(url).then(res => res.json()).then((result) => {
debuglog('%O', result);
return result;
});
}
// Insight - Get friend demographics
getFriendDemographicsInsight() {
const url = '/insight/demographic';
debuglog('GET %s', url);
return this.get(url).then(res => res.json()).then((result) => {
debuglog('%O', result);
return result;
});
}
// γ TO BE IMPLEMENTED γ
// Insight - Get user interaction statistics
// Insight - Get number of followers
getTotalFollowersInsight(date) {
return this.getTotalFollowers(date);
}
getTotalFollowers(date) {
if (date == null) {
date = LineBot.yesterday();
}
const url = `/insight/followers?date=${date}`;
debuglog('GET %s', url);
return this.get(url).then(res => res.json()).then((result) => {
debuglog('%O', result);
return result;
});
}
/**
* --- Users ---
*/
// Users - Get profile
getUserProfile(userId) {
if (Array.isArray(userId)) {
return Promise.all(userId.map(recipient => this.getUserProfile(recipient)));
}
const url = `/profile/${userId}`;
debuglog('GET %s', url);
return this.get(url).then(res => res.json()).then((profile) => {
debuglog('%O', profile);
return profile;
});
}
// γ TO BE IMPLEMENTED γ
// Users - Get a list of users who added your
/**
* --- Bot ---
*/
// Bot - Get bot info
getBotInfo() {
const url = '/info';
debuglog('GET %s', url);
return this.get(url).then(res => res.json()).then((info) => {
debuglog('%O', info);
return info;
});
}
/**
* --- Group ---
*/
// Group - Get group summary
getGroupProfile(groupId) {
const url = `/group/${groupId}/summary`;
debuglog('GET %s', url);
return this.get(url).then(res => res.json()).then((profile) => {
debuglog('%O', profile);
return profile;
});
}
// Group - Get number of users in a group
getGroupMembersCount(groupId) {
const url = `/group/${groupId}/members/count`;
debuglog('GET %s', url);
return this.get(url).then(res => res.json()).then((result) => {
debuglog('%O', result);
return result;
});
}
// Group - Get group member user IDs
getGroupMember(groupId, next) {
const url = `/group/${groupId}/members/ids` + (next ? `?start=${next}` : '');
debuglog('GET %s', url);
return this.get(url).then(res => res.json()).then((groupMember) => {
debuglog('%O', groupMember);
if (groupMember.next) {
return this.getGroupMember(groupId, groupMember.next).then((nextGroupMember) => {
groupMember.memberIds = groupMember.memberIds.concat(nextGroupMember.memberIds);
delete groupMember.next;
return groupMember;
});
}
delete groupMember.next;
return groupMember;
});
}
// Group - Get group member profile
getGroupMemberProfile(groupId, userId) {
if (Array.isArray(userId)) {
return Promise.all(userId.map(recipient => this.getGroupMemberProfile(groupId, recipient)));
}
const url = `/group/${groupId}/member/${userId}`;
debuglog('GET %s', url);
return this.get(url).then(res => res.json()).then((profile) => {
debuglog('%O', profile);
profile.groupId = groupId;
return profile;
});
}
// Group - Leave group
leaveGroup(groupId) {
const url = `/group/${groupId}/leave`;
debuglog('POST %s', url);
return this.post(url).then(res => res.json()).then((result) => {
debuglog('%O', result);
return result;
});
}
/**
* --- Chatroom ---
*/
// Chatroom - Get number of users in a room
getRoomMembersCount(roomId) {
const url = `/room/${roomId}/members/count`;
debuglog('GET %s', url);
return this.get(url).then(res => res.json()).then((result) => {
debuglog('%O', result);
return result;
});
}
// Chatroom - Get room member user IDs
getRoomMember(roomId, next) {
const url = `/room/${roomId}/members/ids` + (next ? `?start=${next}` : '');
debuglog('GET %s', url);
return this.get(url).then(res => res.json()).then((roomMember) => {
debuglog('%O', roomMember);
if (roomMember.next) {
return this.getRoomMember(roomId, roomMember.next).then((nextRoomMember) => {
roomMember.memberIds = roomMember.memberIds.concat(nextRoomMember.memberIds);
delete roomMember.next;
return roomMember;
});
}
delete roomMember.next;
return roomMember;
});
}
// Chatroom - Get room member profile
getRoomMemberProfile(roomId, userId) {
if (Array.isArray(userId)) {
return Promise.all(userId.map(recipient => this.getRoomMemberProfile(roomId, recipient)));
}
const url = `/room/${roomId}/member/${userId}`;
debuglog('GET %s', url);
return this.get(url).then(res => res.json()).then((profile) => {
debuglog('%O', profile);
profile.roomId = roomId;
return profile;
});
}
// Chatroom - Leave room
leaveRoom(roomId) {
const url = `/room/${roomId}/leave`;
debuglog('POST %s', url);
return this.post(url).then(res => res.json()).then((result) => {
debuglog('%O', result);
return result;
});
}
/**
* --- RichMenu ---
*/
// γ TO BE IMPLEMENTED γ
// RichMenu includes many APIs
/**
* --- Account Link ---
*/
// Account Link - Issue link token
getIssueLinkToken(userId) {
const url = `/user/${userId}/linkToken`;
debuglog('GET %s', url);
return this.post(url, {}).then(res => res.json()).then((linkToken) => {
debuglog('%O', linkToken);
return linkToken;
});
}
}
export function linebot(options) {
return new LineBot(options);
}