Baileys icon indicating copy to clipboard operation
Baileys copied to clipboard

message not showing when send to new number first time[BUG]

Open sahilbrandwala opened this issue 2 years ago • 110 comments

When i send message to new number first time messages not showing ...Show only "Waiting for this message. This may take a while" screenshot attatched WhatsApp Image 2022-05-17 at 10 19 19 AM

please help me

sahilbrandwala avatar May 17 '22 05:05 sahilbrandwala

I have the same problem.

jeffersonveloso avatar May 17 '22 14:05 jeffersonveloso

me too

andrody avatar May 17 '22 16:05 andrody

anyone get issue?

sahilbrandwala avatar May 17 '22 17:05 sahilbrandwala

here too

IanosJunior avatar May 17 '22 19:05 IanosJunior

Update the app, it solved for me.

ngadimin51 avatar May 18 '22 01:05 ngadimin51

Update the app, it solved for me.

What version are you using ?

jeffersonveloso avatar May 18 '22 01:05 jeffersonveloso

It's been more than a week, I am getting this issue and have no fix yet.

rajuaryan21 avatar May 18 '22 01:05 rajuaryan21

Update the app, it solved for me.

You mean the sender or receiver? who needs to update the app to avoid this issue?

rajuaryan21 avatar May 18 '22 01:05 rajuaryan21

When i send message to new number first time messages not showing ...Show only "Waiting for this message. This may take a while" screenshot attatched WhatsApp Image 2022-05-17 at 10 19 19 AM

please help me

you should implement getMessage on making socket * fetch a message from your store * implement this so that messages failed to send (solves the "this message can take a while" issue) can be retried getMessage: (key: proto.IMessageKey) => Promise<proto.IMessage | undefined>

example : implement a store at temporaryStore file (I created this file myself)

let messages = []
function deleteMessage(messageID) {
    delete messages[messageID]
}
function saveMessage(messageID, txt) {
    messages[messageID] = txt
}
function getMessage(messageID) {
    return messages[messageID]

}
function clearMessages() {
    messages = []
}
setInterval(clearMessages, 120000)
export default {
    getMessage,
    saveMessage,
    deleteMessage
}


then at making socket :

const retryMessageHandler = async message => {
    console.log("retry for send message !!!!!")
    let text = temporaryStore.getMessage(message.id)
    temporaryStore.deleteMessage(message.id)
    return {
        conversation: text
    }
}
sock = makeWASocket({
        browser: config.getAgent(process.env.AGENT_NUMBER),
        version,
        logger,
        printQRInTerminal: true,
        auth: state,
        msgRetryCounterMap,
        // implement to handle retries
        getMessage: retryMessageHandler  // at this line we use retryMessageHandler
 })


and finally after sending a message , save it at temporaryStore

let whatsappRes = await sock.sendMessage(jid, {text: text})
temporaryStore.saveMessage(whatsappRes.key.id, text)

       
       
       
       

mrhb6006 avatar May 18 '22 05:05 mrhb6006

When i send message to new number first time messages not showing ...Show only "Waiting for this message. This may take a while" screenshot attatched WhatsApp Image 2022-05-17 at 10 19 19 AM please help me you should implement getMessage on making socket

  • fetch a message from your store
  • implement this so that messages failed to send (solves the "this message can take a while" issue) can be retried getMessage: (key: proto.IMessageKey) => Promise<proto.IMessage | undefined>

example : implement a store at temporaryStore file (I created this file myself)

function deleteMessage(messageID) {
    delete messages[messageID]
}
function saveMessage(messageID, txt) {
    messages[messageID] = txt
}
function getMessage(messageID) {
    return messages[messageID]

}
function clearMessages() {
    messages = []
}
setInterval(clearMessages, 120000)
export default {
    getMessage,
    saveMessage,
    deleteMessage
}


then at making socket :

const retryMessageHandler = async message => {
    console.log("retry for send message !!!!!")
    let text = temporaryStore.getMessage(message.id)
    temporaryStore.deleteMessage(message.id)
    return {
        conversation: text
    }
}
sock = makeWASocket({
        browser: config.getAgent(process.env.AGENT_NUMBER),
        version,
        logger,
        printQRInTerminal: true,
        auth: state,
        msgRetryCounterMap,
        // implement to handle retries
        getMessage: retryMessageHandler  // at this line we use retryMessageHandler
 })


and finally after sending a message , save it at temporaryStore

let whatsappRes = await sock.sendMessage(jid, {text: text})
temporaryStore.saveMessage(whatsappRes.key.id, text)

       
       
       
       

Thank you so much, I am gonna implement this now.

adarsh-chakraborty avatar May 18 '22 07:05 adarsh-chakraborty

Update the app, it solved for me.

You mean the sender or receiver? who needs to update the app to avoid this issue?

On my case updating receiver app device is works.

ngadimin51 avatar May 18 '22 09:05 ngadimin51

When i send message to new number first time messages not showing ...Show only "Waiting for this message. This may take a while" screenshot attatched WhatsApp Image 2022-05-17 at 10 19 19 AM please help me

you should implement getMessage on making socket * fetch a message from your store * implement this so that messages failed to send (solves the "this message can take a while" issue) can be retried getMessage: (key: proto.IMessageKey) => Promise<proto.IMessage | undefined>

example : implement a store at temporaryStore file (I created this file myself)

let messages = []
function deleteMessage(messageID) {
    delete messages[messageID]
}
function saveMessage(messageID, txt) {
    messages[messageID] = txt
}
function getMessage(messageID) {
    return messages[messageID]

}
function clearMessages() {
    messages = []
}
setInterval(clearMessages, 120000)
export default {
    getMessage,
    saveMessage,
    deleteMessage
}


then at making socket :

const retryMessageHandler = async message => {
    console.log("retry for send message !!!!!")
    let text = temporaryStore.getMessage(message.id)
    temporaryStore.deleteMessage(message.id)
    return {
        conversation: text
    }
}
sock = makeWASocket({
        browser: config.getAgent(process.env.AGENT_NUMBER),
        version,
        logger,
        printQRInTerminal: true,
        auth: state,
        msgRetryCounterMap,
        // implement to handle retries
        getMessage: retryMessageHandler  // at this line we use retryMessageHandler
 })


and finally after sending a message , save it at temporaryStore

let whatsappRes = await sock.sendMessage(jid, {text: text})
temporaryStore.saveMessage(whatsappRes.key.id, text)

       
       
       
       

Bro thanks to try help us, is possible use this solution for send media url and buttons ?

jeffersonveloso avatar May 18 '22 16:05 jeffersonveloso

When i send message to new number first time messages not showing ...Show only "Waiting for this message. This may take a while" screenshot attatched WhatsApp Image 2022-05-17 at 10 19 19 AM please help me

you should implement getMessage on making socket * fetch a message from your store * implement this so that messages failed to send (solves the "this message can take a while" issue) can be retried getMessage: (key: proto.IMessageKey) => Promise<proto.IMessage | undefined>

