question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

SendMessage() works, but no sent messages in the chat

See original GitHub issue

Is there an existing issue for this?

  • I have searched the existing issues

Describe the bug

I’m doing client.sendMessage(), it doesn’t throw any errors, but message doesn’t appear in the sent messages on the phone and the recepient doesn’t get it. Sometimes it works fine, but sometimes not for the same sender whatsapp account. Is there any restrictions in the WhatsApp to send messages to other users which are not in the contacts or something else?

Expected behavior

Expected to see every sent message on the phone or get an error.

Steps to Reproduce the Bug or Issue

Send messages to the client which is not in the contacts.

Relevant Code

`

try {
  if(activeClients[userId] || Object.entries(activeClients).length >= process.env.ACTIVE_CLIENTS - 1){
    logger.debug("client active for user", userId)
    return resolve({ error: true, msg: firstMsg });
  }

  const collectionU = await getCollection(db, "users");
  const objectIdU = new ObjectId(userId);
  const resultU = await collectionU.findOne({
    _id: objectIdU,
  });

  if(!resultU.session){
    logger.log('user session inactive: ', userId)
    return resolve({ error: true, msg: firstMsg });
  }

  activeClients[userId] = true

  logger.log("---init client---")
  const whatsapp = new Client({
    authStrategy: new LocalAuth({clientId: userId, dataPath: "auth/"}),
    takeoverOnConflict: true,
    takeoverTimeoutMs: 500,
    puppeteer: {
      headless: true,
      ignoreHTTPSErrors: true,
      args: [
        "--no-sandbox",
        "--disable-setuid-sandbox",
        "--disable-extensions",
        '--disable-gpu', 
        "--disable-accelerated-2d-canvas",
        "--no-first-run",
        "--no-zygote",
        '--disable-dev-shm-usage'
      ],
    },
  });

  var timeout = setTimeout(async () => {
    logger.log("timeout send")
    await destroyClient(whatsapp, userId);
    return resolve({ error: true, msg: firstMsg });
  }, 30000);

  whatsapp.on("ready", async () => {
    let msg = helper.replacesName(
      firstMsg.message.message,
      firstMsg.user.firstName
    );
    firstMsg.user.phone = firstMsg.user.phone.replace(/[\s\-\(\)\+]+/gi, '')
    msg = helper.replacesTime(msg, firstMsg.user.time);
    const number_details = await whatsapp.getNumberId(firstMsg.user.phone);
    logger.log(`whatsapp number details`);
    logger.log(number_details);
    if (number_details) {
      await whatsapp.sendMessage(number_details._serialized, msg); // send message
      logger.log(
        "Message sent with getNumberId to " + firstMsg.user.phone
      );
      clearTimeout(timeout);
      await destroyClient(whatsapp, userId);
      return resolve({
        error: false,
        msg: "Send message on number " + firstMsg.user.phone,
      });
    } else {
      const contacts = await whatsapp.getContacts();
      const contact = contacts.find(
        ({ number }) => number === firstMsg.user.phone
      );
      if (contact) {
        const {
          id: { _serialized: chatId },
        } = contact;
        logger.log("chatId: ", chatId)
        await whatsapp.sendMessage(chatId, msg);
        logger.log(
          "Message sent with getContacts to " + firstMsg.user.phone
        );
        clearTimeout(timeout);
        await destroyClient(whatsapp, userId);
        return resolve({ error: false, msg: "Promise" + firstMsg.user.phone });
      } else {
        firstMsg.user.phone = firstMsg.user.phone + "@c.us";
        await whatsapp.sendMessage(firstMsg.user.phone, msg);
        logger.log("Message sent with @c.us to " + firstMsg.user.phone);
        clearTimeout(timeout);
        await destroyClient(whatsapp, userId);
        return resolve({ error: false, msg: "Promise" + firstMsg.user.phone });
      }
    }
  });
  whatsapp.on("auth_failure", async (session) => {
    logger.log("error session", session);
    clearTimeout(timeout);
    await destroyClient(whatsapp, userId);
    return resolve({ error: true, msg: firstMsg });
  });

  whatsapp.initialize().catch(async (ex) => {
    logger.log("---init catch---")
    logger.error(ex);
    clearTimeout(timeout);
    await destroyClient(whatsapp, userId);
    logger.log("---init catch---")
    return resolve({ error: true, msg: firstMsg });
  });
  logger.log("---init client---")
} catch (e) {
  logger.error("catch err: ", e)
  activeClients[userId] = false
  return resolve({ error: true, msg: firstMsg });
}

const destroyClient = async (client, userId = 0) => {
  return new Promise((resolve) => {
    client.removeAllListeners()
    setTimeout(() => {
      try {
        client.destroy();
      } catch (e) {
        logger.error(e);
      }
      delete activeClients[userId];
      return resolve();
    }, 1500);
  });
};

`

Browser Type

Chromium

WhatsApp Account Type

Standard

Does your WhatsApp account have multidevice enabled?

Yes, I am using Multi Device

Environment

OS: Amazon Linux Phone OS: Android whatsapp-web.js version: 1.16.7 WhatsApp Web version: 2.2119 Node.js Version: 16

Additional context

No response

Issue Analytics

  • State:open
  • Created a year ago
  • Reactions:1
  • Comments:13

github_iconTop GitHub Comments

1reaction
bfibriantocommented, Jun 27, 2022

for now I deleted the session and restarted, and it worked

Sadly this workaround not working for me

0reactions
josegbcommented, Jul 13, 2022

I have had the same problem, in my case I managed to solve it by installing an older version of Chrome, specifically 101.0.4951.64-1.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Send chatMessage in a channel or a chat - Microsoft Graph v1.0
Send a new chatMessage in the specified channel or a chat. ... Sending message in a chat ... Example 3: Send message containing...
Read more >
slack api - Why I am unable to send message to the user via ...
We have application that integrates with Slack API and sends the messages via https://api.slack.com/methods/chat.postMessage Slack API.
Read more >
If you can't send or receive messages on your iPhone or iPad
Go to Settings > Messages > iMessage to see what phone numbers and email addresses you. If you receive messages on one device...
Read more >
Send & receive text & voice messages in ... - Google Support
You can send and receive text messages with friends and contacts on Messages. Start a conversation Open the Messages app.
Read more >
Messaging - Messenger Platform - Meta for Developers
Messages sent with the Messenger Platform are classified as one of two different message ... are app-scoped and will not work with the...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found