mukulhase / WebWhatsapp-Wrapper

An API for sending and receiving messages over web.whatsapp [Working as of 18th May 2018]
https://webwhatsapi.readthedocs.io/en/latest/
MIT License
2.04k stars 793 forks source link

WAPI.sendMessageToID does not work #1126

Open kivlanzein opened 2 years ago

kivlanzein commented 2 years ago

please help me, why sendMessageToID not work? , i can't send messages to the new number??

please help me..

mraakashjoshi commented 2 years ago

same issue.

duzaq commented 2 years ago

// use this code window.WAPI.sendMessageToID2 = function (id, message, done) { try { // Create user var idx = new window.Store.UserConstructor(id, {intentionallyUsePrivateConstructor: true}); // Get chat var chat = window.Store.Chat.find(idx); // Send message chat._value.sendMessage(message); } catch (e) { return false;

}
if (done !== undefined) done(false);
return false;

}; //window.WAPI.sendMessageToID2 ('0000000000@c.us','oi');

mraakashjoshi commented 2 years ago

// use this code window.WAPI.sendMessageToID2 = function (id, message, done) { try { // Create user var idx = new window.Store.UserConstructor(id, {intentionallyUsePrivateConstructor: true}); // Get chat var chat = window.Store.Chat.find(idx); // Send message chat._value.sendMessage(message); } catch (e) { return false;

}
if (done !== undefined) done(false);
return false;

}; //window.WAPI.sendMessageToID2 ('0000000000@c.us','oi');

not sending on new number on which there is no chat history

duzaq commented 2 years ago

// use this code window.WAPI.sendMessageToID2 = function (id, message, done) { try { // Create user var idx = new window.Store.UserConstructor(id, {intentionallyUsePrivateConstructor: true}); // Get chat var chat = window.Store.Chat.find(idx); // Send message chat._value.sendMessage(message); } catch (e) { return false;

}
if (done !== undefined) done(false);
return false;

}; //window.WAPI.sendMessageToID2 ('0000000000@c.us','oi');

this was the solution I found, and the sending to new numbers is working

mraakashjoshi commented 2 years ago

// use this code window.WAPI.sendMessageToID2 = function (id, message, done) { try { // Create user var idx = new window.Store.UserConstructor(id, {intentionallyUsePrivateConstructor: true}); // Get chat var chat = window.Store.Chat.find(idx); // Send message chat._value.sendMessage(message); } catch (e) { return false;

}
if (done !== undefined) done(false);
return false;

}; //window.WAPI.sendMessageToID2 ('0000000000@c.us','oi');

this was the solution I found, and the sending to new numbers is working

getting this error javascript error: Unexpected token 'if'

Parveen-Mothsara commented 2 years ago

@duzaq Please share latest wapi.js

mraakashjoshi commented 2 years ago

@duzaq Please share latest wapi.js

just add below line in WAPI.sendMessageToID in try quote

var chat = window.Store.Chat.find(id); if(chat._value.sendMessage(message)){done(true);return true;}

no need of WAPI.sendMessageToID2

mraakashjoshi commented 2 years ago

// use this code window.WAPI.sendMessageToID2 = function (id, message, done) { try { // Create user var idx = new window.Store.UserConstructor(id, {intentionallyUsePrivateConstructor: true}); // Get chat var chat = window.Store.Chat.find(idx); // Send message chat._value.sendMessage(message); } catch (e) { return false;

}
if (done !== undefined) done(false);
return false;

}; //window.WAPI.sendMessageToID2 ('0000000000@c.us','oi');

this was the solution I found, and the sending to new numbers is working

getting this error javascript error: Unexpected token 'if'

just add below line in WAPI.sendMessageToID in try quote

var chat = window.Store.Chat.find(id); if(chat._value.sendMessage(message)){done(true);return true;}

no need of WAPI.sendMessageToID2

mraakashjoshi commented 2 years ago

just add below line in WAPI.sendMessageToID in try quote

var chat = window.Store.Chat.find(id); if(chat._value.sendMessage(message)){done(true);return true;}

no need of WAPI.sendMessageToID2

ruanduarte commented 2 years ago

this worked for me.

fly2012 commented 2 years ago

just add below line in WAPI.sendMessageToID in try quote

var chat = window.Store.Chat.find(id); if(chat._value.sendMessage(message)){done(true);return true;}

no need of WAPI.sendMessageToID2

It doesn't work on New id.How to resolve it?

santirlopez1124 commented 2 years ago

@fly2012 I have the same problem, do u solve it?

ruanduarte commented 2 years ago

Hello, with the code bellow i can send messages to new ids without problem. There's just one weird thing about this function that its always returns "false". But the message is sent successfuly.

