Giter Club home page Giter Club logo

whatsapp-web.js's Introduction


wwebjs.dev Guide


npm Depfu WhatsApp_Web 2.2346.52 Discord server


About

A WhatsApp API client that connects through the WhatsApp Web browser app

The library works by launching the WhatsApp Web browser application and managing it using Puppeteer to create an instance of WhatsApp Web, thereby mitigating the risk of being blocked. The WhatsApp API client connects through the WhatsApp Web browser app, accessing its internal functions. This grants you access to nearly all the features available on WhatsApp Web, enabling dynamic handling similar to any other Node.js application.

Important

It is not guaranteed you will not be blocked by using this method. WhatsApp does not allow bots or unofficial clients on their platform, so this shouldn't be considered totally safe.

Links

Installation

The module is now available on npm! npm i whatsapp-web.js

Note

Node v18+ is required.

QUICK STEPS TO UPGRADE NODE

Windows

Manual

Just get the latest LTS from the official node website.

npm

sudo npm install -g n
sudo n stable

Choco

choco install nodejs-lts

Winget

winget install OpenJS.NodeJS.LTS

Ubuntu / Debian

curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash - &&\
sudo apt-get install -y nodejs

Example usage

const { Client } = require('whatsapp-web.js');

const client = new Client();

client.on('qr', (qr) => {
    // Generate and scan this code with your phone
    console.log('QR RECEIVED', qr);
});

client.on('ready', () => {
    console.log('Client is ready!');
});

client.on('message', msg => {
    if (msg.body == '!ping') {
        msg.reply('pong');
    }
});

client.initialize();

Take a look at example.js for another examples with additional use cases.
For further details on saving and restoring sessions, explore the provided Authentication Strategies.

Supported features

Feature Status
Multi Device
Send messages
Receive messages
Send media (images/audio/documents)
Send media (video) (requires Google Chrome)
Send stickers
Receive media (images/audio/video/documents)
Send contact cards
Send location
Send buttons (DEPRECATED)
Send lists (DEPRECATED)
Receive location
Message replies
Join groups by invite
Get invite for group
Modify group info (subject, description)
Modify group settings (send messages, edit info)
Add group participants
Kick group participants
Promote/demote group participants
Mention users
Mention groups
Mute/unmute chats
Block/unblock contacts
Get contact info
Get profile pictures
Set user status message
React to messages
Create polls
Vote in polls 🔜
Communities 🔜
Channels 🔜

Something missing? Make an issue and let us know!

Contributing

Feel free to open pull requests; we welcome contributions! However, for significant changes, it's best to open an issue beforehand. Make sure to review our contribution guidelines before creating a pull request. Before creating your own issue or pull request, always check to see if one already exists!

Supporting the project

You can support the maintainer of this project through the links below

Disclaimer

This project is not affiliated, associated, authorized, endorsed by, or in any way officially connected with WhatsApp or any of its subsidiaries or its affiliates. The official WhatsApp website can be found at whatsapp.com. "WhatsApp" as well as related names, marks, emblems and images are registered trademarks of their respective owners. Also it is not guaranteed you will not be blocked by using this method. WhatsApp does not allow bots or unofficial clients on their platform, so this shouldn't be considered totally safe.

License

Copyright 2019 Pedro S Lopez

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this project except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

whatsapp-web.js's People

Contributors

alechkos avatar aliyss avatar antoineschaller avatar axeemhaider avatar caioagiani avatar dependabot[bot] avatar depfu[bot] avatar elhumbertoz avatar gabriel-tandil avatar github-actions[bot] avatar jtouris avatar jurajmatus avatar leftbrasil avatar lucasrosa90 avatar mpirescarvalho avatar mrfelipemartins avatar pedroslopez avatar purpshell avatar rc047 avatar ricardoapaes avatar roigreenberg avatar sahalmoidu avatar schwartzblat avatar shirser121 avatar stefanfuchs avatar tofers avatar tuyuribr avatar victormga avatar wictornogueira avatar wwebjs-bot avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

whatsapp-web.js's Issues

Thumbnails for media messages

Currently the thumbnail is not send with images resulting in a blank preview for the recipient.

Also need to add thumbnail for PDF(s) and Hyperlinks

Unable to use .getContacts()

Hi everyone!

When I call getContacts() method on client, I get this error :