example : implement a store at temporaryStore file (I created this file myself)

let messages = []
function deleteMessage(messageID) {
    delete messages[messageID]
}
function saveMessage(messageID, txt) {
    messages[messageID] = txt
}
function getMessage(messageID) {
    return messages[messageID]

}
function clearMessages() {
    messages = []
}
setInterval(clearMessages, 120000)
export default {
    getMessage,
    saveMessage,
    deleteMessage
}


then at making socket :

const retryMessageHandler = async message => {
    console.log("retry for send message !!!!!")
    let text = temporaryStore.getMessage(message.id)
    temporaryStore.deleteMessage(message.id)
    return {
        conversation: text
    }
}
sock = makeWASocket({
        browser: config.getAgent(process.env.AGENT_NUMBER),
        version,
        logger,
        printQRInTerminal: true,
        auth: state,
        msgRetryCounterMap,
        // implement to handle retries
        getMessage: retryMessageHandler  // at this line we use retryMessageHandler
 })


and finally after sending a message , save it at temporaryStore

let whatsappRes = await sock.sendMessage(jid, {text: text})
temporaryStore.saveMessage(whatsappRes.key.id, text)

       
       
       
       

I tested this solution with some numbers and at first it worked for me. I created a more generic function to support sending other messages and not just texts. I tested it with about 10 numbers and it seems to have solved the problem at hand, this may not be the best solution but if anyone else can test it to validate its effectiveness it would be great.

    function saveMessage(messageID, message: Record<string, unknown>): void {
       messages[messageID] = message;
    }

    const response = await sock?.sendMessage(
      jid,
      buttonMessage
    );
   
    temporaryStore.saveMessage(response?.key?.id, {
      buttonsMessage: response?.message?.buttonsMessage,
    });


  retryMessageHandler = async (
    message
  ): Promise<proto.IMessage | undefined> => {
    const messageContent = temporaryStore.getMessage(message.id);

    console.log("retry for send message !!!!!", messageContent);

    temporaryStore.deleteMessage(message.id);

    return messageContent;
  };

jeffersonveloso avatar May 19 '22 01:05 jeffersonveloso

When i send message to new number first time messages not showing ...Show only "Waiting for this message. This may take a while" screenshot attatched WhatsApp Image 2022-05-17 at 10 19 19 AM please help me

you should implement getMessage on making socket * fetch a message from your store * implement this so that messages failed to send (solves the "this message can take a while" issue) can be retried getMessage: (key: proto.IMessageKey) => Promise<proto.IMessage | undefined> example : implement a store at temporaryStore file (I created this file myself)

let messages = []
function deleteMessage(messageID) {
    delete messages[messageID]
}
function saveMessage(messageID, txt) {
    messages[messageID] = txt
}
function getMessage(messageID) {
    return messages[messageID]

}
function clearMessages() {
    messages = []
}
setInterval(clearMessages, 120000)
export default {
    getMessage,
    saveMessage,
    deleteMessage
}


then at making socket :

const retryMessageHandler = async message => {
    console.log("retry for send message !!!!!")
    let text = temporaryStore.getMessage(message.id)
    temporaryStore.deleteMessage(message.id)
    return {
        conversation: text
    }
}
sock = makeWASocket({
        browser: config.getAgent(process.env.AGENT_NUMBER),
        version,
        logger,
        printQRInTerminal: true,
        auth: state,
        msgRetryCounterMap,
        // implement to handle retries
        getMessage: retryMessageHandler  // at this line we use retryMessageHandler
 })


and finally after sending a message , save it at temporaryStore

let whatsappRes = await sock.sendMessage(jid, {text: text})
temporaryStore.saveMessage(whatsappRes.key.id, text)

       
       
       
       

Bro thanks to try help us, is possible use this solution for send media url and buttons ?

yes just save the whole message structure instead of message text at temporaryStore and return that at the retryMessageHandler

mrhb6006 avatar May 19 '22 04:05 mrhb6006

@adiwajshing please help to solve this issue

sahilbrandwala avatar May 19 '22 12:05 sahilbrandwala

You all can use

import { proto } from "@adiwajshing/baileys";
export class MessageRetryHandler {
  public messagesMap: Record<string, proto.IMessage>;

  constructor() {
    this.messagesMap = {};
  }

  addMessage = async (message: proto.IWebMessageInfo) => {
    const id = message.key.id ?? "";

    console.log(this);

    this.messagesMap[id] = this.cleanMessage(message);

    return message;
  };

  getMessage = (msgKey: string): proto.IMessage => {
    return this.messagesMap[msgKey];
  };

  removeMessage = (msgKey: string) => {
    delete this.messagesMap[msgKey];
  };

  getMessageKeys = (): string[] => {
    return Object.keys(this.messagesMap);
  };

  cleanMessage = (message: proto.IWebMessageInfo): proto.IMessage => {
    const msg = message.message ?? {};
    return msg;
  };

  messageRetryHandler = async (message: proto.IMessageKey) => {
    const msg = this.getMessage(message.id ?? "");
    // Remove msg from map
    this.removeMessage(message.id ?? "");
    return msg;
  };
}

Then implement it as

const handler = new MessageRetryHandler();
const socketConfig: Partial<SocketConfig> = {
  printQRInTerminal: false,
  logger: PinoLogger({
    level: "silent",
  }),
  getMessage: handler.messageRetryHandler,
};

And when sending messages,

const sentMessage = await socket.sendMessage(id, {
    text: text,
  })
  .then(handler.addMessage);

This will handle all types of messages automatically, just remember to add the .then(handler.addMessage); after the message.

Manjit2003 avatar May 20 '22 07:05 Manjit2003

@Manjit2003 thanks man...

sahilbrandwala avatar May 20 '22 07:05 sahilbrandwala

image

messages show on phone but still show pending on desktop login

@Manjit2003

sahilbrandwala avatar May 20 '22 08:05 sahilbrandwala

That's the WhatsApp Web bug. Is it usually working on the phone now?

Manjit2003 avatar May 20 '22 08:05 Manjit2003

yes but whatsapp web still showing waiting for message....we use other company api its working well please look also into this

sahilbrandwala avatar May 20 '22 08:05 sahilbrandwala

Okay, i will check it

Manjit2003 avatar May 20 '22 08:05 Manjit2003

@Manjit2003 @Denver1997 I am not able to use this code in the example.ts file. I am not sure where exactly i need to add this code. Can you please add this code in the example.ts and paste the full code here.

picblog229 avatar May 20 '22 11:05 picblog229

@picblog229 Here you go,

import { MessageRetryHandler } from "./retryHandler";
import { Boom } from "@hapi/boom";
import { useSingleFileAuthState } from "./authState";
import makeWASocket, {
  AnyMessageContent,
  DisconnectReason,
  fetchLatestBaileysVersion,
  makeInMemoryStore,
} from "@adiwajshing/baileys";
import pino from "pino";

