forked from voiceflow-gallagan/heroku-vf-slackbot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
334 lines (311 loc) · 9.45 KB
/
index.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
/* eslint-disable no-await-in-loop */
import slack_pkg from '@slack/bolt'
const { App } = slack_pkg
import { cleanEmail, stripEmojis, stripBackSlashs, cleanText, CHIP_ACTION_REGEX, ANY_WORD_REGEX } from './components/utils.js'
import * as Home from './components/home.js'
import axios from 'axios'
import { Text } from 'slate'
import escapeHtml from 'escape-html'
const VOICEFLOW_API_KEY = process.env.VOICEFLOW_API_KEY
const SLACK_APP_TOKEN = process.env.SLACK_APP_TOKEN
const SLACK_BOT_TOKEN = process.env.SLACK_BOT_TOKEN
const SLACK_SIGNING_SECRET = process.env.SLACK_SIGNING_SECRET
let noreply
// Create the Slack app
const app = new App({
signingSecret: SLACK_SIGNING_SECRET,
token: SLACK_BOT_TOKEN,
socketMode: true,
appToken: SLACK_APP_TOKEN,
})
// Slack app_mention event
app.event('app_mention', async ({ event, client, say }) => {
try {
let i = await client.users.info({
user: event.user,
})
let userName = i.user.profile.real_name_normalized
await say(`Hi ${userName}`)
let utterance = event.text.split('>')[1]
utterance = stripEmojis(utterance)
utterance = cleanEmail(utterance)
if (utterance === 'hi' || utterance === 'hi there') {
await interact(event.user, say, client, {
type: 'launch',
})
} else {
await interact(event.user, say, client, {
type: 'text',
payload: utterance,
})
}
} catch (error) {
console.error(error)
}
})
// Listen for users opening your App Home
app.event('app_home_opened', async ({ event, client }) => {
Home.show(client, event)
})
app.action(CHIP_ACTION_REGEX, async ({ action, say, ack, client }) => {
ack()
if (action.type !== 'button') return
// get the user id from the action id
let userID = action.action_id.split(':')[2]
let path = action.action_id.split(':')[1]
await client.users.info({
user: userID,
})
if (path.includes('path-')) {
await interact(userID, say, client, {
type: path,
payload: {
label: action.value,
},
})
} else {
await interact(userID, say, client, {
type: 'intent',
payload: {
query: action.value,
label: action.value,
intent: {
name: path,
},
entities: [],
},
})
}
})
app.message(ANY_WORD_REGEX, async ({ message, say, client }) => {
// Ignoring some message types
if (
message.subtype === 'message_changed' ||
message.subtype === 'message_deleted' ||
message.subtype === 'message_replied'
)
return
// Cleaning user's utterance from Slack
let utterance = stripEmojis(message.text)
// Formating Slack email format from <mailto:name@email.com|name@email.com> to name@email.com
utterance = cleanEmail(utterance)
console.log('Utterance:', utterance)
if (utterance === 'hi' || utterance === 'hi there') {
await interact(message.user, say, client, {
type: 'launch',
})
} else {
await interact(message.user, say, client, {
type: 'text',
payload: utterance,
})
}
})
;(async () => {
// Start the app
await app.start()
console.log(`⚡️ Bolt app is running!`)
})()
// Interact with Voiceflow | Dialog Manager API
async function interact(userID, say, client, request) {
clearTimeout(noreply)
await client.users.info({
user: userID,
})
// call the Voiceflow API with the user's ID & request
const response = await axios({
method: 'POST',
url: `https://general-runtime.voiceflow.com/state/user/${userID}/interact`,
headers: { Authorization: VOICEFLOW_API_KEY, 'Content-Type': 'application/json' },
data: {
request,
config: {
tts: false,
stripSSML: true,
},
},
})
// Handeling the API response
for (const trace of response.data) {
switch (trace.type) {
case 'text': {
// We use Slate's rendering
// and add custom styling
const serialize = node => {
if (Text.isText(node)) {
let string = node.text
let tags = ''
if (node.fontWeight) {
tags = '*'
}
if (node.italic) {
tags = tags + '_'
}
if (node.underline) {
// ignoring underline tag as Slack doesn't support it
// https://api.slack.com/reference/surfaces/formatting
}
if (node.strikeThrough) {
tags = tags + '~'
}
return `${tags}${string}${tags.split('').reverse().join('')}`
}
const children = node.children.map(n => serialize(n)).join('')
switch (node.type) {
case 'link':
return `<${escapeHtml(node.url)}|${children}>`
default:
return children
}
}
// Render slate content
let renderedMessage = trace.payload.slate.content
.map((slateData) =>
slateData.children
.map((slateChild) => serialize(slateChild))
.join('')
)
.join('\n')
console.log('Render:',renderedMessage)
try {
await say({
text: 'Voiceflow Bot',
blocks: [
{
type: 'section',
text: {
type: 'mrkdwn',
text: cleanText(stripBackSlashs(renderedMessage)),
},
},
],
})
} catch (error) {
// Avoid breaking the Bot by ignoring then content if not supported
console.log('Not supported yet')
return false
}
break
}
case 'speak': {
try {
await say({
text: 'Voiceflow Bot',
blocks: [
{
type: 'section',
text: {
type: 'mrkdwn',
text: stripBackSlashs(trace.payload.message),
},
},
],
})
} catch (error) {
// Avoid breaking the Bot by ignoring then content if not supported
console.log('Not supported yet')
return false
}
break
}
case 'visual': {
if (trace.payload.visualType === 'image') {
try {
await say({
text: 'Voiceflow Bot',
blocks: [
{
type: 'image',
image_url: trace.payload.image,
alt_text: 'image',
},
],
})
} catch (error) {
// Avoid breaking the Bot by ignoring then content if not supported
console.log('Not supported yet')
return false
}
}
break
}
case 'choice': {
const buttons = trace.payload.buttons
if (buttons.length) {
try {
let url = null
await say({
text: 'Voiceflow Bot',
blocks: [
{
type: 'actions',
elements: buttons.map(({ name, request }) => {
// Handle URL action
if(Object.keys(request.payload).includes("actions")){
if(Object.values(request.payload.actions[0]).includes("open_url")){
url = escapeHtml(request.payload.actions[0].payload.url)
}
}
if (request.type == 'intent') {
let button = {
type: 'button',
action_id: `chip:${
request.payload.intent.name
}:${userID}:${Math.random().toString(6)}`,
text: {
type: 'plain_text',
text: name,
emoji: true,
},
value: name,
style: 'primary'
}
if(url){ button.url = url}
return button
} else {
let button = {
type: 'button',
action_id: `chip:${
request.type
}:${userID}:${Math.random().toString(6)}`,
text: {
type: 'plain_text',
text: name,
emoji: true,
},
value: name,
style: 'primary'
}
if(url){ button.url = url}
return button
}
}),
},
],
})
} catch (error) {
// Avoid breaking the Bot by ignoring then content if not supported
console.log('Not supported yet')
return false
}
}
break
}
case 'no-reply': {
noreply = setTimeout(function () {
interact(userID, say, client, {
type: 'no-reply',
})
}, trace.payload.timeout * 1000)
break
}
case 'end': {
// an end trace means the the Voiceflow dialog has ended
console.log('End Convo')
clearTimeout(noreply)
return false
}
}
}
return true
}