Skip to content

Commit

Permalink
feat(messaging): support receiving proactive messages (#5728)
Browse files Browse the repository at this point in the history
* feat(messaging): support receiving proactive messages

* proactive-trigger

* add schema validation

* remove proactive-trigger change
  • Loading branch information
samuelmasse committed Dec 3, 2021
1 parent f46a00e commit 57c20f3
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 2 deletions.
25 changes: 24 additions & 1 deletion packages/bp/src/core/messaging/messaging-router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,13 @@ export class MessagingRouter extends CustomRouter {
}

await this.messaging.receive(event.data as MessageNewEventData)
} else if (event.type === 'conversation.started') {
const { error } = ConversationStartedEventSchema.validate(event.data)
if (error) {
return res.status(400).send(error.message)
}

await this.messaging.conversationStarted(event.data as ConversationStartedEventData)
} else if (event.type === 'user.new') {
this.messaging.incrementNewUsersCount()
}
Expand Down Expand Up @@ -69,8 +76,15 @@ export interface MessageNewEventData {
collect: boolean
}

export interface ConversationStartedEventData {
clientId: string
userId: string
conversationId: string
channel: string
}

interface MessagingEvent {
type: 'message.new' | 'user.new'
type: 'message.new' | 'conversation.started' | 'user.new'
data: any
}

Expand All @@ -92,3 +106,12 @@ const MessageNewEventSchema = joi
.required()
})
.required()

const ConversationStartedEventSchema = joi
.object({
clientId: joi.string().required(),
userId: joi.string().required(),
conversationId: joi.string().required(),
channel: joi.string().required()
})
.required()
20 changes: 19 additions & 1 deletion packages/bp/src/core/messaging/messaging-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { AppLifecycle, AppLifecycleEvents } from 'lifecycle'
import LRUCache from 'lru-cache'
import ms from 'ms'
import yn from 'yn'
import { MessageNewEventData } from './messaging-router'
import { MessageNewEventData, ConversationStartedEventData } from './messaging-router'

@injectable()
export class MessagingService {
Expand Down Expand Up @@ -158,6 +158,24 @@ export class MessagingService {
return this.eventEngine.sendEvent(event)
}

async conversationStarted(msg: ConversationStartedEventData) {
if (!this.channelNames.includes(msg.channel)) {
return
}

const event = Event({
direction: 'incoming',
type: 'proactive-trigger',
payload: {},
channel: msg.channel,
threadId: msg.conversationId,
target: msg.userId,
botId: this.botsByClientId[msg.clientId]
})

return this.eventEngine.sendEvent(event)
}

private async fixOutgoingUrls(event: IO.OutgoingEvent, next: IO.MiddlewareNextCallback) {
this.fixPayloadUrls(event.payload)
next()
Expand Down

0 comments on commit 57c20f3

Please sign in to comment.