fix(baileys): resolve incoming message events not working after reconnection

- Add cleanup logic in mount() to prevent memory leaks from multiple subscriptions

- Recreate messageSubject if it was completed during logout

- Remount messageProcessor in connectToWhatsapp() to ensure subscription is active after reconnection

This fixes the issue where incoming message events stop working after logout and reconnect, while outgoing message events continue to work normally.

The root cause was that onDestroy() calls complete() on the RxJS Subject, making it permanently closed. When reconnecting, the Subject would silently ignore all new messages.

The fix ensures that:

1. Old subscriptions are properly cleaned up before creating new ones

2. If the Subject is closed, a new one is created automatically

3. The messageProcessor is remounted on every connection to ensure active subscription
This commit is contained in:
Murilo Leal 2025-11-04 13:49:38 -03:00
parent 3454bec79f
commit 92626fa559
2 changed files with 21 additions and 0 deletions

View File

@ -19,6 +19,22 @@ export class BaileysMessageProcessor {
}>();
mount({ onMessageReceive }: MountProps) {
// Se já existe subscription, fazer cleanup primeiro
if (this.subscription && !this.subscription.closed) {
this.subscription.unsubscribe();
}
// Se o Subject foi completado, recriar
if (this.messageSubject.closed) {
this.processorLogs.warn('MessageSubject was closed, recreating...');
this.messageSubject = new Subject<{
messages: WAMessage[];
type: MessageUpsertType;
requestId?: string;
settings: any;
}>();
}
this.subscription = this.messageSubject
.pipe(
tap(({ messages }) => {

View File

@ -710,6 +710,11 @@ export class BaileysStartupService extends ChannelStartupService {
this.loadWebhook();
this.loadProxy();
// Remontar o messageProcessor para garantir que está funcionando após reconexão
this.messageProcessor.mount({
onMessageReceive: this.messageHandle['messages.upsert'].bind(this),
});
return await this.createClient(number);
} catch (error) {
this.logger.error(error);