· 7 years ago · Jun 23, 2018, 03:08 PM
1'use strict';
2
3const express = require('express');
4const bodyParser = require('body-parser');
5const ZaloOA = require('zalo-sdk').ZaloOA;
6const BaseBot = require('botmaster').BaseBot;
7
8class ZaloBot extends BaseBot {
9 /**
10 * Constructor to the ZaloBot class
11 *
12 * @param {object} settings - ZaloBot take a settings
13 * object as first param.
14 * @example
15 * // single page bot
16 * const ZaloBot = new ZaloBot({
17 * oaId: 'YOUR OA ID',
18 * oaSecret: 'YOUR OA Secret'
19 * webhookEndpoint: 'someEndpoint'
20 * })
21 */
22
23 constructor(settings) {
24 super(settings);
25 this.type = 'zalo';
26 this.requiresWebhook = true;
27 this.webhookEndpoint = settings.webhookEndpoint;
28
29 const zaConfig = {
30 oaid: settings.oaId,
31 secretkey: settings.oaSecret
32 }
33 this.zaloOA = new ZaloOA(zaConfig);
34
35
36 this.receives = {
37 text: true,
38 attachment: {
39 audio: true,
40 file: true,
41 image: true,
42 video: true,
43 location: true,
44 fallback: true,
45 },
46 echo: true,
47 read: true,
48 delivery: true,
49 postback: true,
50 quickReply: true,
51 };
52
53 this.sends = {
54 text: true,
55 quickReply: true,
56 locationQuickReply: true,
57 senderAction: {
58 typingOn: true,
59 typingOff: true,
60 markSeen: true,
61 },
62 attachment: {
63 audio: true,
64 file: true,
65 image: true,
66 video: true,
67 },
68 };
69
70 this.retrievesUserInfo = true;
71
72 this.__createMountPoints();
73 }
74
75 /**
76 * @ignore
77 * sets up the app. that will be mounted onto a botmaster object
78 * Note how neither of the declared routes uses webhookEndpoint.
79 * This is because I can now count on botmaster to make sure that requests
80 * meant to go to this bot are indeed routed to this bot. Otherwise,
81 * I can also use the full path: i.e. `${this.type}/${this.webhookEndpoint}`.
82 */
83 __createMountPoints() {
84 this.app = express();
85 this.requestListener = this.app;
86 }
87
88 /**
89 * @ignore
90 * see botmaster's BaseBot #getUserInfo
91 *
92 * @param {string} userId id of the user whose information is requested
93 */
94 async __getUserInfo(userId) {
95 if(!userId) {
96 console.log('Error: You must provide userId');
97 return null;
98 }
99 const response = await this.zaloOA.api('getprofile', { uid: userId });
100 const profile = response.data;
101 return profile;
102 }
103
104 async sendTextMessageTo(text, recipientId, sendOptions) {
105 try {
106 await this.zaloOA.api('sendmessage/text', 'POST', { uid: recipientId, message: text });
107 return true;
108 } catch(error){
109 Console.log('Error:' , error);
110 return false;
111 }
112 }
113}
114
115module.exports = ZaloBot;