const logger = pino();
logger.level = "trace";

const useStore = !process.argv.includes("--no-store");
const doReplies = !process.argv.includes("--no-reply");

// external map to store retry counts of messages when decryption/encryption fails
// keep this out of the socket itself, so as to prevent a message decryption/encryption loop across socket restarts
const msgRetryCounterMap: MessageRetryMap = {};

const handler = new MessageRetryHandler();

// the store maintains the data of the WA connection in memory
// can be written out to a file & read from it
const store = useStore ? makeInMemoryStore({ logger }) : undefined;
store?.readFromFile("./baileys_store_multi.json");
// save every 10s
setInterval(() => {
  store?.writeToFile("./baileys_store_multi.json");
}, 10_000);

const { state, saveState } = useSingleFileAuthState("./auth_info_multi.json");

// start a connection
const startSock = async () => {
  // fetch latest version of WA Web
  const { version, isLatest } = await fetchLatestBaileysVersion();
  console.log(`using WA v${version.join(".")}, isLatest: ${isLatest}`);

  const sock = makeWASocket({
    version,
    logger,
    printQRInTerminal: true,
    auth: state,
    msgRetryCounterMap,
    // implement to handle retries
    getMessage: handler.messageRetryHandler,
  });

  store?.bind(sock.ev);

  const sendMessageWTyping = async (msg: AnyMessageContent, jid: string) => {
    await sock.presenceSubscribe(jid);
    await delay(500);

    await sock.sendPresenceUpdate("composing", jid);
    await delay(2000);

    await sock.sendPresenceUpdate("paused", jid);

    await sock.sendMessage(jid, msg).then(handler.addMessage);
  };

  sock.ev.on("call", (item) => console.log("recv call event", item));
  sock.ev.on("chats.set", (item) =>
    console.log(`recv ${item.chats.length} chats (is latest: ${item.isLatest})`)
  );
  sock.ev.on("messages.set", (item) =>
    console.log(
      `recv ${item.messages.length} messages (is latest: ${item.isLatest})`
    )
  );
  sock.ev.on("contacts.set", (item) =>
    console.log(`recv ${item.contacts.length} contacts`)
  );

  sock.ev.on("messages.upsert", async (m) => {
    console.log(JSON.stringify(m, undefined, 2));

    const msg = m.messages[0];
    if (!msg.key.fromMe && m.type === "notify" && doReplies) {
      console.log("replying to", m.messages[0].key.remoteJid);
      await sock!.sendReadReceipt(msg.key.remoteJid, msg.key.participant, [
        msg.key.id,
      ]);
      await sendMessageWTyping({ text: "Hello there!" }, msg.key.remoteJid);
    }
  });

  sock.ev.on("messages.update", (m) => console.log(m));
  sock.ev.on("message-receipt.update", (m) => console.log(m));
  sock.ev.on("presence.update", (m) => console.log(m));
  sock.ev.on("chats.update", (m) => console.log(m));
  sock.ev.on("contacts.upsert", (m) => console.log(m));

  sock.ev.on("connection.update", (update) => {
    const { connection, lastDisconnect } = update;
    if (connection === "close") {
      // reconnect if not logged out
      if (
        (lastDisconnect?.error as Boom)?.output?.statusCode !==
        DisconnectReason.loggedOut
      ) {
        startSock();
      } else {
        console.log("Connection closed. You are logged out.");
      }
    }

    console.log("connection update", update);
  });
  // listen for when the auth credentials is updated
  sock.ev.on("creds.update", saveState);

  return sock;
};

startSock();

Manjit2003 avatar May 20 '22 11:05 Manjit2003

This doesn't work, does anyone have any idea why? I tried @Manjit2003 code and I get the same message Waiting for this message....

WevertonCouto avatar May 20 '22 18:05 WevertonCouto

image

messages show on phone but still show pending on desktop login

@Manjit2003

Reinstall desktop whatsapp app

ngadimin51 avatar May 21 '22 00:05 ngadimin51

@picblog229 Here you go,

import { MessageRetryHandler } from "./retryHandler";
import { Boom } from "@hapi/boom";
import { useSingleFileAuthState } from "./authState";
import makeWASocket, {
  AnyMessageContent,
  DisconnectReason,
  fetchLatestBaileysVersion,
  makeInMemoryStore,
} from "@adiwajshing/baileys";
import pino from "pino";

const logger = pino();
logger.level = "trace";

const useStore = !process.argv.includes("--no-store");
const doReplies = !process.argv.includes("--no-reply");

// external map to store retry counts of messages when decryption/encryption fails
// keep this out of the socket itself, so as to prevent a message decryption/encryption loop across socket restarts
const msgRetryCounterMap: MessageRetryMap = {};

const handler = new MessageRetryHandler();

// the store maintains the data of the WA connection in memory
// can be written out to a file & read from it
const store = useStore ? makeInMemoryStore({ logger }) : undefined;
store?.readFromFile("./baileys_store_multi.json");
// save every 10s
setInterval(() => {
  store?.writeToFile("./baileys_store_multi.json");
}, 10_000);

const { state, saveState } = useSingleFileAuthState("./auth_info_multi.json");

// start a connection
const startSock = async () => {
  // fetch latest version of WA Web
  const { version, isLatest } = await fetchLatestBaileysVersion();
  console.log(`using WA v${version.join(".")}, isLatest: ${isLatest}`);

  const sock = makeWASocket({
    version,
    logger,
    printQRInTerminal: true,
    auth: state,
    msgRetryCounterMap,
    // implement to handle retries
    getMessage: handler.messageRetryHandler,
  });

  store?.bind(sock.ev);

  const sendMessageWTyping = async (msg: AnyMessageContent, jid: string) => {
    await sock.presenceSubscribe(jid);
    await delay(500);

    await sock.sendPresenceUpdate("composing", jid);
    await delay(2000);

    await sock.sendPresenceUpdate("paused", jid);

    await sock.sendMessage(jid, msg).then(handler.addMessage);
  };

  sock.ev.on("call", (item) => console.log("recv call event", item));
  sock.ev.on("chats.set", (item) =>
    console.log(`recv ${item.chats.length} chats (is latest: ${item.isLatest})`)
  );
  sock.ev.on("messages.set", (item) =>
    console.log(
      `recv ${item.messages.length} messages (is latest: ${item.isLatest})`
    )
  );
  sock.ev.on("contacts.set", (item) =>
    console.log(`recv ${item.contacts.length} contacts`)
  );

  sock.ev.on("messages.upsert", async (m) => {
    console.log(JSON.stringify(m, undefined, 2));

    const msg = m.messages[0];
    if (!msg.key.fromMe && m.type === "notify" && doReplies) {
      console.log("replying to", m.messages[0].key.remoteJid);
      await sock!.sendReadReceipt(msg.key.remoteJid, msg.key.participant, [
        msg.key.id,
      ]);
      await sendMessageWTyping({ text: "Hello there!" }, msg.key.remoteJid);
    }
  });

  sock.ev.on("messages.update", (m) => console.log(m));
  sock.ev.on("message-receipt.update", (m) => console.log(m));
  sock.ev.on("presence.update", (m) => console.log(m));
  sock.ev.on("chats.update", (m) => console.log(m));
  sock.ev.on("contacts.upsert", (m) => console.log(m));

  sock.ev.on("connection.update", (update) => {
    const { connection, lastDisconnect } = update;
    if (connection === "close") {
      // reconnect if not logged out
      if (
        (lastDisconnect?.error as Boom)?.output?.statusCode !==
        DisconnectReason.loggedOut
      ) {
        startSock();
      } else {
        console.log("Connection closed. You are logged out.");
      }
    }

    console.log("connection update", update);
  });
  // listen for when the auth credentials is updated
  sock.ev.on("creds.update", saveState);

  return sock;
};

