wa-automate-nodejs is the most advanced NodeJS library which provides a high-level API control to WA.
It is built using puppeteer, based on this python wrapper.
> npm i --save @open-wa/wa-automate
// import { create, Client } from '@open-wa/wa-automate';
const wa = require('@open-wa/wa-automate');
wa.create().then(client => start(client));
function start(client) {
client.onMessage(message => {
if (message.body === 'Hi') {
client.sendText(message.from, 'π Hello!');
}
});
}
After executing create()
function, @open-wa/wa-automate will create an instance of WA web. If you are not logged in, it will print a QR code in the terminal. Scan it with your phone and you are ready to go!
With the constant updates from WA. It is advisable to always use the latest version of @open-wa/wa-automate
.
Function | Description | Implemented |
---|---|---|
Receive message | β | |
Automatic QR Refresh | β | |
Send text | β | |
Get contacts | β | |
Get chats | β | |
Get groups | β | |
Get group members | β | |
Send contact | β | |
Get contact detail | β | |
Send Images (image) | β | |
Send media (audio, doc) | β | |
Send media (video) | β | |
Send stickers | β | |
Decrypt media (image, audio, doc) | β | |
Capturing QR Code | β | |
Multiple Sessions | β | |
[Last seen & isOnline (beta)] | β | |
π SEND LOCATION!! (beta) | β | |
Simulated '...typing' | β | |
Send GIFs! | β | |
Forward Messages | β | |
Listen to Read Receipts | β | |
Listen to Live Locations | β | |
Group participant changes | β | |
Create Groups | β | |
add, remove, promote, demote participants | β |
Checkout all the available functions here.
open-wa is at the forefront of open source WA developmentand runs on donations from backers. To encourage donations, backers have access to exclusive features with an Insiders Program license key.
Function | Description |
---|---|
setGroupToAdminsOnly |
Changes group setting so only admins can send messages |
setGroupEditToAdminsOnly |
Changes group setting so only admins can edit group info |
setProfilePic |
Change the host phones profile picture |
onRemovedFromGroup |
Detect when host phone is removed from a group |
onContactAdded |
Detect when host phone adds a new contact |
getCommonGroups |
Retreive all common groups between the host device and a conttact |
clearAllChats |
Easily clear memory by clearing all chats of all messages on the host device and WA Web |
sendReplyWithMentions |
Send a reply to a message with mentions |
onChatOpened |
Detect when a chat is selected in the UI |
Learn more about license keys.
There are 3 ways to start a chat with a new number:
-
You can send a special link to the person you want to start a chat with. This will open a conversation with your number on their phone. This way you can insure that they have explicitly started a conversation with you.
-
You can add this button to your website which, when clicked, will open a chat with you in the same way as above.
-
In order to unlock the functionality to send texts to unknown numbers through @open-wa/wa-automate itself, you will need a License key.
One License Key is valid for one number. Each License Key for this is Β£10 per month. Instructions below.
For now the process happens through Gumroad
How to get an License key:
-
Go to Gumroad.
-
Click on the type of license you require.
-
In the checkout, enter the host phone number you want to assign to the License Key (the one you will be using with open-wa, not your personal number) , along with the use case for this functionality and your github username. Please note, with this new system you'll only be able to change the number once.
-
Complete the checkout process.
-
You will instantly receive your License key on the screen and in your email.
-
Add licenseKey to your config:
...
create({
licenseKey: "..."
})
//or for multiple license keys to stack features.
create({
licenseKey: ["...","..."]
})
...
Notes:
- You can change the number assigned to a specific License Key once.
- In order to cancel your License Key, simply stop your membership.
- You can use multiple license keys for each host number.
- Apart from adding your licenseKey to your config, you will need to change nothing else in your code.
- An added benefit for members is priority on issues.
- License Key requests may be rejected.
You can clone this repo and run the demo, but you will need to use typescript/ts-node:
> git clone https://github.com/open-wa/wa-automate-nodejs.git
> cd wa-automate-nodejs
> npm i
> npm i -g ts-node typescript
> cd demo
> ts-node index.ts
An event is emitted every time the QR code is received by the system. You can grab hold of this event emitter by importing ev
import { ev } from '@open-wa/wa-automate';
const fs = require('fs');
ev.on('qr.**', async qrcode => {
//qrcode is base64 encoded qr code image
//now you can do whatever you want with it
const imageBuffer = Buffer.from(
qrcode.replace('data:image/png;base64,', ''),
'base64'
);
fs.writeFileSync('qr_code.png', imageBuffer);
});
You can see a live implementation of this on demo/index.ts
. Give it a spin! :D
In version v1.6.13^, you can now refresh the QR code every 10 seconds (you can change the interval).
create({
autoRefresh:false, //default to true
qrRefreshS:30 //please note that if this is too long then your qr code scan may end up being invalid. Generally qr codes expire every 15 seconds.
}).then(async client => await start(client));
As of v1.6.6^ you can now kill the session when required. Best practice is to manage trycatch-es yourself and kill the client on catch.
try{
...
await client.sendMessage(...
...
} catch(error){
client.kill();
//maybe restart the session then
}
When a user starts using WA web in a different browser, @open-wa/wa-automate will be left on a screen prompting you to click 'Use here'. As of v1.6.6^ you can now force the client to press 'Use here' everytime the state has changed to 'CONFLICT'. onStateChanged results in 'UNPAIRED', 'CONNECTED' or 'CONFLICT';
client.onStateChanged(state=>{
console.log('statechanged', state)
if(state==="CONFLICT") client.forceRefocus();
});
Here is a sample of how to decrypt media. This has been tested on images, videos, documents, audio and voice notes.
import { create, Client, decryptMedia } from '@open-wa/wa-automate';
const mime = require('mime-types');
const fs = require('fs');
function start(client: Client) {
client.onMessage(async message => {
if (message.mimetype) {
const filename = `${message.t}.${mime.extension(message.mimetype)}`;
const mediaData = await decryptMedia(message);
const imageBase64 = `data:${message.mimetype};base64,${mediaData.toString(
'base64'
)}`;
await client.sendImage(
message.from,
imageBase64,
filename,
`You just sent me this ${message.type}`
);
fs.writeFile(filename, mediaData, function(err) {
if (err) {
return console.log(err);
}
console.log('The file was saved!');
});
}
});
}
create().then(client => start(client));
It is always preferable to keep projects smaller than needed so you can now use a lightweight library called wa-decrypt for projects that do not need all of @open-wa/wa-automate.
You can install that using:
> npm i --save wa-decrypt
and import it like so:
import { decryptMedia } from 'wa-decrypt';
Learn more about wa-decrypt here
If you are having issues with decryption it may be due to the user agent being used by the decrypt method. You can remedy this by passing a custom user agent as a second parameter to the decrypt method. Now there is a convenience method on the WA class to allow you to easily get a compatible user agent shown below. This feature is available in v.1.5.8 and above.
...
const generatedUa = await client.getGeneratedUserAgent(); //you can optionally pass your custom user agent in here also getGeneratedUserAgent('...');
const mediaData = await decryptMedia(message,generatedUa);
...
Here is a sample of how to send media. This has been tested on images, videos, documents, audio and voice notes.
Interestingly sendImage has always worked for sending any type of file.
An example of sending a is shown in the Decrypting Media secion above also.
import { create, Client} from '@open-wa/wa-automate';
function start(client: Client) {
await client.sendFile('[email protected]',[BASE64 FILE DATA],'some file.pdf', `Hello this is the caption`);
}
create().then(client => start(client));
Please note sometimes short(<4s) voice notes sometimes do not decrypt properly and result in empty audio files.
If you intend to use video via @open-wa/wa-automate, you need to use a chrome instance with puppeteer instead of the default chromium instance. This is becase chromium does not have any relevant video codecs needed for new WA web video sending features.
You will need to make sure that you have a valid chrome instance on your machine then use the following to tell puppeteer where it can find your chrome isntance. The below demo is an example for mac & windows. For linux based hosts, you can find the chrome path with whereis google-chrome
, it should be something like /usr/bin/google-chrome
create({
// For Mac:
executablePath: '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
// For Windows:
// executablePath: 'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe',
}).then(client => start(client));
Extending the functionality of sending videos, version 1.4.2 brings with it the ability to send GIFs!!!! This was super annoying to figure out, as I was sent on a wild goose chase but it turned out that the answer was just 2 simple lines.
There are two ways to send GIFs - by Video or by giphy link.
- Sending Video as a GIF.
WA doesn't actually support the .gif format - probably due to how inefficient it is as a filetype - they instead convert GIFs to video then process them.
In order to send gifs you need to do the same (convert the gif to an mp4 file) then use the following method:
import { create, Client} from '@open-wa/wa-automate';
function start(client: Client) {
await client.sendVideoAsGif('[email protected]',[BASE64 Video FILE DATA],'some file.mp4', `Hello this is the caption`);
}
///IMPORTANT! Please make sure to point to your chrome installation and make sure your host has ffmpeg support
create({
// For Mac:
executablePath: '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
// For Windows:
// executablePath: 'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe',
}).then(client => start(client));
- Sending a Giphy Media Link
This is a convenience method to make it easier to send gifs from the website GIPHY. You need to make sure you use a giphy media link as shown below.
import { create, Client} from '@open-wa/wa-automate';
function start(client: Client) {
await client.sendGiphy('[email protected]','https://media.giphy.com/media/oYtVHSxngR3lC/giphy.gif', `Hello this is the caption`);
}
create({
executablePath: '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
}).then(client => start(client));
As of version 1.3.0 you can now send location!! You can't even do this in normal WA web interface.
You need to pass the following params:
- chat id: [email protected]
- latitude: '51.5074'
- longitude: '0.1278'
- location text: 'LONDON!'
Here's how you do it:
await client.sendLocation('[email protected]', '51.5074', '0.1278', 'LONDON!')
As of version 1.3.1 you can now simulate '...typing'
You need to pass the following params:
- chat id: [email protected]
- on: true or false
Note: You need to manually turn this off!!!
//start '...typing'
await client.simulateTyping('[email protected]',true)
//wait 3 seconds
//stop '...typing'
await client.simulateTyping('[email protected]',false)
Generally, after the 20th chat in your WA, getChat methods do not retreive the chat picture. You need to get these from the WA servers. This is how you do it in v1.6.6^:
client.getProfilePicFromServer('[email protected]')
As of version 1.5.1 you can now forward messages. This has been tested on most types of messages.
You need to pass the following params:
- chat to forward messages to : [email protected]
- messages: a single or array of message ids or message objects
- skipMyMessages: true or false, if true it will filter out messages sent by you from the list of messages, default false.
Note: You need to manually turn this off!!!
//forward messages
await client.forwardMessages('[email protected]',[...],true)
//forward single message by id
await client.forwardMessages('[email protected],"...",true)
As of version 1.6.17, you can now reply to specific messages.
...
/**
* @param to string chatid
* @param content string reply text
* @param quotedMsg string | Message the msg object or id to reply to.
*/
await client.reply('[email protected]','This is the reply',message);
...
As of v1.7.2 you can now create a new group. The first parameter is the group name, the second parameter is the contact ids to add as participants
...
client.createGroup('Cool new group','[email protected]') //you can also send an array of ids.
...
As of v1.7.0 you can now add, remove, promote & demote participants for groups. The first parameter is the chat id for the group. The second parameter is the number to which you are conducting the action.
...
client.addParticipant('[email protected]','[email protected]')
client.removeParticipant('[email protected]','[email protected]')
client.promoteParticipant('[email protected]','[email protected]')
client.demoteParticipant('[email protected]','[email protected]')
...
As of version 1.5.6 you can now listen in on changes to group participants. You can react to when participants are added and removed.
client.onParticipantsChanged("[email protected]", (participantChangedEvent:any) => console.log("participant changed for group", participantChangedEvent));
//participantChangedEvent returns
{
by: '[email protected]', //who performed the action
action: 'remove',
who: [ '[email protected]' ] //all the numbers the action effects.
}
This solution can result in some false positives and misfires however a lot of effort has been made to mitigate this to a reasonable level. Best practice is to maintian a seperate registry of participants and go from that.
As of version 1.7.21 you can now listen to live locations from a specific chat. You can see the liveLocation callback object here
client.onLiveLocation('[email protected]', (liveLocation) => {
console.log('Someone moved',liveLocation)
})
As of version 1.5.3 you can now listen in on the read state (or technically acknowledgement state) of the messages. As of writing the limitation is presumed to be on sent messages.
The callback you set returns the whole raw message object.
Here's how you do it.
client.onAck((msg:any) => console.log(msg.id.toString(),msg.body,msg.ack))
ack represents the acknoledgement state, of which there are 3.
1 => Message Sent (1 tick)
2 => Message Received by Recipient (2 ticks)
3 => Message Read Receipt Confirmed (2 blue ticks)
Note: You won't get 3 if the recipient has read receipts off.
If you want to kill the process after a certain amount of seconds due to an unscanned code, you can now set the qrTimeout parameter in the configuration object. You can also use authTimeout if you want to wait only a certain period of time to wait for the session to connect to the phone.
create({
qrTimeout: 30, //kills the session if the QR code is not scanned within 30 seconds.
authTimeout: 30 //kills the session if the session hasn't authentication 30 seconds (e.g If the session has the right credentials but the phone is off).
})
.then(client => start(client));
With v1.2.4, you can now run multiple sessions of @open-wa/wa-automate in the same 'app'. This allows you to do interesting things for example:
- Design and run automated tests for you WA bot.
- Connect two or more WA numbers to a single (or multiple) message handler(s)
- Use one client to make sure another one is alive by pinging it.
Please see demo/index.ts for a working example
NOTE: DO NOT CREATE TWO SESSIONS WITH THE SAME SESSIONID. DO NOT ALLOW SPACES AS SESSION ID.
import { create, Client} from '@open-wa/wa-automate';
function start(client: Client) {
...
}
create().then(client => start(client));
create({
sessionId:'another_session'
}).then(client => start(client));
You can then capture the QR Code for each session using the following event listener code:
//events are fired with the ev namespace then the session Id. e.g "qr.another_session"
//You can however use the wildcard operator with the new event listener and capture the session Id as a parameter instead.
ev.on('qr.**', async (qrcode,sessionId) => {
console.log("TCL: qrcode,sessioId", qrcode,sessionId)
//base64 encoded qr code image
const imageBuffer = Buffer.from(qrcode.replace('data:image/png;base64,',''), 'base64');
fs.writeFileSync(`qr_code${sessionId?'_'+sessionId:''}.png`, imageBuffer);
});
Since this project is built upon puppeteer, you can access the Puppeteer Page instance by referencing client.page
, and then therefore you can listen to any errors on the page like so:
client.page.on('error', _=>{
...
}
With v.1.2.6 you can now forward custom arguments through the library to puppeteer. This includes any overrides to the pupeteer config and a custom useragent.
Note: If you want to change the user agent but leave the puppeteer config the same then just pass {} to the pupeteer config. Also if you don't want to use a custom session then just use 'session' for the first argument.
As with session name segment, these are all optional parameters.
Why should you use a custom user agent?
Users of these WA injection libraries should use different user agents (preferably copy the one you have one your own pc) because then it makes it harder for WA to break the mecahnism to restart sessions for this library.
Setting up your client in headless:false
mode ensures you can easily visually debug any issues.
Example:
import { create, Client} from '@open-wa/wa-automate';
function start(client: Client) {
...
}
create().then(client => start(client));
//1st argument is the session name
//2nd argument is the puppeteer config override
//3rd argument is the user agent override
create({
headless: false,
customUserAgent: 'some custom user agent'
})
.then(client => start(client));
Since this is not an officially sanctioned solution it is temperamental to say the least. Here are some best practices:
- Keep the session alive
- Offload most work off of your @open-wa/wa-automate setup (i.e forward all events to a pubsub or something)
- Keep the phone nearby just in case you need to reauthenticate
- Use a chrome instance instead of the default chromium instance
- Use headless: false for easy & quick visual debugging
- Implement the unread messages functionality on creation of a session so you don't miss any messages upon any downtime.
- Implement a promise-queue
- Use a unique and valid custom user-agent
await
all @open-wa/wa-automate methods just in case- Do not run your s@open-wa/wa-automate instance on a Windows machine.
- Always kill the session safely upon error or SIGINT.
- Regularly restart your process to manage memory consumption
- If memory leaks continue to be an issue then use
cacheEnabled:false
in the config to disable the cache on the page.
import { create, Client} from '@open-wa/wa-automate';
const { default: PQueue } = require("p-queue");
const queue = new PQueue({
concurrency: 4,
autoStart:false
});
const proc = async message => {
//do something with the message here
console.log(message)
return true;
}
const processMessage = message => queue.add(()=>proc(message));
async function start(client: Client) {
const unreadMessages = await client.getAllUnreadMessages();
unreadMessages.forEach(processMessage)
...
await client.onMessage(processMessage);
queue.start();
}
create().then(client => start(client));
//1st argument is the session name
//2nd argument is the puppeteer config override
//3rd argument is the user agent override
create({
// For Mac:
executablePath: '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
// For Windows:
// executablePath: 'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe',
headless: false,
autoRefresh:true,
cacheEnabled:false,
customUserAgent: 'some custom user agent'
})
.then(client => start(client));
Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.
Hippocratic + Do Not Harm Version 1.0
This code is in no way affiliated with, authorized, maintained, sponsored or endorsed by WA or any of its affiliates or subsidiaries. This is an independent and unofficial software. Use at your own risk.
This distribution includes cryptographic software. The country in which you currently reside may have restrictions on the import, possession, use, and/or re-export to another country, of encryption software. BEFORE using any encryption software, please check your country's laws, regulations and policies concerning the import, possession, or use, and re-export of encryption software, to see if this is permitted. See http://www.wassenaar.org/ for more information.
The U.S. Government Department of Commerce, Bureau of Industry and Security (BIS), has classified this software as Export Commodity Control Number (ECCN) 5D002.C.1, which includes information security software using or performing cryptographic functions with asymmetric algorithms. The form and manner of this distribution makes it eligible for export under the License Exception ENC Technology Software Unrestricted (TSU) exception (see the BIS Export Administration Regulations, Section 740.13) for both object code and source code.