(node:8700) UnhandledPromiseRejectionWarning: Error: Evaluation failed: TypeError: Cannot read property 'serialize' of undefined at Object.window.WWebJS.getContactModel (__puppeteer_evaluation_script__:125:27) at Object.window.WWebJS.getContact (__puppeteer_evaluation_script__:144:30) at __puppeteer_evaluation_script__:2:34 at ExecutionContext._evaluateInternal (C:\Users\X\Documents\MyPROJECTS\LPP\node_modules\puppeteer\lib\ExecutionContext.js:122:13) at runMicrotasks (<anonymous>) at processTicksAndRejections (internal/process/task_queues.js:85:5) at async ExecutionContext.evaluate (C:\Users\X\Documents\MyPROJECTS\LPP\node_modules\puppeteer\lib\ExecutionContext.js:48:12) at async Client.getContactById (C:\Users\X\Documents\MyPROJECTS\LPP\node_modules\whatsapp-web.js\src\Client.js:326:23) at async C:\Users\X\Documents\MyPROJECTS\LPP\server.js:117:15

Any help? Thank you!

UnhandledPromiseRejectionWarning: Error: Failed to launch the browser process! in Ubuntu

Could someone tell me how do I use this api on my digital ocean vps? You are giving this error.

(node:10756) UnhandledPromiseRejectionWarning: Error: Failed to launch the browser process!
[0214/135926.657963:ERROR:zygote_host_impl_linux.cc(89)] Running as root without --no-sandbox is not supported. See https://crbug.com/638180.

TROUBLESHOOTING: https://github.com/puppeteer/puppeteer/blob/master/docs/troubleshooting.md

at onClose (/root/guiseuguia/node_modules/puppeteer/lib/Launcher.js:750:14)
at Interface.<anonymous> (/root/guiseuguia/node_modules/puppeteer/lib/Launcher.js:739:50)
at Interface.emit (events.js:228:7)
at Interface.close (readline.js:402:8)
at Socket.onend (readline.js:180:10)
at Socket.emit (events.js:228:7)
at endReadableNT (_stream_readable.js:1185:12)
at processTicksAndRejections (internal/process/task_queues.js:81:21)

(node:10756) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:10756) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Whatsapp modules

Now project uses moduleRaid to fetch api of whatsapp, but I cant find modules like MediaCollection and UserConstructor through mR.findModule() it returns empty array. I need them to send pics, or how can I send images? Thanks in advance, @pedroslopez

Is it possible to stop bot responses after responding the first time?

Is it possible to make the bot respond to a command only the first time the person uses it?
In the example below, every message that another person keeps that is "Hi", the bot will reply with "Hello", I wanted to know if it is possible to make him reply to that message only the first time no more.

client.on('message', async msg => {
     if (msg.body == 'Hi') {
         client.sendMessage(msg.from, "Hello");
     }
});

Send images

Do you have the project to send ready-made images?

Fix setting group properties (subject, description)

The functions setSubject and setGroupDesc have been removed from the Chat model. A workaround needs to be implemented, possibly with the Store.Wap.setGroupDescription and Store.Wap.setGroupProperty functions.

i cant run after qr login ok

  • ------------------- Console output -------------------**
    QR 1@htAEW3G+2IPejlXnUTtgbAgV6+QKD+YSsPZuppm/K0KPg5RRiPU7UVQF,rm+1iMFAkKzEWETbxI0J8HNDOt3prpSL9RkD7lRfakU=,Vm79d6BycCHJToOphPq28Q==
    (node:2432) UnhandledPromiseRejectionWarning: Error: Evaluation failed: TypeError: Cannot read property 'default' of undefined
    at puppeteer_evaluation_script:7:162
    at ExecutionContext._evaluateInternal (C:\Servicios\Modulos\node_modules\puppeteer\lib\ExecutionContext.js:122:13)
    at processTicksAndRejections (internal/process/task_queues.js:93:5)
    at async ExecutionContext.evaluate (C:\Servicios\Modulos\node_modules\puppeteer\lib\ExecutionContext.js:48:12)
    at async Client.initialize (C:\Servicios\Modulos\bot-whatsapp\src\Client.js:80:9)
    -- ASYNC --
    at ExecutionContext. (C:\Servicios\Modulos\node_modules\puppeteer\lib\helper.js:111:15)
    at DOMWorld.evaluate (C:\Servicios\Modulos\node_modules\puppeteer\lib\DOMWorld.js:112:20)
    at runMicrotasks ()
    at processTicksAndRejections (internal/process/task_queues.js:93:5)
    -- ASYNC --
    at Frame. (C:\Servicios\Modulos\node_modules\puppeteer\lib\helper.js:111:15)
    at Page.evaluate (C:\Servicios\Modulos\node_modules\puppeteer\lib\Page.js:827:43)
    at Page. (C:\Servicios\Modulos\node_modules\puppeteer\lib\helper.js:112:23)
    at Client.initialize (C:\Servicios\Modulos\bot-whatsapp\src\Client.js:80:20)
    at runMicrotasks ()
    at processTicksAndRejections (internal/process/task_queues.js:93:5)
    (node:2432) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
    (node:2432) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

