Skip to content

Commit b071bdd

Browse files
committed
✨ chatwoot integration now replicates host outgoing msgs in cw #2934
1 parent 2fb2829 commit b071bdd

File tree

1 file changed

+59
-22
lines changed

1 file changed

+59
-22
lines changed

src/cli/integrations/chatwoot.ts

Lines changed: 59 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,9 @@ const convoReg = {
1414
//WID : chatwoot conversation ID
1515
"example@c.us": "1"
1616
}
17+
const ignoreMap = {
18+
"example_message_id": true
19+
}
1720

1821
export const chatwoot_webhook_check_event_name = "cli.integrations.chatwoot.check"
1922

@@ -71,7 +74,13 @@ export const chatwootMiddleware: (cliConfig: cliFlags, client: Client) => expres
7174
promises.push(client.sendText(to, content));
7275
}
7376
}
74-
return await Promise.all(promises)
77+
const outgoingMessageIds = await Promise.all(promises)
78+
log.info(`Outgoing message IDs: ${JSON.stringify(outgoingMessageIds)}`)
79+
/**
80+
* Add these message IDs to the ignore map
81+
*/
82+
outgoingMessageIds.map(id=>ignoreMap[`${id}`]=true)
83+
return outgoingMessageIds
7584
}
7685
try {
7786
const processAndSendResult = await processMesssage();
@@ -235,7 +244,13 @@ export const setupChatwootOutgoingMessageHandler: (cliConfig: cliFlags, client:
235244
const { data } = await cwReq('get',`contacts/${contactReg[number]}/conversations`);
236245
const allContactConversations = data.payload.filter(c=>c.inbox_id===inboxId).sort((a,b)=>a.id-b.id)
237246
const [opened, notOpen] = [allContactConversations.filter(c=>c.status==='open'), allContactConversations.filter(c=>c.status!='open')]
238-
return opened[0] || notOpen[0];
247+
const hasOpenConvo = opened[0] ? true : false;
248+
const resolvedConversation = opened[0] || notOpen[0];
249+
if(!hasOpenConvo) {
250+
//reopen convo
251+
await openConversation(resolvedConversation.id)
252+
}
253+
return resolvedConversation;
239254
} catch (error) {
240255
return;
241256
}
@@ -267,11 +282,22 @@ export const setupChatwootOutgoingMessageHandler: (cliConfig: cliFlags, client:
267282
}
268283
}
269284

270-
const sendConversationMessage = async (content, contactId, message) => {
285+
const openConversation = async (conversationId, status = "opened") => {
286+
try {
287+
const { data } = await cwReq( 'post',`conversations/${conversationId}/messages`, {
288+
status
289+
});
290+
return data;
291+
} catch (error) {
292+
return;
293+
}
294+
}
295+
296+
const sendConversationMessage = async (content, contactId, message: Message) => {
271297
try {
272298
const { data } = await cwReq( 'post',`conversations/${convoReg[contactId]}/messages`, {
273299
content,
274-
"message_type": 0,
300+
"message_type": message.fromMe ? "outgoing" : "incoming",
275301
"private": false
276302
});
277303
return data;
@@ -299,37 +325,31 @@ export const setupChatwootOutgoingMessageHandler: (cliConfig: cliFlags, client:
299325
}
300326
}
301327

302-
303-
304-
// const inboxId = s.match(/conversations\/\d*/g) && s.match(/conversations\/\d*/g)[0].replace('conversations/','')
305-
/**
306-
* Update the chatwoot contact and conversation registries
307-
*/
308-
const setOnMessageProm = client.onMessage(async message => {
309-
if (message.from.includes('g')) {
328+
const processWAMessage = async (message : Message) => {
329+
if (message.chatId.includes('g')) {
310330
//chatwoot integration does not support group chats
311331
return;
312332
}
313333
/**
314334
* Does the contact exist in chatwoot?
315335
*/
316-
if (!contactReg[message.from]) {
317-
const contact = await searchContact(message.from)
336+
if (!contactReg[message.chatId]) {
337+
const contact = await searchContact(message.chatId)
318338
if (contact) {
319-
contactReg[message.from] = contact.id
339+
contactReg[message.chatId] = contact.id
320340
} else {
321341
//create the contact
322-
contactReg[message.from] = (await createContact(message.sender)).id
342+
contactReg[message.chatId] = (await createContact(message.sender)).id
323343
}
324344
}
325345

326-
if (!convoReg[message.from]) {
327-
const conversation = await getContactConversation(message.from);
346+
if (!convoReg[message.chatId]) {
347+
const conversation = await getContactConversation(message.chatId);
328348
if (conversation) {
329-
convoReg[message.from] = conversation.id
349+
convoReg[message.chatId] = conversation.id
330350
} else {
331351
//create the conversation
332-
convoReg[message.from] = (await createConversation(contactReg[message.from])).id
352+
convoReg[message.chatId] = (await createConversation(contactReg[message.chatId])).id
333353
}
334354
}
335355
/**
@@ -360,10 +380,27 @@ export const setupChatwootOutgoingMessageHandler: (cliConfig: cliFlags, client:
360380
text = message?.ctwaContext?.sourceUrl ? `${message.body}\n\n${message.ctwaContext.sourceUrl}` : message.body || "__UNHANDLED__";
361381
break;
362382
}
363-
if(hasAttachments) await sendAttachmentMessage(text, message.from, message)
364-
else await sendConversationMessage(text, message.from, message)
383+
if(hasAttachments) await sendAttachmentMessage(text, message.chatId, message)
384+
else await sendConversationMessage(text, message.chatId, message)
385+
}
386+
// const inboxId = s.match(/conversations\/\d*/g) && s.match(/conversations\/\d*/g)[0].replace('conversations/','')
387+
/**
388+
* Update the chatwoot contact and conversation registries
389+
*/
390+
const setOnMessageProm = client.onMessage(processWAMessage)
391+
const setOnAckProm = client.onAck(async ackEvent =>{
392+
if(ackEvent.ack == 1 && ackEvent.isNewMsg && ackEvent.self==="in") {
393+
if(ignoreMap[ackEvent.id]) {
394+
delete ignoreMap[ackEvent.id]
395+
return;
396+
}
397+
const _message = await client.getMessageById(ackEvent.id)
398+
return await processWAMessage(_message)
399+
}
400+
return;
365401
})
366402
proms.push(setOnMessageProm)
403+
proms.push(setOnAckProm)
367404
await Promise.all(proms);
368405
return;
369406
}

0 commit comments

Comments
 (0)