Skip to content

Commit 7df26ea

Browse files
committed
Novas correções, e logs de erro com lID
1 parent 3fa9d10 commit 7df26ea

File tree

2 files changed

+89
-32
lines changed

2 files changed

+89
-32
lines changed

src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts

Lines changed: 88 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -422,6 +422,11 @@ export class BaileysStartupService extends ChannelStartupService {
422422
state: connection,
423423
statusReason: (lastDisconnect?.error as Boom)?.output?.statusCode ?? 200,
424424
};
425+
426+
this.logger.log(`Connection state changed to: ${connection}, instance: ${this.instance.id}`);
427+
if (lastDisconnect?.error) {
428+
this.logger.warn(`Connection error:`, lastDisconnect.error);
429+
}
425430
}
426431

427432
if (connection === 'close') {
@@ -1348,6 +1353,41 @@ export class BaileysStartupService extends ChannelStartupService {
13481353

13491354
this.sendDataWebhook(Events.MESSAGES_UPSERT, messageRaw);
13501355

1356+
// Schedule automatic status update for PENDING sent messages
1357+
if (messageRaw.key.fromMe && messageRaw.status === 'PENDING') {
1358+
setTimeout(async () => {
1359+
try {
1360+
const stillPendingMessage = await this.prismaRepository.message.findFirst({
1361+
where: {
1362+
instanceId: this.instanceId,
1363+
key: { path: ['id'], equals: messageRaw.key.id },
1364+
status: 'PENDING'
1365+
}
1366+
});
1367+
1368+
if (stillPendingMessage) {
1369+
this.logger.warn(`Forcing status update for PENDING message after timeout: ${messageRaw.key.id}`);
1370+
await this.prismaRepository.message.update({
1371+
where: { id: stillPendingMessage.id },
1372+
data: { status: 'SERVER_ACK' }
1373+
});
1374+
1375+
// Emit webhook for the status change
1376+
this.sendDataWebhook(Events.MESSAGES_UPDATE, {
1377+
messageId: stillPendingMessage.id,
1378+
keyId: messageRaw.key.id,
1379+
remoteJid: messageRaw.key.remoteJid,
1380+
fromMe: messageRaw.key.fromMe,
1381+
status: 'SERVER_ACK',
1382+
instanceId: this.instanceId
1383+
});
1384+
}
1385+
} catch (error) {
1386+
this.logger.error(`Error updating PENDING message status: ${error.message}`);
1387+
}
1388+
}, 30000); // 30 seconds timeout
1389+
}
1390+
13511391
await chatbotController.emit({
13521392
instance: { instanceName: this.instance.name, instanceId: this.instanceId },
13531393
remoteJid: messageRaw.key.remoteJid,
@@ -1493,33 +1533,34 @@ export class BaileysStartupService extends ChannelStartupService {
14931533

14941534
continue;
14951535
} else if (update.status !== undefined && status[update.status] !== findMessage.status) {
1496-
if (!key.fromMe && key.remoteJid) {
1497-
readChatToUpdate[key.remoteJid] = true;
1536+
const { remoteJid } = key;
1537+
const timestamp = findMessage.messageTimestamp;
1538+
const fromMe = key.fromMe.toString();
1539+
const normalizedRemoteJid = normalizeJid(remoteJid);
1540+
const messageKey = `${normalizedRemoteJid}_${timestamp}_${fromMe}`;
14981541

1499-
const { remoteJid } = key;
1500-
const timestamp = findMessage.messageTimestamp;
1501-
const fromMe = key.fromMe.toString();
1502-
const normalizedRemoteJid = normalizeJid(remoteJid);
1503-
const messageKey = `${normalizedRemoteJid}_${timestamp}_${fromMe}`;
1542+
const cachedTimestamp = await this.baileysCache.get(messageKey);
15041543

1505-
const cachedTimestamp = await this.baileysCache.get(messageKey);
1544+
if (!cachedTimestamp) {
1545+
// Handle read status for received messages
1546+
if (!key.fromMe && key.remoteJid && status[update.status] === status[4]) {
1547+
readChatToUpdate[key.remoteJid] = true;
1548+
this.logger.log(`Update as read in message.update ${remoteJid} - ${timestamp}`);
1549+
await this.updateMessagesReadedByTimestamp(remoteJid, timestamp);
1550+
await this.baileysCache.set(messageKey, true, 5 * 60);
1551+
}
15061552

1507-
if (!cachedTimestamp) {
1508-
if (status[update.status] === status[4]) {
1509-
this.logger.log(`Update as read in message.update ${remoteJid} - ${timestamp}`);
1510-
await this.updateMessagesReadedByTimestamp(remoteJid, timestamp);
1511-
await this.baileysCache.set(messageKey, true, 5 * 60);
1512-
}
1553+
// Update message status for all messages (sent and received)
1554+
await this.prismaRepository.message.update({
1555+
where: { id: findMessage.id },
1556+
data: { status: status[update.status] },
1557+
});
15131558

1514-
await this.prismaRepository.message.update({
1515-
where: { id: findMessage.id },
1516-
data: { status: status[update.status] },
1517-
});
1518-
} else {
1519-
this.logger.info(
1520-
`Update readed messages duplicated ignored in message.update [avoid deadlock]: ${messageKey}`,
1521-
);
1522-
}
1559+
this.logger.log(`Message status updated from ${findMessage.status} to ${status[update.status]} for message ${key.id}`);
1560+
} else {
1561+
this.logger.info(
1562+
`Update messages duplicated ignored in message.update [avoid deadlock]: ${messageKey}`,
1563+
);
15231564
}
15241565
}
15251566

@@ -1946,11 +1987,19 @@ export class BaileysStartupService extends ChannelStartupService {
19461987
}
19471988

19481989
if (message['conversation']) {
1949-
return await this.client.sendMessage(
1950-
sender,
1951-
{ text: message['conversation'], mentions, linkPreview: linkPreview } as unknown as AnyMessageContent,
1952-
option as unknown as MiscMessageGenerationOptions,
1953-
);
1990+
try {
1991+
this.logger.log(`Attempting to send conversation message to ${sender}: ${message['conversation']}`);
1992+
const result = await this.client.sendMessage(
1993+
sender,
1994+
{ text: message['conversation'], mentions, linkPreview: linkPreview } as unknown as AnyMessageContent,
1995+
option as unknown as MiscMessageGenerationOptions,
1996+
);
1997+
this.logger.log(`Message sent successfully with ID: ${result.key.id}`);
1998+
return result;
1999+
} catch (error) {
2000+
this.logger.error(`Failed to send message to ${sender}:`, error);
2001+
throw error;
2002+
}
19542003
}
19552004

19562005
if (!message['audio'] && !message['poll'] && !message['sticker'] && sender != 'status@broadcast') {
@@ -3340,7 +3389,6 @@ export class BaileysStartupService extends ChannelStartupService {
33403389
.filter((user) => user.exists)
33413390
.map((user) => ({
33423391
remoteJid: user.jid,
3343-
jidOptions: user.jid.replace('+', ''),
33443392
lid: user.lid,
33453393
})),
33463394
);
@@ -4234,8 +4282,17 @@ export class BaileysStartupService extends ChannelStartupService {
42344282
source: getDevice(message.key.id),
42354283
};
42364284

4237-
if (!messageRaw.status && message.key.fromMe === false) {
4238-
messageRaw.status = status[3]; // DELIVERED MESSAGE
4285+
// Log for debugging PENDING status
4286+
if (message.key.fromMe && (!message.status || message.status === 1)) {
4287+
this.logger.warn(`Message sent with PENDING status - ID: ${message.key.id}, Instance: ${this.instance.id}, Status: ${message.status}, RemoteJid: ${message.key.remoteJid}`);
4288+
}
4289+
4290+
if (!messageRaw.status) {
4291+
if (message.key.fromMe === false) {
4292+
messageRaw.status = status[3]; // DELIVERED MESSAGE for received messages
4293+
} else {
4294+
messageRaw.status = status[2]; // SERVER_ACK for sent messages without status
4295+
}
42394296
}
42404297

42414298
if (messageRaw.message.extendedTextMessage) {

src/utils/onWhatsappCache.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ function getAvailableNumbers(remoteJid: string) {
5454

5555
interface ISaveOnWhatsappCacheParams {
5656
remoteJid: string;
57-
lid?: string;
57+
lid?: string | null;
5858
}
5959

6060
export async function saveOnWhatsappCache(data: ISaveOnWhatsappCacheParams[]) {

0 commit comments

Comments
 (0)