¿whats is this?

Multiple sessions

I'm trying to initialize the script in multiple sessions, does anyone have any tips?

const {Client} = require(`./1.0.1/index`);
const fs = require(`fs`);

const session = function (number) {

	console.log('number', number);

	const client = new Client({
		puppeteer: {
			headless: false,
			userDataDir: __dirname + `/${number}`,
			args: ['--no-sandbox']
		},
		session: function () {
			if (fs.existsSync(`./${number}.json`))
				return require(`./${number}.json`);
			else return false;
		}
	});

	client.initialize();

	client.on(`qr`, (qr) => {
		console.log('qr', qr);
	});

	client.on(`authenticated`, (session) => {
		if (!fs.existsSync(`./${number}.json`)) {
			fs.writeFile(`./${number}.json`, JSON.stringify(session), function (err) {
				if (err) console.log(err);
				else console.log(`Session stored`);
			});
		}
	});

	client.on(`auth_failure`, (msg) => {
		console.log(`auth_failure`, msg);
	});

	client.on(`ready`, () => {
		console.log(`ready`);
	});

	client.on(`message`, async msg => {
		console.log('message', msg)
	});

	client.on(`disconnected`, (reason) => {
		console.log(`disconnected`, reason);
	});


};

new session('phone-number');

Restore session

I'm trying to restore the WhatsApp Session, I found that most of data is saved in the localStorage and a little part is on cookies

I obtained the cookies using the dev tools functions because there are HttpOnly, and it can't be obtained through normal methods

async cookies() {
    const client = await this.pupPage.target().createCDPSession();
    let r = await client.send('Network.getAllCookies');
    return r.cookies;
}

But I'm unable to apply them, I'd tried with

page.setCookie()

But isn't working

Web server and Client

Is it possible to run the library on a web server and have a client interface on the desktop?

In this case, the chromium instance would be on the desktop.

error when installing (This is related to npm not being able to find a file.)

is giving this error when using the command npm i whatsapp-web.js

PS C:\Users\Evandro\Desktop\PROJETOS> npm i whatsapp-web.js
npm ERR! code ENOENT
npm ERR! syscall spawn git
npm ERR! path git
npm ERR! errno ENOENT
npm ERR! enoent Error while executing:
npm ERR! enoent undefined ls-remote -h -t https://github.com/pixeldesu/moduleRaid.git
npm ERR! enoent
npm ERR! enoent
npm ERR! enoent spawn git ENOENT
npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Evandro\AppData\Roaming\npm-cache\_logs\2020-02-21T14_03_39_863Z-debug.log

Problem when I reload the page and the window.Store variable the instance is removed

I greet Pedro lopez, yesterday you talk to me about the fact that I cannot refresh the browser due to the fact that the instance was erased in memory, now as I can simulate that from low, I mean working underneath all the actions that I want to do For example, the other day I talked to you on Twitter, how can I start the chat conversation, but you still haven't worked that method because of the fact that it is very busy. as I can simulate that page by console and execute the actions below what I want it to do. For example, I want to consume by the method I get a request and that that request I simulate from under that page and then I do all the kind of actions that I want to do, I don't know if I understand myself. also how can I fill in the window.Store variable again, because there has to be a way to do hehehe. @pedroslopez

Send Online Status

Online presence should be sent out so that receivers can get accurate last seen time

Is it possible to create submenus?

I would like to know if it is possible to create submenus, for example:

1 - news
2 - support
3 - ...

you can create other menus within each number of that

Sending media

Hi all, in last build cannot send pics, it throws error

Error: upload failed: media entry was not created

How to reproduce with example.js?

  1. Send Pic to the bot
  2. Reply to this pic with reply text !resendmedia

How to delete or archive a chat?

Hi! It's amazing how this project is growing.

I need to be able to archive or delete conversations. I don't find this feature implemented but it would be important because when there are a lot of conversations the page takes a long time to load and sometimes the timeouts expire.

Best regards
Gabriel

The integration stopped working

The integration stopped working

Yesterday it didn't connect and returned an error that said "Protocol error" among other things, but at the moment I didn't copy the trace.

Today it still doesn't work but it no longer emits that error
I guess there have been changes to WhatsApp web

QR RECEIVED null

I have used example.js but the qr is null, anyone have seen like this ?

My advice

