From 50dbc7ddebc394ab4320609d3a0709bafc2ea7c9 Mon Sep 17 00:00:00 2001 From: Lucas Avila Date: Thu, 6 May 2021 22:25:23 -0300 Subject: [PATCH] add code to handle client-side bot messages --- components/ChatWindow.tsx | 62 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) diff --git a/components/ChatWindow.tsx b/components/ChatWindow.tsx index 045e359..016866a 100644 --- a/components/ChatWindow.tsx +++ b/components/ChatWindow.tsx @@ -153,6 +153,9 @@ class ChatWindow extends React.Component { return this.updateExistingCustomer(customerId, metadata); case 'notifications:display': return this.handleDisplayNotifications(payload); + + case 'papercups:send_bot_message': + return this.handleBotMessage(payload); case 'papercups:toggle': return this.handleToggleDisplay(payload); case 'papercups:plan': @@ -597,6 +600,10 @@ class ChatWindow extends React.Component { }; isCustomerMessage = (message: Message, customerId: string): boolean => { + if (message.type === 'bot') { + return false; + } + return ( message.customer_id === customerId || (message.sent_at && message.type === 'customer') @@ -679,6 +686,61 @@ class ChatWindow extends React.Component { } }; + handleBotMessage = async (details: any) => { + const body = details?.message ?? ''; + const signature = details?.singature ?? ''; + + const {customerId, conversationId, isSending} = this.state; + + if (isSending) { + return; + } + + const sentAt = new Date().toISOString(); + // TODO: figure out how this should work if `customerId` is null + const payload: Message = { + body, + customer_id: this.state.customerId, + type: 'bot', + sent_at: sentAt, + }; + + this.setState( + { + messages: [...this.state.messages, payload], + }, + () => this.scrollIntoView() + ); + + if (!customerId || !conversationId) { + await this.initializeNewConversation(customerId); + } + + // We should never hit this block, just adding to satisfy TypeScript + if (!this.channel) { + return; + } + + // // TODO: deprecate 'shout' event in favor of 'message:created' + this.channel.push('bot:shout', { + body, + type: 'reply', + // customer_id: this.state.customerId, + sent_at: sentAt, + // user_id: 1, + signature, + }); + + // TODO: should this only be emitted after the message is successfully sent? + this.emit('message:sent', { + body, + type: 'bot', + sent_at: sentAt, + customer_id: this.state.customerId, + conversation_id: this.state.conversationId, + }); + }; + handleSendMessage = async (message: Partial, email?: string) => { const {customerId, conversationId, isSending} = this.state; const {body, file_ids = []} = message;