startSock();

Using this example code the problem appeared: "waiting for this message. this may take a while".

image

Analyzing the logs this appears several times:

{
    "level": 30,
    "time": 1653081636518,
    "pid": 11,
    "hostname": "7141cc37f605",
    "attrs": {
        "from": "[email protected]",
        "type": "retry",
        "id": "BAE52F42979AB40B",
        "participant": "[email protected]",
        "t": "1653081626"
    },
    "key": {
        "remoteJid": "[email protected]",
        "id": "",
        "fromMe": true,
        "participant": "[email protected]"
    },
    "msg": "will not send message again, as sent too many times"
}

To improve error identification, I added this code snippet in function getMessage:

const sock = makeWASocket({
    version,
    logger,
    printQRInTerminal: true,
    auth: state,
    msgRetryCounterMap,
    // implement to handle retries
    getMessage: async (key) => {
        const msg = await handler.messageRetryHandler(key);
        console.log(`Get message ${JSON.stringify(key)} for resend, ${msg ? 'found' : 'not_found'}`);
        return msg;
    }
  });

Resulting in

"Get message {"remoteJid":"[email protected]","id":"BAE52F42979AB40B","fromMe":true,"participant":"[email protected]"} for resend, found"

What would that error ("will not send message again, as sent too many times") be? is it possible to solve?

LeonardoBein avatar May 21 '22 03:05 LeonardoBein

@Manjit2003 thanks for posting the code. But I am still getting following compile error:. Can you please have a look.

TSError: ⨯ Unable to compile TypeScript: Example/example.ts:55:41 - error TS2345: Argument of type '(message: proto.IWebMessageInfo) => Promise<proto.IWebMessageInfo>' is not assignable to parameter of type '(value: WebMessageInfo) => IWebMessageInfo | PromiseLike<IWebMessageInfo>'. Types of parameters 'message' and 'value' are incompatible. Type 'WebMessageInfo' is not assignable to type 'IWebMessageInfo'. Types of property 'messageStubType' are incompatible. Type 'import("/home/emr2043/asp_w/w/WAProto/index").proto.WebMessageInfo.WebMessageInfoStubType' is not assignable to type 'import("/home/emr2043/asp_w/w/node_modules/@adiwajshing/baileys/WAProto/index").proto.WebMessageInfo.WebMessageInfoStubType'. Property 'COMMUNITY_UNLINK_PARENT_GROUP' is missing in type 'import("/home/emr2043/asp_w/w/node_modules/@adiwajshing/baileys/WAProto/index").proto.WebMessageInfo.WebMessageInfoStubType'.

55 await sock.sendMessage(jid, msg).then(handler.addMessage);

picblog229 avatar May 21 '22 07:05 picblog229

@picblog229 can you please send me the code....

Manjit2003 avatar May 21 '22 14:05 Manjit2003

@LeonardoBein try debugging with this code snippet,

const sock = makeWASocket({
    version,
    logger,
    printQRInTerminal: true,
    auth: state,
    msgRetryCounterMap,
    // implement to handle retries
    getMessage: async (key) => {
        const msg = await handler.getMessage(message.id ?? "");
        console.log(`Get message ${JSON.stringify(key)} for resend, ${msg ? 'found' : 'not_found'}`);
    }
  });

Manjit2003 avatar May 21 '22 14:05 Manjit2003

@picblog229 Here you go,

import { MessageRetryHandler } from "./retryHandler";
import { Boom } from "@hapi/boom";
import { useSingleFileAuthState } from "./authState";
import makeWASocket, {
  AnyMessageContent,
  DisconnectReason,
  fetchLatestBaileysVersion,
  makeInMemoryStore,
} from "@adiwajshing/baileys";
import pino from "pino";

const logger = pino();
logger.level = "trace";

const useStore = !process.argv.includes("--no-store");
const doReplies = !process.argv.includes("--no-reply");

// external map to store retry counts of messages when decryption/encryption fails
// keep this out of the socket itself, so as to prevent a message decryption/encryption loop across socket restarts
const msgRetryCounterMap: MessageRetryMap = {};

const handler = new MessageRetryHandler();

// the store maintains the data of the WA connection in memory
// can be written out to a file & read from it
const store = useStore ? makeInMemoryStore({ logger }) : undefined;
store?.readFromFile("./baileys_store_multi.json");
// save every 10s
setInterval(() => {
  store?.writeToFile("./baileys_store_multi.json");
}, 10_000);

const { state, saveState } = useSingleFileAuthState("./auth_info_multi.json");

// start a connection
const startSock = async () => {
  // fetch latest version of WA Web
  const { version, isLatest } = await fetchLatestBaileysVersion();
  console.log(`using WA v${version.join(".")}, isLatest: ${isLatest}`);

  const sock = makeWASocket({
    version,
    logger,
    printQRInTerminal: true,
    auth: state,
    msgRetryCounterMap,
    // implement to handle retries
    getMessage: handler.messageRetryHandler,
  });

  store?.bind(sock.ev);

  const sendMessageWTyping = async (msg: AnyMessageContent, jid: string) => {
    await sock.presenceSubscribe(jid);
    await delay(500);

    await sock.sendPresenceUpdate("composing", jid);
    await delay(2000);

    await sock.sendPresenceUpdate("paused", jid);

    await sock.sendMessage(jid, msg).then(handler.addMessage);
  };

  sock.ev.on("call", (item) => console.log("recv call event", item));
  sock.ev.on("chats.set", (item) =>
    console.log(`recv ${item.chats.length} chats (is latest: ${item.isLatest})`)
  );
  sock.ev.on("messages.set", (item) =>
    console.log(
      `recv ${item.messages.length} messages (is latest: ${item.isLatest})`
    )
  );
  sock.ev.on("contacts.set", (item) =>
    console.log(`recv ${item.contacts.length} contacts`)
  );

  sock.ev.on("messages.upsert", async (m) => {
    console.log(JSON.stringify(m, undefined, 2));

    const msg = m.messages[0];
    if (!msg.key.fromMe && m.type === "notify" && doReplies) {
      console.log("replying to", m.messages[0].key.remoteJid);
      await sock!.sendReadReceipt(msg.key.remoteJid, msg.key.participant, [
        msg.key.id,
      ]);
      await sendMessageWTyping({ text: "Hello there!" }, msg.key.remoteJid);
    }
  });

  sock.ev.on("messages.update", (m) => console.log(m));
  sock.ev.on("message-receipt.update", (m) => console.log(m));
  sock.ev.on("presence.update", (m) => console.log(m));
  sock.ev.on("chats.update", (m) => console.log(m));
  sock.ev.on("contacts.upsert", (m) => console.log(m));

  sock.ev.on("connection.update", (update) => {
    const { connection, lastDisconnect } = update;
    if (connection === "close") {
      // reconnect if not logged out
      if (
        (lastDisconnect?.error as Boom)?.output?.statusCode !==
        DisconnectReason.loggedOut
      ) {
        startSock();
      } else {
        console.log("Connection closed. You are logged out.");
      }
    }

    console.log("connection update", update);
  });
  // listen for when the auth credentials is updated
  sock.ev.on("creds.update", saveState);

  return sock;
};