window.WAPI.sendMessageToID = function (id, message, done) {
    try {
        window.getContact = (id) => {
            return Store.WapQuery.queryExist(id);
        }
        window.getContact(id).then(contact => {
            if (contact.status === 404) {
                done(true);
            } else {
                if(typeof contact.jid === 'undefined') {
                        contact.jid = {
                            '_serialized' : id,
                            'server' : '@' + id.split('@')[1],
                            'user' : id.split('@')[0]
                        }
                 }
                Store.FindChat.findChat(contact.jid).then(chat => {
                    chat.sendMessage(message);
                    return true;
                }).catch(reject => {
                    if (WAPI.sendMessage(id, message)) {
                        done(true);
                        return true;
                    }else{
                        done(false);
                        return false;
                    }
                });
            }
        });
    } catch (e) {
        if (window.Store.Chat.length === 0)
            return false;

        firstChat = Store.Chat.models[0];
        var originalID = firstChat.id;
        firstChat.id = typeof originalID === "string" ? id : new window.Store.UserConstructor(id, { intentionallyUsePrivateConstructor: true });
        if (done !== undefined) {
            firstChat.sendMessage(message).then(function () {
                firstChat.id = originalID;
                done(true);
            });
            return true;
        } else {
            firstChat.sendMessage(message);
            firstChat.id = originalID;
            return true;
        }
    }
    if (done !== undefined) done(false);
    return false;
}
santirlopez1124 commented 2 years ago

Hi @ruanduarte, did u check it in whatsapp business multidevice version? Because it doesn't work to me

ruanduarte commented 2 years ago

@santirlopez1124, no, I didn't. I'm using the normal version without multidevice. :/

vilsonei commented 2 years ago

I solved like this:

1) Add the line with FindChat in neededObjects

