diff --git a/src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts b/src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts index fe1c0301..8f5e8f2a 100644 --- a/src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts +++ b/src/api/integrations/chatbot/chatwoot/services/chatwoot.service.ts @@ -890,6 +890,13 @@ export class ChatwootService { sourceId?: string, quotedMsg?: MessageModel, ) { + if (sourceId) { + const messageAlreadySaved = await chatwootImport.getExistingSourceIds([sourceId]); + if (messageAlreadySaved.size > 0) { + this.logger.warn('Message already saved on chatwoot'); + return null; + } + } const data = new FormData(); if (content) { diff --git a/src/api/integrations/chatbot/chatwoot/utils/chatwoot-import-helper.ts b/src/api/integrations/chatbot/chatwoot/utils/chatwoot-import-helper.ts index 8f1ae580..50881465 100644 --- a/src/api/integrations/chatbot/chatwoot/utils/chatwoot-import-helper.ts +++ b/src/api/integrations/chatbot/chatwoot/utils/chatwoot-import-helper.ts @@ -169,16 +169,17 @@ class ChatwootImport { } } - private async getExistingSourceIds(sourceIds: string[]): Promise> { + public async getExistingSourceIds(sourceIds: string[]): Promise> { const existingSourceIdsSet = new Set(); if (sourceIds.length === 0) { return existingSourceIdsSet; } + const formattedSourceIds = sourceIds.map((sourceId) => `WAID:${sourceId.replace('WAID:', '')}`); // Make sure the sourceId is always formatted as WAID:1234567890 const query = 'SELECT source_id FROM messages WHERE source_id = ANY($1)'; const pgClient = postgresClient.getChatwootConnection(); - const result = await pgClient.query(query, [sourceIds]); + const result = await pgClient.query(query, [formattedSourceIds]); for (const row of result.rows) { existingSourceIdsSet.add(row.source_id);