startSock();

this work for me, but generate large files, how can delete?, i trying add setinterval every 6 hours but this delete and recreate same size file

store:function(h){
     
     if(!stores[h]){
         stores[h] = makeInMemoryStore({ logger });
         stores[h].readFromFile( __dirname + '/sessions/' + h + '_store.json');
         setInterval(() => {
         	stores[h].writeToFile( __dirname + '/sessions/' + h + '_store.json')
         }, 10000)
         
         setInterval(()=>{
            if (fs.existsSync(__dirname + '/sessions/' + h + '_store.json')) {
                 fs.unlinkSync(__dirname + '/sessions/' + h + '_store.json')
             } 
         }, 1000*60*60*6)
         
         return stores[h];
     }else{
         return stores[h];
     }
     
 }

enoksaju avatar May 22 '22 03:05 enoksaju

@LeonardoBein try debugging with this code snippet,

const sock = makeWASocket({
    version,
    logger,
    printQRInTerminal: true,
    auth: state,
    msgRetryCounterMap,
    // implement to handle retries
    getMessage: async (key) => {
        const msg = await handler.getMessage(message.id ?? "");
        console.log(`Get message ${JSON.stringify(key)} for resend, ${msg ? 'found' : 'not_found'}`);
    }
  });

Did not solve. Continue with the same error.

LeonardoBein avatar May 26 '22 20:05 LeonardoBein

@adiwajshing please also look into this bug... waiting for solution from last 20-25days

sahilbrandwala avatar May 27 '22 06:05 sahilbrandwala

Updated to latest version and i add the message memory store and it works for me.

marutichintan avatar May 27 '22 13:05 marutichintan

Updated to latest version and i add the message memory store and it works for me.

Can you show a example for us? I did all of sugestions and nothing works for me

WevertonCouto avatar May 27 '22 13:05 WevertonCouto

You all can use

import { proto } from "@adiwajshing/baileys";
export class MessageRetryHandler {
  public messagesMap: Record<string, proto.IMessage>;

  constructor() {
    this.messagesMap = {};
  }

  addMessage = async (message: proto.IWebMessageInfo) => {
    const id = message.key.id ?? "";

    console.log(this);

    this.messagesMap[id] = this.cleanMessage(message);

    return message;
  };

  getMessage = (msgKey: string): proto.IMessage => {
    return this.messagesMap[msgKey];
  };

  removeMessage = (msgKey: string) => {
    delete this.messagesMap[msgKey];
  };

  getMessageKeys = (): string[] => {
    return Object.keys(this.messagesMap);
  };

  cleanMessage = (message: proto.IWebMessageInfo): proto.IMessage => {
    const msg = message.message ?? {};
    return msg;
  };

  messageRetryHandler = async (message: proto.IMessageKey) => {
    const msg = this.getMessage(message.id ?? "");
    // Remove msg from map
    this.removeMessage(message.id ?? "");
    return msg;
  };
}

Then implement it as

const handler = new MessageRetryHandler();
const socketConfig: Partial<SocketConfig> = {
  printQRInTerminal: false,
  logger: PinoLogger({
    level: "silent",
  }),
  getMessage: handler.messageRetryHandler,
};

And when sending messages,

const sentMessage = await socket.sendMessage(id, {
    text: text,
  })
  .then(handler.addMessage);

This will handle all types of messages automatically, just remember to add the .then(handler.addMessage); after the message.

This solution is working, but not always. Some messages are retried 5 times without success and then it gives up.

GeovaneW96 avatar May 27 '22 16:05 GeovaneW96

Waiting for this message. This may take a while. Learn more. click on learn more. you will find you need send message to sync with other instance (Whatsapp web and mobile), it's because end to end encryption. Add Message Store to have sync data. this what i think so.

marutichintan avatar May 28 '22 04:05 marutichintan

You all can use

import { proto } from "@adiwajshing/baileys";
export class MessageRetryHandler {
  public messagesMap: Record<string, proto.IMessage>;

  constructor() {
    this.messagesMap = {};
  }

  addMessage = async (message: proto.IWebMessageInfo) => {
    const id = message.key.id ?? "";

    console.log(this);

    this.messagesMap[id] = this.cleanMessage(message);

    return message;
  };

  getMessage = (msgKey: string): proto.IMessage => {
    return this.messagesMap[msgKey];
  };

  removeMessage = (msgKey: string) => {
    delete this.messagesMap[msgKey];
  };

  getMessageKeys = (): string[] => {
    return Object.keys(this.messagesMap);
  };

  cleanMessage = (message: proto.IWebMessageInfo): proto.IMessage => {
    const msg = message.message ?? {};
    return msg;
  };

  messageRetryHandler = async (message: proto.IMessageKey) => {
    const msg = this.getMessage(message.id ?? "");
    // Remove msg from map
    this.removeMessage(message.id ?? "");
    return msg;
  };
}

Then implement it as

const handler = new MessageRetryHandler();
const socketConfig: Partial<SocketConfig> = {
  printQRInTerminal: false,
  logger: PinoLogger({
    level: "silent",
  }),
  getMessage: handler.messageRetryHandler,
};

And when sending messages,

const sentMessage = await socket.sendMessage(id, {
    text: text,
  })
  .then(handler.addMessage);

This will handle all types of messages automatically, just remember to add the .then(handler.addMessage); after the message.

This solution is working, but not always. Some messages are retried 5 times without success and then it gives up.

Did you found a fix for this? I am having this same issue.

guilhermeromer avatar May 31 '22 17:05 guilhermeromer

You all can use

import { proto } from "@adiwajshing/baileys";
export class MessageRetryHandler {
  public messagesMap: Record<string, proto.IMessage>;