if (!window.Store) {
  (function () {
    function getStore(modules) {
      let foundCount = 0;
      let neededObjects = [
          ...,
          { id: "FindChat", conditions: (module) => module.findChat ? module : module.default && module.default.findChat ? module.default : null }
     ]
     ....

2) Replace your getChat implementation with this one

window.WAPI.getChat = function (id, done) {

  // New version WhatsApp Beta Multi Device
  if (WAPI.isMultiDeviceVersion()) {
    let chat = window.Store.Chat.get(id);
    if (chat) {
      if (chat.sendMessage) {
        if (done) done(chat);
        return chat;
      } else {
        if (done) done(chat._value);
        return chat._value;
      }
    } else {
      // Create user
      var idx = new window.Store.UserConstructor(id, { intentionallyUsePrivateConstructor: true });

      window.Store.FindChat.findChat(idx).then(chat => {
        if (done) done(chat);
      }).catch(e => {
        if (done) done(null);
      })

      return undefined;
    }
  } else
  // Old version
  {
    id = typeof id == "string" ? id : id._serialized;
    const found = window.Store.Chat.get(id);
    found.sendMessage = (found.sendMessage) ? found.sendMessage : function () { return window.Store.sendMessage.apply(this, arguments); };
    if (done !== undefined) done(found);
    return found;
  }
}

3) This is my isMultiDeviceVersion method

window.WAPI.isMultiDeviceVersion = function () {
  try {
    let resp = window.Store.FeatureChecker.GK.features['MD_BACKEND'];
    return resp;
  } catch {
    return false;
  }
}

4) My sendMessageToID method

window.WAPI.sendMessageToID = function (id, message, done) {

  try {
    // New version WhatsApp Beta
    if (WAPI.isMultiDeviceVersion()) {
      WAPI.getChat(id, chat => {
        if (chat) {
          chat.sendMessage(message);
          done(true);
          return true;
        } else {
          done(false);
          return false;
        }
      });
    } else {
      // Old version of WhatsApp
      try {
        window.getContact = (id) => {
          return Store.WapQuery.queryExist(id);
        }
        window.getContact(id).then(contact => {
          if (contact.status === 404) {
            done(true);
          } else {
            Store.Chat.find(contact.jid).then(chat => {
              chat.sendMessage(message);
              done(true);
              return true;
            }).catch(reject => {
              if (WAPI.sendMessage(id, message)) {
                done(true);
                return true;
              } else {
                done(false);
                return false;
              }
            });
          }
        });
      } catch (e) {
        if (window.Store.Chat.length === 0) {
          done(false);
          return false;
        }

        firstChat = Store.Chat.models[0];
        var originalID = firstChat.id;
        firstChat.id = typeof originalID === "string" ? id : new window.Store.UserConstructor(id, { intentionallyUsePrivateConstructor: true });
        if (done !== undefined) {
          firstChat.sendMessage(message).then(function () {
            firstChat.id = originalID;
            done(true);
          });
          return true;
        } else {
          firstChat.sendMessage(message);
          firstChat.id = originalID;
          done(true);
          return true;
        }
      }
    }
  } catch (e) {
    done(false);
    return false;
  }
}
dekkardnexus5 commented 2 years ago

Vilson ney, It worked for me! Tk you very much for your solution Did you have had any number banned after send message to new Id?

alexeykirichek commented 2 years ago

@vilsonei, hello! I tried to use the algorithm that you suggest, but I came across the fact that in all cases a message is sent, even if the number is not registered in WA. Is this how it should be, or did I make some mistake?

vilsonei commented 2 years ago

Vilson ney, It worked for me! Tk you very much for your solution Did you have had any number banned after send message to new Id?

Not yet! I believe that WhatsApp has lowered the sensitivity of robots in the latest version.

vilsonei commented 2 years ago

@vilsonei, hello! I tried to use the algorithm that you suggest, but I came across the fact that in all cases a message is sent, even if the number is not registered in WA. Is this how it should be, or did I make some mistake?

I do like this:

BWAPI.enviarMensagem = (numero, msg, resolve) => {
  WAPI.checkNumberStatus(numero, data => {

    // Se o status é 200 envia a mensagem
    // if (data.status === 200) {
    if (data && data.status === 200) {
      numero = data.id._serialized;
      WAPI.sendMessageToID(numero, msg, data => {
        resolve(true);
      })

    } else
    // Caso contrário tente utilizar com o nono digito
    if ( numero.length < 18 ) {
      let numeroNonoDigito = window.BWAPI.addNonoDigito(numero);
      window.BWAPI.enviarMensagem(numeroNonoDigito, msg, resolve)
    } else {
      resolve(false);
    }
  });
}

BWAPI.addNonoDigito = (numero) => {
    return numero.substring(0,4) + '9' + numero.substring(4, numero.length);
}
pablodosreis commented 2 years ago

Vilsonei, wich version do you use as base from your script?

If is possible, could you share your complete wapi.js?

I'm trying make your changes but I thing my initial version is not the same.

vilsonei commented 2 years ago

Vilsonei, wich version do you use as base from your script?

If is possible, could you share your complete wapi.js?

I'm trying make your changes but I thing my initial version is not the same.

This is my lasted customized version: Link for download

There are some test codes I forgot to remove 😅

RDKclick commented 2 years ago

@vilsonei How can I check whether the WA account exists using this script? "Store.QueryExist.queryExist("788888887737@c.us")" is no wrok

luidiva commented 2 years ago

Receving this message when calling sendMessage sendMessage JavaScript stack: TypeError: Cannot read properties of undefined (reading 'then') at Object.window.WAPI.sendMessage (eval at executeScript

vilsonei commented 2 years ago

@vilsonei How can I check whether the WA account exists using this script? "Store.QueryExist.queryExist("788888887737@c.us")" is no wrok

Yes! Try this using my custom script:

WAPI.checkNumberStatus(numero, data => {

    // if status 200 send message
    // if (data.status === 200) {
    if (data && data.status === 200) {
      numero = data.id._serialized;
      WAPI.sendMessageToID(numero, msg, data => {
        resolve(true);
      })

    } else {
      resolve(false);
    }
  });

See my custom script here.

vilsonei commented 2 years ago

Receving this message when calling sendMessage sendMessage JavaScript stack: TypeError: Cannot read properties of undefined (reading 'then') at Object.window.WAPI.sendMessage (eval at executeScript

Are you using this script? See script

roigreenberg commented 2 years ago

Hi @vilsonei I merged your script into mine, and tried to use it with multi-devices,

For some reason, after scanning the QR code, I get an error asking me if my computer has internet. I'm running it from Azure, and if I'm trying to go to another website it's obviously working.

Do you have any idea what can be the error?

vilsonei commented 2 years ago

Hi @vilsonei I merged your script into mine, and tried to use it with multi-devices,

For some reason, after scanning the QR code, I get an error asking me if my computer has internet. I'm running it from Azure, and if I'm trying to go to another website it's obviously working.

Do you have any idea what can be the error?

Do you see any errors in the browser's debug console?

roigreenberg commented 2 years ago

No. I now noticed that if I delete the local storage and rescan the QR, it works, but after a restart, it happens again.

vilsonei commented 2 years ago

No. I now noticed that if I delete the local storage and rescan the QR, it works, but after a restart, it happens again.

You should analyze the moment you are injecting WAPI.js

WAPI.js should only be injected after WhatsApp is fully loaded so that the context variables are not lost or injected incorrectly.

roigreenberg commented 2 years ago

Where can I control it?

Are there any required changes in asyncdriver.py or __init_\.py?

luidiva commented 2 years ago

Receving this message when calling sendMessage sendMessage JavaScript stack: TypeError: Cannot read properties of undefined (reading 'then') at Object.window.WAPI.sendMessage (eval at executeScript

Are you using this script? See script

Yes I am. Try adding a try/catch block around the chat.sendMessage(message).then(function () { to catch the error, please.

window.WAPI.sendMessage = function (id, message, done) {
    var chat = WAPI.getChat(id);
    if (chat !== undefined) {
        if (done !== undefined) {
            try {
                chat.sendMessage(message).then(function () {
                    function sleep(ms) {
                        return new Promise(resolve => setTimeout(resolve, ms));
                    }

                    var trials = 0;

                    function check() {
                        for (let i = chat.msgs.models.length - 1; i >= 0; i--) {
                            let msg = chat.msgs.models[i];

                            if (!msg.senderObj.isMe || msg.body != message) {
                                continue;
                            }
                            done(WAPI._serializeMessageObj(msg));
                            return True;
                        }
                        trials += 1;
                        console.log(trials);
                        if (trials > 30) {
                            done(true);
                            return;
                        }
                        sleep(500).then(check);
                    }
                    check();
                });
                return true;
            } catch (e) {
                console.log(e);
            }

        } else {
            chat.sendMessage(message);
            return true;
        }
    } else {
        if (done !== undefined)
            done(false);
        return false;
    }
};
luidiva commented 2 years ago

Receving this message when calling sendMessage sendMessage JavaScript stack: TypeError: Cannot read properties of undefined (reading 'then') at Object.window.WAPI.sendMessage (eval at executeScript

Are you using this script? See script

Tudo bem @vilsonei ? Conseguiu reproduzir o erro do sendMessage(msg).then ?

roigreenberg commented 2 years ago

@vilsonei did you do any changes in order to save the session in multi-device mode? I understood there is a different file that needed to be saved, but I don't know which one..

vilsonei commented 2 years ago

@vilsonei did you do any changes in order to save the session in multi-device mode? I understood there is a different file that needed to be saved, but I don't know which one..

I didn't make any changes as I use the script with node and puppeteer, so I save the session in browser context.

Masterxv commented 2 years ago

window.Store.WapQuery.queryExist not working anymore

Parveen-Mothsara commented 2 years ago

Vilsonei, wich version do you use as base from your script? If is possible, could you share your complete wapi.js? I'm trying make your changes but I thing my initial version is not the same.

This is my lasted customized version: Link for download

There are some test codes I forgot to remove 😅

@vilsonei I just use your wapi.js in multi device version,but checkNumberStatus is always give true either number exist or not.

ruanduarte commented 2 years ago

Thanks @vilsonei , this version worked or me.

DevSmith commented 2 years ago

it is stopped working, please help.

DevSmith commented 2 years ago

@vilsonei please share latest wapi.

vilsonei commented 2 years ago

@vilsonei please share latest wapi.

My WAPI.js is customized for my business rule, but you can compare and utilize. Click here

yagoocarvalho commented 2 years ago

@vilsonei your code works for a while but then the message goes to the WhatsApp web platform and can't be delivered, and when restart the driver it works again, can you share with us your environment configs (python and selenium versions)? Thanks!

yagoocarvalho commented 2 years ago

@vilsonei your code works for a while but then the message goes to the WhatsApp web platform and can't be delivered, and when restart the driver it works again, can you share with us your environment configs (python and selenium versions)? Thanks!

vilsonei commented 2 years ago

@vilsonei your code works for a while but then the message goes to the WhatsApp web platform and can't be delivered, and when restart the driver it works again, can you share with us your environment configs (python and selenium versions)? Thanks!

@yagoocarvalho I did not test in python and selenium environments, I use this script in one of my applications with puppeteer, so I can't give you this answer.

Parveen-Mothsara commented 2 years ago

@vilsonei CheckNumberStatus not working ,its callback always in pending state.please help.

vilsonei commented 2 years ago

@vilsonei CheckNumberStatus not working ,its callback always in pending state.please help.

@Parveen-Mothsara compare your API with this one, check that the modules import is correct. If you've done this procedure and it still doesn't work, post your code here so we can take a look.

Parveen-Mothsara commented 2 years ago

@vilsonei CheckNumberStatus not working ,its callback always in pending state.please help.

@Parveen-Mothsara compare your API with this one, check that the modules import is correct. If you've done this procedure and it still doesn't work, post your code here so we can take a look.

Thanks @vilsonei its work for me you are a true gem.

pablodosreis commented 2 years ago

I recommend this project.

https://github.com/wppconnect-team/wa-js

I've migrate for them, the developers are really fast in resolve the problems on new versions. And there is a way to use old versios while new versions are witout support

Parveen-Mothsara commented 2 years ago

Hi @vilsonei can you help me to Download media from incoming message.. How we use downloadFileWithCredentials or downloadFile.

Parveen-Mothsara commented 2 years ago

Hi @vilsonei can you help me to Download media from incoming message.. How we use downloadFileWithCredentials or downloadFile.

Hi @vilsonei Please reply,I need this..