-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathBotpressConnectApp.ts
286 lines (224 loc) · 11.1 KB
/
BotpressConnectApp.ts
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
import { IAppAccessors, IHttp, ILogger, IModify, IPersistence, IRead, IConfigurationExtend, IEnvironmentRead, IConfigurationModify, ITypingOptions } from '@rocket.chat/apps-engine/definition/accessors';
import { App } from '@rocket.chat/apps-engine/definition/App';
import { ILivechatRoom } from '@rocket.chat/apps-engine/definition/livechat';
import { IMessage, IPostMessageSent } from '@rocket.chat/apps-engine/definition/messages';
import { IAppInfo } from '@rocket.chat/apps-engine/definition/metadata';
import { IRoom } from '@rocket.chat/apps-engine/definition/rooms';
import { IUser } from '@rocket.chat/apps-engine/definition/users';
import { AppSetting, settings } from './config/SettingsBotpress';
import { IUIKitResponse, UIKitBlockInteractionContext } from '@rocket.chat/apps-engine/definition/uikit';
import { UIKitIncomingInteractionContainerType } from '@rocket.chat/apps-engine/definition/uikit/UIKitIncomingInteractionContainer';
import { checkIfValidRoom, parseBotAnswer } from './lib/botpress';
import { ISetting, } from '@rocket.chat/apps-engine/definition/settings';
import { IApp } from '@rocket.chat/apps-engine/definition/IApp';
export class BotpressConnectApp extends App implements IPostMessageSent {
constructor(info: IAppInfo, logger: ILogger, accessors: IAppAccessors, app: IApp) {
super(info, logger, accessors);
}
// -------------------------------------------------------------
// Use static variables to refresh them on app settings update
// -------------------------------------------------------------
public static botAliasName;
public static botID;
public static botURL;
public static botRoom;
public async initialize(configurationExtend: IConfigurationExtend, environmentRead: IEnvironmentRead): Promise<void> {
await this.extendConfiguration(configurationExtend);
this.getLogger().log('Init Botpress Connector',);
}
// ---------------------------------------
// Button action handler
// ---------------------------------------
public async executeBlockActionHandler(context: UIKitBlockInteractionContext, read: IRead, http: IHttp, persistence: IPersistence, modify: IModify): Promise<IUIKitResponse> {
try {
const interactionData = context.getInteractionData();
const { room, container: { id, type }, value, message, user } = interactionData;
if (type !== UIKitIncomingInteractionContainerType.MESSAGE) {
return context.getInteractionResponder().successResponse();
}
if (!message) {
return context.getInteractionResponder().successResponse();
}
// -------------------------------------------------------------------------
// Init Values
// -------------------------------------------------------------------------
if (!BotpressConnectApp.botRoom) {
this.initVariables(read);
}
const sender = await read.getUserReader().getByUsername(BotpressConnectApp.botRoom);
const validRoom = await checkIfValidRoom(read, message, true, BotpressConnectApp.botRoom);
if (!validRoom) {
return context.getInteractionResponder().successResponse();
}
if (value) {
if (interactionData.message) {
let block = JSON.parse(JSON.stringify(interactionData.message.blocks));
let choice = "";
block[0].elements.map(el => {
if (el.value === value) {
choice = el.text.text;
}
})
await this.deleteActionBlocks(modify, sender, id, "`" + choice + "`");
}
}
const chatRoom = room as ILivechatRoom;
let botpressMessage = {
"type": "text",
"text": value
}
const { data } = await http.post(BotpressConnectApp.botURL + "/api/v1/bots/" + BotpressConnectApp.botID + "/converse/" + user.id, {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
content: JSON.stringify(botpressMessage)
});
if (!data.responses) {
return context.getInteractionResponder().successResponse();
}
data.responses.map(async (response) => {
await parseBotAnswer(this, message.id, response, sender, chatRoom, read, modify, BotpressConnectApp.botAliasName);
});
return context.getInteractionResponder().successResponse();
} catch (error) {
return context.getInteractionResponder().errorResponse();
}
}
public async deleteActionBlocks(modify: IModify, appUser: IUser, msgId: string, choice: string): Promise<void> {
const msg = await modify.getUpdater().message(msgId, appUser);
msg.setEditor(appUser).setBlocks(modify.getCreator().getBlockBuilder().getBlocks());
msg.setText(choice);
return modify.getUpdater().finish(msg);
};
public async executePostMessageSent(message: IMessage, read: IRead, http: IHttp, persistence: IPersistence, modify: IModify): Promise<void> {
// -------------------------------------------------------------------------
// Init Variables
// -------------------------------------------------------------------------
if (!BotpressConnectApp.botRoom) {
this.initVariables(read);
}
const sender = await read.getUserReader().getByUsername(BotpressConnectApp.botRoom);
const validRoom = await checkIfValidRoom(read, message, false, BotpressConnectApp.botRoom);
if (!validRoom) {
return;
}
const botVersion = await http.get(BotpressConnectApp.botURL + "/version");
const { text, editedAt, room, id, threadId } = message;
const chatRoom = room as ILivechatRoom;
let botpressMessage;
const versionDiff = await this.compareVersion(botVersion.content, "12.26.7");
// ------------------------------------------------------------
// meatadata is available from botpress version > v12.26.7
// ------------------------------------------------------------
if (versionDiff) {
botpressMessage = {
"type": "text",
"text": text,
"metadata": {
"sendername": message.sender.name,
"senderusername": message.sender.username,
"senderemail": message.sender.emails[0]?.address
}
}
} else {
botpressMessage = {
"type": "text",
"text": text,
}
}
const replyInThread = await read.getEnvironmentReader().getSettings().getValueById(AppSetting.ppBotpressReplyInThread);
const notifiedId: string = "@" + BotpressConnectApp.botRoom;
const isNotified = message.text?.includes(notifiedId);
//If "Reply In Thread" option is selected, then the bot should only respond when it is mentioned
if (replyInThread) {
if (!isNotified && !message.threadId) {
return;
}
}
let replyId = id;
if (!replyInThread) {
replyId = message.sender.id;
}
if (threadId) {
replyId = threadId;
}
const { data } = await http.post(
BotpressConnectApp.botURL
+ "/api/v1/bots/"
+ BotpressConnectApp.botID
+ "/converse/"
+ replyId,
{
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
content: JSON.stringify(botpressMessage)
});
if (!data.responses) {
return;
}
data.responses.map(async (response) => {
await parseBotAnswer(this, id, response, sender, chatRoom, read, modify, BotpressConnectApp.botAliasName);
});
}
private async compareVersion(v1: any, v2: string) {
const v1Array = v1.split(".");
const v2Array = v2.split(".");
if (parseInt(v1Array[0]) > parseInt(v2Array[0])) {
return true;
} else {
if (parseInt(v1Array[1]) > parseInt(v2Array[1])) {
return true;
} else {
if (parseInt(v1Array[2]) > parseInt(v2Array[2])) {
return true;
} else {
return false;
}
}
}
}
private async showTyping(sender: IUser, room: IRoom, read: IRead): Promise<void> {
const tpyingOptions: ITypingOptions = {
id: room.id,
username: BotpressConnectApp.botRoom
}
await read.getNotifier().typing(tpyingOptions);
}
private async sendNotifyMessage(sender: IUser, room: IRoom, read: IRead, text: string): Promise<void> {
const botAlias = await read.getEnvironmentReader().getSettings().getValueById(AppSetting.ppBotAlias);
const msg = read.getNotifier().getMessageBuilder().setText(text)
.setUsernameAlias(botAlias).setEmojiAvatar(':space_invader:')
.setRoom(room).setSender(sender).getMessage();
await read.getNotifier().notifyUser(sender, msg);
}
protected async extendConfiguration(configuration: IConfigurationExtend): Promise<void> {
await Promise.all(settings.map((setting) => configuration.settings.provideSetting(setting)));
}
protected async initVariables(read) {
BotpressConnectApp.botRoom = await read.getEnvironmentReader().getSettings().getValueById(AppSetting.ppBotpressRCChannel);
BotpressConnectApp.botURL = await read.getEnvironmentReader().getSettings().getValueById(AppSetting.ppBotpressServerUrl);
BotpressConnectApp.botID = await read.getEnvironmentReader().getSettings().getValueById(AppSetting.ppBotpressBotID);
BotpressConnectApp.botAliasName = await read.getEnvironmentReader().getSettings().getValueById(AppSetting.ppBotAlias);
}
public async onSettingUpdated(setting: ISetting, configurationModify: IConfigurationModify, read: IRead, http: IHttp): Promise<void> {
// -------------------------------------
// Value mapping
// -------------------------------------
if (setting.id == AppSetting.ppBotAlias) {
BotpressConnectApp.botAliasName = setting.value;
}
if (setting.id == AppSetting.ppBotpressBotID) {
BotpressConnectApp.botID = setting.value;
}
if (setting.id == AppSetting.ppBotpressRCChannel) {
BotpressConnectApp.botRoom = setting.value;
}
if (setting.id == AppSetting.ppBotpressServerUrl) {
BotpressConnectApp.botURL = setting.value;
}
return super.onSettingUpdated(setting, configurationModify, read, http);
}
}