  constructor() {
    this.messagesMap = {};
  }

  addMessage = async (message: proto.IWebMessageInfo) => {
    const id = message.key.id ?? "";

    console.log(this);

    this.messagesMap[id] = this.cleanMessage(message);

    return message;
  };

  getMessage = (msgKey: string): proto.IMessage => {
    return this.messagesMap[msgKey];
  };

  removeMessage = (msgKey: string) => {
    delete this.messagesMap[msgKey];
  };

  getMessageKeys = (): string[] => {
    return Object.keys(this.messagesMap);
  };

  cleanMessage = (message: proto.IWebMessageInfo): proto.IMessage => {
    const msg = message.message ?? {};
    return msg;
  };

  messageRetryHandler = async (message: proto.IMessageKey) => {
    const msg = this.getMessage(message.id ?? "");
    // Remove msg from map
    this.removeMessage(message.id ?? "");
    return msg;
  };
}

Then implement it as

const handler = new MessageRetryHandler();
const socketConfig: Partial<SocketConfig> = {
  printQRInTerminal: false,
  logger: PinoLogger({
    level: "silent",
  }),
  getMessage: handler.messageRetryHandler,
};

And when sending messages,

const sentMessage = await socket.sendMessage(id, {
    text: text,
  })
  .then(handler.addMessage);

This will handle all types of messages automatically, just remember to add the .then(handler.addMessage); after the message.

This solution is working, but not always. Some messages are retried 5 times without success and then it gives up.

Did you found a fix for this? I am having this same issue.

Not really a fix, but I send a new message after 5 failed retries.

GeovaneW96 avatar May 31 '22 19:05 GeovaneW96

When i send message to new number first time messages not showing ...Show only "Waiting for this message. This may take a while" screenshot attatched WhatsApp Image 2022-05-17 at 10 19 19 AM please help me you should implement getMessage on making socket

  • fetch a message from your store
  • implement this so that messages failed to send (solves the "this message can take a while" issue) can be retried getMessage: (key: proto.IMessageKey) => Promise<proto.IMessage | undefined>

example : implement a store at temporaryStore file (I created this file myself)

function deleteMessage(messageID) {
    delete messages[messageID]
}
function saveMessage(messageID, txt) {
    messages[messageID] = txt
}
function getMessage(messageID) {
    return messages[messageID]

}
function clearMessages() {
    messages = []
}
setInterval(clearMessages, 120000)
export default {
    getMessage,
    saveMessage,
    deleteMessage
}


then at making socket :

const retryMessageHandler = async message => {
    console.log("retry for send message !!!!!")
    let text = temporaryStore.getMessage(message.id)
    temporaryStore.deleteMessage(message.id)
    return {
        conversation: text
    }
}
sock = makeWASocket({
        browser: config.getAgent(process.env.AGENT_NUMBER),
        version,
        logger,
        printQRInTerminal: true,
        auth: state,
        msgRetryCounterMap,
        // implement to handle retries
        getMessage: retryMessageHandler  // at this line we use retryMessageHandler
 })


and finally after sending a message , save it at temporaryStore

let whatsappRes = await sock.sendMessage(jid, {text: text})
temporaryStore.saveMessage(whatsappRes.key.id, text)

       
       
       
       

Thank you so much, I am gonna implement this now.

When i send message to new number first time messages not showing ...Show only "Waiting for this message. This may take a while" screenshot attatched WhatsApp Image 2022-05-17 at 10 19 19 AM please help me

you should implement getMessage on making socket * fetch a message from your store * implement this so that messages failed to send (solves the "this message can take a while" issue) can be retried getMessage: (key: proto.IMessageKey) => Promise<proto.IMessage | undefined>

example : implement a store at temporaryStore file (I created this file myself)

let messages = []
function deleteMessage(messageID) {
    delete messages[messageID]
}
function saveMessage(messageID, txt) {
    messages[messageID] = txt
}
function getMessage(messageID) {
    return messages[messageID]

}
function clearMessages() {
    messages = []
}
setInterval(clearMessages, 120000)
export default {
    getMessage,
    saveMessage,
    deleteMessage
}


then at making socket :

const retryMessageHandler = async message => {
    console.log("retry for send message !!!!!")
    let text = temporaryStore.getMessage(message.id)
    temporaryStore.deleteMessage(message.id)
    return {
        conversation: text
    }
}
sock = makeWASocket({
        browser: config.getAgent(process.env.AGENT_NUMBER),
        version,
        logger,
        printQRInTerminal: true,
        auth: state,
        msgRetryCounterMap,
        // implement to handle retries
        getMessage: retryMessageHandler  // at this line we use retryMessageHandler
 })


and finally after sending a message , save it at temporaryStore

let whatsappRes = await sock.sendMessage(jid, {text: text})
temporaryStore.saveMessage(whatsappRes.key.id, text)

       
       
       
       

Sorry

Alhar6i avatar Jun 03 '22 19:06 Alhar6i

This issue is stale because it has been open 6 days with no activity. Remove the stale label or comment or this will be closed in 2 days

github-actions[bot] avatar Jun 10 '22 03:06 github-actions[bot]