I use this solution too (not yours but using Store).
If you plan to distribute this for any people on github, you should be aware that whatsapp can easily identify that you`re using Pupeteer for automation AND using the Store.

We use this method since 2017, and yes, using only as a chatbot, and still getting banned ...

An real-life example is MGP25 with his api, ( i know it connects directly to whatsapp servers and etc ). They know about him, whatsapp told about him in a anti-spam conference ...

So. If i was you, i would consider keeping this repository private, it garantees that this method will be available longer.

Dont read me wrong ;) as i said, just a advice

Read receipts.

Is there a way to fetch the read receipt information from a message id?

The information may be something like;

  1. SENT
  2. DELIVERED
  3. READ

Unable to use .getState()

Hello

When I call getState() method on client, I get this error :

UnhandledPromiseRejectionWarning: TypeError: Can not read property 'evaluate' of null at Client.getState (..\node_modules\whatsapp-web.js\src\Client.js:389:35)

Is it possible than i'm calling getState wrong way ?

client.getState().then((data) => { 
        console.log(data)
    });

return await this.pupPage.evaluate(() => {

Using whatsapp-web on Linux server

pt-br
Boa tarde, gostaria de rodar em um servidor ubuntu, tem como iniciar a aplicação passando somente o objeto de sessão, sem ler o código QR?
se sim, como fazer?

en-us
Good afternoon, I would like to run on a ubuntu server, can I start the application by passing only the session object, without reading the QR code?
If so, how?

Simulate '...typing' in the chat. sendChatstateComposing

Code used in the sulla-hotfix project https://github.com/smashah/sulla/

{ id: "WapQuery", conditions: (module) => (module.queryExist) ? module : ((module.default && module.default.queryExist) ? module.default : null) },

/**

  • Simulate '...typing' in the chat.
  • @param {string} chatId '[email protected]'
  • @param {boolean} on true to turn on similated typing, false to turn it off //you need to manually turn this off.
    */
    window.WAPI.simulateTyping = async function (chatId, on) {
    if (on) await Store.WapQuery.sendChatstateComposing(chatId)
    else await Store.WapQuery.sendChatstateComposing(chatId)
    };

Whatsapp Js API SetUp

Hi, i am trying to setup this whatsapp API Javascript project.Below is how i setup my javascript code but i am getting no response. Is there anyone willing to help me or with a solution. Please help me i want to catch up with you.

`<script src="https://github.com/pedroslopez/whatsapp-web.js.git"></script>

<script> const { Client } = require('whatsapp-web.js'); const client = new Client(); client.on('qr', (qr) => { // Generate and scan this code with your phone console.log('QR RECEIVED', qr); }); client.on('ready', () => { console.log('Client is ready!'); }); client.on('message', msg => { if (msg.body == '!ping') { msg.reply('pong'); } }); client.initialize(); </script>

`

You can come to my whatsapp inbox for personal inboxassistance if you don't mind. https://wa.me/263783059999

Memory Optimization Tips

What are some of the memory and CPU optimizations we could do maybe in terms of puppeteer flags and other for running this library at scale?
Let's say the use case requires to keep the user to be logged in most of the time say 24/7 from the server side of things to keep all incoming and outgoing messages syncing to a DB and suppose we are using an EC2 instance for hosting the application.
Also, Is using some other hosted service like browserless something you guys would recommend? I am really new to headless browser space and automation using them in general.

author is undefined

When I receive a message the author is undefined even if they are in my contacts list

QR Code updated every 30 seconds

I would like to know the possibility of obtaining the updated QR Code without the need to restart the script.

As there is a listening for 'qr', I think he should forward new events as soon as he detects a new QR Code.

Remove group participants

How do I get an object of type GroupChat to be able to remove participants from the group?

I tried this:

let group = await client.getChatById("[email protected]");
await group.removeParticipants(["...","..."])

//Error: Evaluation failed: TypeError: Cannot read property 'removeParticipants' of undefined

Adding a .editorconfig

Just a suggestion but adding a definitive config file for editing would make editing and pushing changes a lot easier. -> spaces / tabs

How to read old messages

Hi, I need to read the an amount of latest messages from a chat.
This amount can be 50 for sample.
These messages can be new or old.
I rave trying some samples posted here as:
loadAndGetAllMessagesInChat, loadEarlierMessagesTillDate, loadAllEarlierMessages ans similares, but
nothing is working.
Is it possible?
Does someone could post a sample?

After Login i need a help

I started the project and logged in to Whatsapp.
The project is responding to messages.
But how do I send a message? Do I send the message through the console?

https://prnt.sc/r38ly1

Thank you for your help.

Changings in web whatsapp

Looks like Web Whatsapp classes has been changed, moreover here is an error with injecting modules, to be exact the error is here store_id = modules[key].id.replace(/"/g, '"');, property id is not defined. @pedroslopez Can you help with it?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.