/
WhatsAppBuilder.kt
317 lines (294 loc) · 11.7 KB
/
WhatsAppBuilder.kt
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
/*
* Copyright (C) 2017/2021 e-voyageurs technologies
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ai.tock.bot.connector.whatsapp
import ai.tock.bot.connector.ConnectorMessage
import ai.tock.bot.connector.ConnectorType
import ai.tock.bot.connector.whatsapp.model.common.WhatsAppTextBody
import ai.tock.bot.connector.whatsapp.model.send.QuickReply
import ai.tock.bot.connector.whatsapp.model.send.WhatsAppBotAction
import ai.tock.bot.connector.whatsapp.model.send.WhatsAppBotActionButton
import ai.tock.bot.connector.whatsapp.model.send.WhatsAppBotActionButtonReply
import ai.tock.bot.connector.whatsapp.model.send.WhatsAppBotActionSection
import ai.tock.bot.connector.whatsapp.model.send.WhatsAppBotAttachment
import ai.tock.bot.connector.whatsapp.model.send.WhatsAppBotBody
import ai.tock.bot.connector.whatsapp.model.send.WhatsAppBotImageMessage
import ai.tock.bot.connector.whatsapp.model.send.WhatsAppBotInteractive
import ai.tock.bot.connector.whatsapp.model.send.WhatsAppBotInteractiveMessage
import ai.tock.bot.connector.whatsapp.model.send.WhatsAppBotInteractiveType
import ai.tock.bot.connector.whatsapp.model.send.WhatsAppBotMessage
import ai.tock.bot.connector.whatsapp.model.send.WhatsAppBotMessageInteractiveMessage
import ai.tock.bot.connector.whatsapp.model.send.WhatsAppBotRecipientType
import ai.tock.bot.connector.whatsapp.model.send.WhatsAppBotRow
import ai.tock.bot.connector.whatsapp.model.send.WhatsAppBotTextMessage
import ai.tock.bot.connector.whatsapp.model.webhook.WhatsAppComponent
import ai.tock.bot.connector.whatsapp.model.webhook.WhatsAppLanguage
import ai.tock.bot.connector.whatsapp.model.webhook.WhatsAppTemplate
import ai.tock.bot.definition.IntentAware
import ai.tock.bot.definition.Parameters
import ai.tock.bot.definition.StoryHandlerDefinition
import ai.tock.bot.definition.StoryStep
import ai.tock.bot.engine.BotBus
import ai.tock.bot.engine.Bus
import ai.tock.bot.engine.I18nTranslator
import ai.tock.bot.engine.action.SendChoice
import mu.KotlinLogging
private val logger = KotlinLogging.logger {}
internal const val WHATS_APP_CONNECTOR_TYPE_ID = "whatsapp"
private const val WHATS_APP_BUTTONS_TITLE_MAX_LENGTH = 20
private const val WHATS_APP_BUTTONS_ID_MAX_LENGTH = 256
private const val WHATS_APP_SECTION_TITLE_MAX_LENGTH = 24
private const val WHATS_APP_ROW_TITLE_MAX_LENGTH = 24
private const val WHATS_APP_ROW_ID_MAX_LENGTH = 200
private const val WHATS_APP_ROW_DESCRIPTION_MAX_LENGTH = 72
private const val WHATS_APP_MAX_ROWS = 10
private const val WHATS_APP_MAX_SECTIONS = 10
/**
* The WhatsApp connector type.
*/
val whatsAppConnectorType = ConnectorType(WHATS_APP_CONNECTOR_TYPE_ID)
/**
* Sends an WhatsApp message only if the [ConnectorType] of the current [BotBus] is [whatsAppConnectorType].
*/
fun <T : Bus<T>> T.sendToWhatsApp(
messageProvider: T.() -> WhatsAppBotMessage,
delay: Long = defaultDelay(currentAnswerIndex)
): T {
if (isCompatibleWith(whatsAppConnectorType)) {
withMessage(messageProvider(this))
send(delay)
}
return this
}
/**
* Sends an WhatsApp message as last bot answer, only if the [ConnectorType] of the current [BotBus] is [whatsAppConnectorType].
*/
fun <T : Bus<T>> T.endForWhatsApp(
messageProvider: T.() -> WhatsAppBotMessage,
delay: Long = defaultDelay(currentAnswerIndex)
): T {
if (isCompatibleWith(whatsAppConnectorType)) {
withMessage(messageProvider(this))
end(delay)
}
return this
}
/**
* Adds a WhatsApp [ConnectorMessage] if the current connector is WhatsApp.
* You need to call [BotBus.send] or [BotBus.end] later to send this message.
*/
fun <T : Bus<T>> T.withWhatsApp(messageProvider: () -> WhatsAppBotMessage): T {
return withMessage(whatsAppConnectorType, messageProvider)
}
/**
* Creates a [WhatsAppBotTextMessage].
*
* @param text the text sent
* @param previewUrl is preview mode is used?
*/
fun BotBus.whatsAppText(
text: CharSequence,
previewUrl: Boolean = false
): WhatsAppBotTextMessage =
WhatsAppBotTextMessage(
text = WhatsAppTextBody(translate(text).toString()),
recipientType = (connectorData.callback as? WhatsAppConnectorCallback)?.recipientType
?: WhatsAppBotRecipientType.individual,
userId = userId.id,
previewUrl = previewUrl
)
/**
* Creates a [WhatsAppBotImageMessage].
*/
fun BotBus.whatsAppImage(
byteImages: ByteArray,
contentType: String = "image/png",
caption: CharSequence? = null
): WhatsAppBotImageMessage =
WhatsAppBotImageMessage(
image = WhatsAppBotAttachment(
byteImages,
contentType,
caption?.let { translate(it).toString() }
),
recipientType = (connectorData.callback as? WhatsAppConnectorCallback)?.recipientType
?: WhatsAppBotRecipientType.individual,
userId = userId.id
)
/**
* Creates a [WhatsAppBotInteractiveMessage]
*/
fun BotBus.whatsAppInteractiveMessage(
nameSpace: String,
templateName: String,
components: List<WhatsAppComponent>? = emptyList()
): WhatsAppBotInteractiveMessage =
WhatsAppBotInteractiveMessage(
template = buildTemplate(nameSpace, templateName, components),
recipientType = (connectorData.callback as? WhatsAppConnectorCallback)?.recipientType
?: WhatsAppBotRecipientType.individual,
userId = userId.id
)
fun I18nTranslator.replyButtonMessage(
text: CharSequence,
vararg replies: QuickReply
) : WhatsAppBotMessageInteractiveMessage = replyButtonMessage(text, replies.toList())
fun I18nTranslator.replyButtonMessage(
text: CharSequence,
replies: List<QuickReply>
) : WhatsAppBotMessageInteractiveMessage = WhatsAppBotMessageInteractiveMessage(
recipientType = WhatsAppBotRecipientType.individual,
interactive = WhatsAppBotInteractive(
type = WhatsAppBotInteractiveType.button,
body = WhatsAppBotBody(translate(text).toString()),
action = WhatsAppBotAction(
buttons = replies.map {
WhatsAppBotActionButton(
reply = WhatsAppBotActionButtonReply(
id = it.payload.checkLength(WHATS_APP_BUTTONS_ID_MAX_LENGTH),
title = translate(it.title).toString().checkLength(WHATS_APP_BUTTONS_TITLE_MAX_LENGTH),
)
)
}
)
)
)
fun I18nTranslator.completeListMessage(
text: CharSequence,
button: CharSequence,
vararg sections: WhatsAppBotActionSection
) : WhatsAppBotMessageInteractiveMessage = completeListMessage(text, button, sections.toList())
fun I18nTranslator.completeListMessage(
text: CharSequence,
button: CharSequence,
sections: List<WhatsAppBotActionSection>,
) : WhatsAppBotMessageInteractiveMessage = WhatsAppBotMessageInteractiveMessage(
recipientType = WhatsAppBotRecipientType.individual,
interactive = WhatsAppBotInteractive(
type = WhatsAppBotInteractiveType.list,
body = WhatsAppBotBody(translate(text).toString()),
action = WhatsAppBotAction(
button = translate(button).toString().checkLength(WHATS_APP_BUTTONS_TITLE_MAX_LENGTH),
sections = sections.map {
WhatsAppBotActionSection(
title = translate(it.title).toString().checkLength(WHATS_APP_SECTION_TITLE_MAX_LENGTH),
rows = it.rows?.map { row ->
WhatsAppBotRow(
id = row.id.checkLength(WHATS_APP_ROW_ID_MAX_LENGTH),
title = translate(row.title).toString().checkLength(WHATS_APP_ROW_TITLE_MAX_LENGTH),
description = translate(row.description).toString().checkLength(WHATS_APP_ROW_DESCRIPTION_MAX_LENGTH)
)
}
)
}
)
)
).also {
if ((it.interactive.action?.sections?.flatMap { s -> s.rows ?: listOf() }?.count() ?: 0) > WHATS_APP_MAX_ROWS) {
error("a list message is limited to $WHATS_APP_MAX_ROWS rows across all sections.")
}
if ((it.interactive.action?.sections?.count() ?: 0) > WHATS_APP_MAX_SECTIONS) {
error("sections count in list message should not exceed $WHATS_APP_MAX_SECTIONS.")
}
if ((it.interactive.action?.button?.count() ?: 0) > WHATS_APP_BUTTONS_TITLE_MAX_LENGTH) {
error("button text ${it.interactive.action?.button} should not exceed $WHATS_APP_BUTTONS_TITLE_MAX_LENGTH chars.")
}
}
fun I18nTranslator.listMessage(
text: CharSequence,
button: CharSequence,
vararg replies: QuickReply
) : WhatsAppBotMessageInteractiveMessage =
listMessage(text, button, replies.toList())
fun I18nTranslator.listMessage(
text: CharSequence,
button: CharSequence,
replies: List<QuickReply>
) : WhatsAppBotMessageInteractiveMessage =
completeListMessage(
text, button, WhatsAppBotActionSection(rows = replies.map {
WhatsAppBotRow(
id = it.payload,
title = it.title,
description = it.subTitle
)
})
)
fun I18nTranslator.nlpQuickReply(
title: CharSequence,
subTitle: CharSequence? = null,
textToSend: CharSequence = title,
) : QuickReply = QuickReply(
translate(title).toString(),
SendChoice.encodeNlpChoiceId(translate(textToSend).toString()),
translate(subTitle).toString(),
)
fun <T: Bus<T>> T.quickReply(
title: CharSequence,
subTitle: CharSequence? = null,
targetIntent: IntentAware,
parameters: Parameters
): QuickReply =
quickReply(title, subTitle, targetIntent, stepName, parameters.toMap())
fun <T: Bus<T>> T.quickReply(
title: CharSequence,
subTitle: CharSequence? = null,
targetIntent: IntentAware,
step: StoryStep<out StoryHandlerDefinition>? = null,
vararg parameters: Pair<String, String>
) : QuickReply = quickReply(title, subTitle, targetIntent.wrappedIntent(), step?.name, parameters.toMap())
fun <T: Bus<T>> T.quickReply(
title: CharSequence,
subTitle: CharSequence? = null,
targetIntent: IntentAware,
step: String? = null,
parameters: Map<String, String> = mapOf()
) : QuickReply =
quickReply(title, subTitle, targetIntent, step, parameters) { intent, s, params ->
SendChoice.encodeChoiceId(intent, s, params, null, null, sourceAppId = null)
}
private fun I18nTranslator.quickReply(
title: CharSequence,
subTitle: CharSequence? = null,
targetIntent: IntentAware,
step: String? = null,
parameters: Map<String, String>,
payloadEncoder: (IntentAware, String?, Map<String, String>) -> String
) : QuickReply = QuickReply(
translate(title).toString(),
payloadEncoder.invoke(targetIntent, step, parameters),
translate(subTitle).toString()
)
private fun buildTemplate(
nameSpace: String,
templateName: String,
components: List<WhatsAppComponent>?
): WhatsAppTemplate {
return WhatsAppTemplate(
namespace = nameSpace,
name = templateName,
language = WhatsAppLanguage(
code = "fr",
policy = "deterministic"
),
components = components
)
}
private fun String.checkLength(maxLength: Int) : String {
if (maxLength > 0 && this.length > maxLength) {
error("text $this should not exceed $maxLength chars.")
}
return this
}