any solution :(?

Bloxoid123 avatar Jun 14 '22 15:06 Bloxoid123

we must create new file?

nurmawan avatar Jun 15 '22 09:06 nurmawan

@adiwajshing I've two related finds.

  1. retryCount for sendMessageAgain is calculated per message, but often we need to resend same message to different devices.
  2. I've added dynamic delay between assertSessions and relayMessage in sendMessageAgain and the number of "waiting" messages become significantly reduced. Can I send patch to you for that?

ChCh27 avatar Jun 15 '22 11:06 ChCh27

@adiwajshing У меня есть две связанные находки.

  1. retryCount для sendMessageAgain рассчитывается для каждого сообщения, но часто нам нужно повторно отправлять одно и то же сообщение на разные устройства.
  2. Я добавил динамическую задержку между assertSessions и relayMessage в sendMessageAgain, и количество "ожидающих" сообщений значительно сократилось.Могу ли я отправить вам патч для этого?

Hi, please show this solution in the comments

salykingleb avatar Jun 15 '22 11:06 salykingleb

patch in attachment messages-recv.txt

ChCh27 avatar Jun 15 '22 11:06 ChCh27

патч во вложении messages-recv.txt

Thank you friend!

salykingleb avatar Jun 15 '22 11:06 salykingleb

In general, do you have any thoughts about what this problem is related to?

salykingleb avatar Jun 15 '22 11:06 salykingleb

Also examples of getMessage above are not correct. They delete saved message after first get, but we can do up to 5 attempts to resend message.

ChCh27 avatar Jun 15 '22 11:06 ChCh27

In general, do you have any thoughts about what this problem is related to?

No :(

ChCh27 avatar Jun 15 '22 11:06 ChCh27

In general, do you have any thoughts about what this problem is related to?

No :(

We are also guessing

salykingleb avatar Jun 15 '22 11:06 salykingleb

It's strange that on version 4.1.0, before the fixes about a month ago, everything works correctly

salykingleb avatar Jun 15 '22 11:06 salykingleb

patch in attachment messages-recv.txt

Not helped for me :( Anyone helped?

bugsbunch avatar Jun 15 '22 17:06 bugsbunch

исправление во вложении messages-recv.txt

Мне не помогло: ( Кто-нибудь помог? also no

salykingleb avatar Jun 15 '22 17:06 salykingleb

Does anyone have a working solution? Even if it's not very good. Very necessary

bugsbunch avatar Jun 15 '22 18:06 bugsbunch

not working

enoksaju avatar Jun 15 '22 21:06 enoksaju

I saw a fix in the bible, but it didn't help for me. Are there those who work for?

salykingleb avatar Jun 16 '22 12:06 salykingleb

I saw a fix in the bible, but it didn't help for me. Are there those who work for?

Statistic becomes better with this getMessage method and new baileys fixes. But about 20% of messages are still not delivered https://discord.com/channels/725839806084546610/891299313932722247/975018675306373140

bugsbunch avatar Jun 16 '22 14:06 bugsbunch

I also have this problem

fxj1997 avatar Jun 17 '22 09:06 fxj1997

Please help us @adiwajshing I have the same problem.

anjarokz avatar Jun 17 '22 12:06 anjarokz

me too..

jeanscircuits avatar Jun 22 '22 06:06 jeanscircuits

This problem persists.

jeffersonveloso avatar Jun 26 '22 02:06 jeffersonveloso

Please help us @adiwajshing I have the same problem.

mnsise avatar Jun 26 '22 07:06 mnsise

I have same problem, please help.

junfpurba avatar Jun 26 '22 10:06 junfpurba

any solution!? problem already exists

sreza78 avatar Jun 27 '22 17:06 sreza78

i have the same problem...

zellsito avatar Jun 29 '22 02:06 zellsito

A temporary solution add an delay in getMessage For some reason baileys calls this function before the callback that saves the message

Thanks @mrhb6006 , and @Manjit2003

linkbr avatar Jul 01 '22 23:07 linkbr

any update ?

MaznAbdullah avatar Jul 09 '22 18:07 MaznAbdullah

Hi I have same problem And I get this error only on new chat and for first message !!!

vahid-jml avatar Jul 12 '22 11:07 vahid-jml

Some one give us a fix for this issue, receivers are not able to see the message content

I can pay for any available solution :)

MuhammadKarzoun avatar Jul 13 '22 19:07 MuhammadKarzoun

Please use baileys version 4.1.0 till the issue is not resolved.

aarvee022 avatar Jul 14 '22 08:07 aarvee022

same issue here. Does the delay in getMessage has any effect?

tiesco238 avatar Jul 15 '22 09:07 tiesco238

any update ?

fabbioSborges avatar Jul 15 '22 13:07 fabbioSborges

When i send message to new number first time messages not showing ...Show only "Waiting for this message. This may take a while" screenshot attatched WhatsApp Image 2022-05-17 at 10 19 19 AM please help me

you should implement getMessage on making socket * fetch a message from your store * implement this so that messages failed to send (solves the "this message can take a while" issue) can be retried getMessage: (key: proto.IMessageKey) => Promise<proto.IMessage | undefined>

example : implement a store at temporaryStore file (I created this file myself)

let messages = []
function deleteMessage(messageID) {
    delete messages[messageID]
}
function saveMessage(messageID, txt) {
    messages[messageID] = txt
}
function getMessage(messageID) {
    return messages[messageID]

}
function clearMessages() {
    messages = []
}
setInterval(clearMessages, 120000)
export default {
    getMessage,
    saveMessage,
    deleteMessage
}


then at making socket :

const retryMessageHandler = async message => {
    console.log("retry for send message !!!!!")
    let text = temporaryStore.getMessage(message.id)
    temporaryStore.deleteMessage(message.id)
    return {
        conversation: text
    }
}
sock = makeWASocket({
        browser: config.getAgent(process.env.AGENT_NUMBER),
        version,
        logger,
        printQRInTerminal: true,
        auth: state,
        msgRetryCounterMap,
        // implement to handle retries
        getMessage: retryMessageHandler  // at this line we use retryMessageHandler
 })


and finally after sending a message , save it at temporaryStore

let whatsappRes = await sock.sendMessage(jid, {text: text})
temporaryStore.saveMessage(whatsappRes.key.id, text)

       
       
       
       

can you help me fixing the issue ? I am looking to some one who can fix it in my app

MuhammadKarzoun avatar Jul 16 '22 11:07 MuhammadKarzoun

Please use baileys version 4.1.0 till the issue is not resolved.

Has anyone tried it with that version?

enoksaju avatar Jul 16 '22 13:07 enoksaju

Yes, but no difference.. Tried also latest commit but no luck.

tiesco238 avatar Jul 18 '22 09:07 tiesco238

Statistic becomes better with this getMessage method and new baileys fixes. But about 20% of messages are still not delivered https://discord.com/channels/725839806084546610/891299313932722247/975018675306373140

retry sending with getMessage not always works for me, sometimes message still waiting

makanSukros avatar Jul 19 '22 02:07 makanSukros

same issue

Ajayos avatar Jul 19 '22 08:07 Ajayos

Statistic becomes better with this getMessage method and new baileys fixes. But about 20% of messages are still not delivered https://discord.com/channels/725839806084546610/891299313932722247/975018675306373140

retry sending with getMessage not always works for me, sometimes message still waiting

same issue. is there anything we can do to resend the message even after attemp failed? it's hard to reproduce the failed after 5 attemp retries issue as it only occasionally happen

Fonnte avatar Jul 19 '22 08:07 Fonnte

same issue

guilhermebkel avatar Jul 19 '22 12:07 guilhermebkel

As I explained before, this method works for me and solved the problem

https://github.com/adiwajshing/Baileys/issues/1631#issuecomment-1129573412

Read this comment and the comments below it carefully

mrhb6006 avatar Jul 21 '22 12:07 mrhb6006

As I explained before, this method works for me and solved the problem

#1631 (comment)

Read this comment and the comments below it carefully

Hi Brother, can you help me fix the issue in my script, I am ready to have a deal

thanks

MuhammadKarzoun avatar Jul 22 '22 12:07 MuhammadKarzoun

As I explained before, this method works for me and solved the problem #1631 (comment) Read this comment and the comments below it carefully

Hi Brother, can you help me fix the issue in my script, I am ready to have a deal

thanks

@MuhammadKarzoun We already implemented this in our script with the store function, but it consumes more Ram and did not work

enoksaju avatar Jul 22 '22 12:07 enoksaju

Using Baileys 4.1.0 with store is helps. Latest version have the problem unsolved. Observing 300+ instances of Baileys.

keef3ar avatar Jul 22 '22 12:07 keef3ar

Using Baileys 4.1.0 with store is helps. Latest version have the problem unsolved. Observing 300+ instances of Baileys.

which kind of store? multifile session or single file? any msghdlr? plz give us an example code tnx!

zellsito avatar Jul 25 '22 07:07 zellsito

Still relevant

neves-gabriel avatar Jul 27 '22 03:07 neves-gabriel

Very relevant.

Heknon avatar Jul 27 '22 16:07 Heknon

By store i mean messages store + message handler from above. Session is stored in remote database.

      getMessage: async (key): Promise<proto.IMessage | undefined> => {
        Logger.print({ retry_message: key });
        const { id } = key;
        if (id) {
          const found = Storage.getSent(id);
          if (found) {
            Logger.print({ retry_found: key });
            return found;
          } else Logger.print({ retry_no_found: key });
        }
      }

keef3ar avatar Jul 28 '22 10:07 keef3ar

same issue

fman42 avatar Aug 01 '22 08:08 fman42

This issue is stale because it has been open 6 days with no activity. Remove the stale label or comment or this will be closed in 2 days

github-actions[bot] avatar Aug 08 '22 03:08 github-actions[bot]

+1

enoksaju avatar Aug 08 '22 03:08 enoksaju

Still relevant

neves-gabriel avatar Aug 08 '22 13:08 neves-gabriel

This issue is stale because it has been open 6 days with no activity. Remove the stale label or comment or this will be closed in 2 days

github-actions[bot] avatar Aug 15 '22 03:08 github-actions[bot]

Quando eu envio uma mensagem para um novo número, a primeira mensagem não aparece ...Mostrar apenas "Aguardando esta mensagem. Isso pode demorar um pouco" captura de tela anexada , por favor me ajudeImagem do WhatsApp 2022-05-17 às 10 19 19 AM

você deve implementar getMessage ao fazer soquete * buscar uma mensagem de sua loja * implementar isso para que as mensagens com falha no envio (resolve o problema "esta mensagem pode demorar um pouco") possam ser repetidas getMessage: (chave: proto.IMessageKey) => Promessa<proto.IMessage | undefined> exemplo: implemente uma loja no arquivo temporárioStore (eu mesmo criei este arquivo)

let messages = []
function deleteMessage(messageID) {
    delete messages[messageID]
}
function saveMessage(messageID, txt) {
    messages[messageID] = txt
}
function getMessage(messageID) {
    return messages[messageID]

}
function clearMessages() {
    messages = []
}
setInterval(clearMessages, 120000)
export default {
    getMessage,
    saveMessage,
    deleteMessage
}


then at making socket :

const retryMessageHandler = async message => {
    console.log("retry for send message !!!!!")
    let text = temporaryStore.getMessage(message.id)
    temporaryStore.deleteMessage(message.id)
    return {
        conversation: text
    }
}
sock = makeWASocket({
        browser: config.getAgent(process.env.AGENT_NUMBER),
        version,
        logger,
        printQRInTerminal: true,
        auth: state,
        msgRetryCounterMap,
        // implement to handle retries
        getMessage: retryMessageHandler  // at this line we use retryMessageHandler
 })


and finally after sending a message , save it at temporaryStore

let whatsappRes = await sock.sendMessage(jid, {text: text})
temporaryStore.saveMessage(whatsappRes.key.id, text)

       
       
       
       

Mano, obrigado por tentar nos ajudar, é possível usar esta solução para enviar url de mídia e botões?

sim , apenas salve toda a estrutura da mensagem em vez do texto da mensagem no temporárioStore e retorne isso no retryMessageHandler

Também pensei nisso! Deve resolver para cada tipo de mensagem já que a estrutura é salva completamente e não só o texto

undefined-60 avatar Aug 16 '22 11:08 undefined-60

Quando eu envio uma mensagem para um novo número, a primeira mensagem não aparece ...Mostrar apenas "Aguardando esta mensagem. Isso pode demorar um pouco" captura de tela anexada , por favor me ajudeImagem do WhatsApp 2022-05-17 às 10 19 19 AM

você deve implementar getMessage ao fazer soquete * buscar uma mensagem de sua loja * implementar isso para que as mensagens com falha no envio (resolve o problema "esta mensagem pode demorar um pouco") possam ser repetidas getMessage: (chave: proto.IMessageKey) => Promessa<proto.IMessage | undefined> exemplo: implemente uma loja no arquivo temporárioStore (eu mesmo criei este arquivo)

let messages = []
function deleteMessage(messageID) {
    delete messages[messageID]
}
function saveMessage(messageID, txt) {
    messages[messageID] = txt
}
function getMessage(messageID) {
    return messages[messageID]

}
function clearMessages() {
    messages = []
}
setInterval(clearMessages, 120000)
export default {
    getMessage,
    saveMessage,
    deleteMessage
}


then at making socket :

const retryMessageHandler = async message => {
    console.log("retry for send message !!!!!")
    let text = temporaryStore.getMessage(message.id)
    temporaryStore.deleteMessage(message.id)
    return {
        conversation: text
    }
}
sock = makeWASocket({
        browser: config.getAgent(process.env.AGENT_NUMBER),
        version,
        logger,
        printQRInTerminal: true,
        auth: state,
        msgRetryCounterMap,
        // implement to handle retries
        getMessage: retryMessageHandler  // at this line we use retryMessageHandler
 })


and finally after sending a message , save it at temporaryStore

let whatsappRes = await sock.sendMessage(jid, {text: text})
temporaryStore.saveMessage(whatsappRes.key.id, text)

       
       
       
       

Mano, obrigado por tentar nos ajudar, é possível usar esta solução para enviar url de mídia e botões?

sim , apenas salve toda a estrutura da mensagem em vez do texto da mensagem no temporárioStore e retorne isso no retryMessageHandler

Também pensei nisso! Deve resolver para cada tipo de mensagem já que a estrutura é salva completamente e não só o texto

This solution in some chats not work for template buttons, buttons and media.

jeffersonveloso avatar Aug 16 '22 16:08 jeffersonveloso

Still relevant

adarsh-chakraborty avatar Aug 22 '22 18:08 adarsh-chakraborty

This issue is stale because it has been open 6 days with no activity. Remove the stale label or comment or this will be closed in 2 days

github-actions[bot] avatar Aug 29 '22 03:08 github-actions[bot]

Still relevant

craines avatar Aug 29 '22 18:08 craines

I would send a default message, before sending the right message. But it would be nice to know when this error happens, to simply resend the message again

craines avatar Aug 29 '22 18:08 craines

+1

erickmunozr avatar Aug 31 '22 03:08 erickmunozr

So that this does not happen, I only have to connect the account with baileys, if I open another session with whatsapp web the next day it starts to generate that problem

erickmunozr avatar Aug 31 '22 03:08 erickmunozr