GithubHelp home page GithubHelp logo

chrishubert / whatsapp-api Goto Github PK

View Code? Open in Web Editor NEW
411.0 22.0 200.0 991 KB

This project is a REST API wrapper for the whatsapp-web.js library, providing an easy-to-use interface to interact with the WhatsApp Web platform.

Home Page: https://www.christophehubert.com

License: Other

Dockerfile 0.50% JavaScript 99.50%
api-rest docker whatsapp api whatsapp-api whatsapp-automation whatsapp-bot whatsapp-web-api

whatsapp-api's Introduction

WhatsApp REST API

REST API wrapper for the whatsapp-web.js library, providing an easy-to-use interface to interact with the WhatsApp Web platform. It is designed to be used as a docker container, scalable, secure, and easy to integrate with other non-NodeJs projects.

This project is a work in progress: star it, create issues, features or pull requests ❣️

NOTE: I can't guarantee you will not be blocked by using this method, although it has worked for me. WhatsApp does not allow bots or unofficial clients on their platform, so this shouldn't be considered totally safe.

Table of Contents

1. Quick Start with Docker

2. Features

3. Run Locally

4. Testing

5. Documentation

6. Deploy to Production

7. Contributing

8. License

9. Star History

Quick Start with Docker

dockeri.co

  1. Clone the repository:
git clone https://github.com/chrishubert/whatsapp-api.git
cd whatsapp-api
  1. Run the Docker Compose:
docker-compose pull && docker-compose up
  1. Visit http://localhost:3000/session/start/ABCD

  2. Scan the QR on your console using WhatsApp mobile app -> Linked Device -> Link a Device (it may take time to setup the session)

  3. Visit http://localhost:3000/client/getContacts/ABCD

  4. EXTRA: Look at all the callbacks data in ./session/message_log.txt

Quick Start

Features

  1. API and Callbacks
Actions Status Sessions Status Callbacks Status
Send Image Message Initiate session Callback QR code
Send Video Message Terminate session Callback new message
Send Audio Message Terminate inactive sessions Callback status change
Send Document Message Terminate all sessions Callback message media attachment
Send File URL Healthcheck
Send Button Message Local test callback
Send Contact Message
Send List Message
Set Status
Send Button With Media
Is On Whatsapp?
Download Profile Pic
User Status
Block/Unblock User
Update Profile Picture
Create Group
Leave Group
All Groups
Invite User
Make Admin
Demote Admin
Group Invite Code
Update Group Participants
Update Group Setting
Update Group Subject
Update Group Description
  1. Handle multiple client sessions (session data saved locally), identified by unique id

  2. All endpoints may be secured by a global API key

  3. On server start, all existing sessions are restored

  4. Set messages automatically as read

  5. Disable any of the callbacks

Run Locally

  1. Clone the repository:
git clone https://github.com/chrishubert/whatsapp-api.git
cd whatsapp-api
  1. Install the dependencies:
npm install
  1. Copy the .env.example file to .env and update the required environment variables:
cp .env.example .env
  1. Run the application:
npm run start
  1. Access the API at http://localhost:3000

Testing

Run the test suite with the following command:

npm run test

Documentation

API documentation can be found in the swagger.json file. See this file directly into Swagger Editor or any other OpenAPI-compatible tool to view and interact with the API documentation.

This documentation is straightforward if you are familiar with whatsapp-web.js library (https://docs.wwebjs.dev/) If you are still confused - open an issue and I'll improve it.

Also, there is an option to run the documentation endpoint locally by setting the ENABLE_SWAGGER_ENDPOINT environment variable. Restart the service and go to /api-docs endpoint to see it.

By default, all callback events are delivered to the webhook defined with the BASE_WEBHOOK_URL environment variable. This can be overridden by setting the *_WEBHOOK_URL environment variable, where * is your sessionId. For example, if you have the sessionId defined as DEMO, the environment variable must be DEMO_WEBHOOK_URL.

By setting the DISABLED_CALLBACKS environment variable you can specify what events you are not willing to receive on your webhook.

Scanning QR code

In order to validate a new WhatsApp Web instance you need to scan the QR code using your mobile phone. Official documentation can be found at (https://faq.whatsapp.com/1079327266110265/?cms_platform=android) page. The service itself delivers the QR code content as a webhook event or you can use the REST endpoints (/session/qr/:sessionId or /session/qr/:sessionId/image to get the QR code as a png image).

Deploy to Production

  • Load the docker image in docker-compose, or your Kubernetes environment
  • Disable the ENABLE_LOCAL_CALLBACK_EXAMPLE environment variable
  • Set the API_KEY environment variable to protect the REST endpoints
  • Run periodically the /api/terminateInactiveSessions endpoint to prevent useless sessions to take up space and resources(only in case you are not in control of the sessions)

Contributing

Please read CONTRIBUTING.md for details on our code of conduct, and the process for submitting pull requests to us.

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 https://whatsapp.com. "WhatsApp" as well as related names, marks, emblems and images are registered trademarks of their respective owners.

License

This project is licensed under the MIT License - see the LICENSE.md file for details.

Star History

Star History Chart

whatsapp-api's People

Contributors

andersonlima47 avatar autodepo avatar avoylenko avatar chrishubert avatar dependabot[bot] avatar khsalem95 avatar mkhleel avatar ruanfernandes avatar snyk-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

whatsapp-api's Issues

Bulk Message

Can this API supply bulk message with delay by default?

Documentation improvements

hello, I did not find these things in the documentation, can you tell? everything I tried didn't work either, can you help with easas 3 questions?

How can I send a message to a number?

How can I send a message to a group?

how can i create a group?

Set webhook url per session?

Hello, thanks for putting this together, and sorry my dumb questions below (Im more used to "MyZap api").

If I understand correctly, the webhook url is stored in the .env, and there is no endpoint or way to update the .env webhook urls while the node app is running, right?

I ask this because my use case is several clients with unique, optional, webhook urls, as its used in MyZap and some others...

For now my osha solution is to route every client to BASE_WEBHOOK_URL, and then re-route them again individually, unless Im missing something as big as a house?

Using Webhook

Hi Chris,

how we use other webhook.site alternative like

https://github.com/syifarahmat/webhook

what can i do? after.

Versionning

Thanks for the great repo!!!
I'd suggest two things:

  • create git tags for every release? So, we that we can compare changes between versions
  • create tags for docker images, so that we can use old image versions as sometimes the lastest one could fail
image

Possibility to send message with media at same time

My suggestion is to add additional case to make possible to send message with media:

clientController.js

case 'MessageWithMedia': {
        const { mimetype, data, filename, filesize } = options.media
        options.media = new MessageMedia(mimetype, data, filename, filesize)
        messageOut = await client.sendMessage(chatId, content, options)
        break
}

Session not connected

After setting up a new server from scratch, logging in and then sending a message I get the error "session_not_connected".

In the webhook it does not show the "authenticated" and "ready" messages and stops at the message "A carregar as suas conversas".

Web Hook Not Receiving on Creation

When I run http://localhost:3000/api/startSession/ABCD QR not Received in Callback. but response showing {"success":true,"message":"Session initiated successfully"}
Please guide me how i can solve the issue.

I setup ENV in Production like Below -

# Application
PORT=3000 # OPTIONAL
API_KEY=your_global_api_key_here # OPTIONAL
BASE_WEBHOOK_URL=https://webhook.site/9d706220-f9cb-4a59-97c9-09bcfa6caccd # MANDATORY
ENABLE_LOCAL_CALLBACK_EXAMPLE=FALSE # OPTIONAL, NOT RECOMMENDED FOR PRODUCTION
MAX_ATTACHMENT_SIZE=10000000 # IN BYTES

Get User Bio ?

Hi,
Is it posssible through a contactId that we haven't chatted with, get their Bio ?
On web.whatsapp.com when I search for a new phone number, that I check their profile, sometime I can see this :
FWqXQvg

I did try :

curl -X POST http://localhost:3000/contact/getAbout/ABCD
-H "Content-Type: application/json"
-d '{"contactId": "{phone}@c.us"}'

I get: {"success":true,"result":{}}
(nothing in the result property)

Thank you !

Can no longer send messages

After I updated to the latest docker image, I can no longer send messages. I always receive {"success":false,"error":"session_not_connected"} even I restarted the session many times for different devices

Idle session auto-termination

Sir,
When i create an Instance it continue send QR code in call back in every second . it stop when Instance is Deleted.

My point is:
After creating an instance , After 1-2 minute , if QR not scan within 2 minute , this will go to sleep mode and will not send any Call back for that QR of specific Instance.

Later if need to Scan QR again , we have to call a api and then again QR receving will start.

It may help us to Reduce server Load

Always get session_not_connected

Hello,

I don't know why after success scan barcode then wait until some minutes then try to call session/status/:sessionId always get response below.

image

Running with docker.

Could you help me?

Thanks.

convert qr_code from webhook

How do I convert the qr_code that comes in the webhook to a qr_code in a format that I can scan on the device?

QR Return in Session/Start Response

Expected Behavior:
When initiating a session through the /start endpoint, the response should include a QR code that users can scan with their devices to complete the session setup process.

Current Behavior:
Currently, the /start endpoint response does not include a QR code for session setup, which makes it less intuitive for users to complete the process.

Steps to Reproduce:

  1. Make a POST request to the /start endpoint with the required parameters.
  2. Check the response received from the endpoint.

Proposed Solution:
Include a QR code image in the response JSON of the /start endpoint. The QR code should contain a unique identifier or session token that can be used by the client to confirm and finalize the session setup. This would improve user experience and streamline the process.

Labels:

  • enhancement
  • API

ARM cloud server

In Ampere A1 Compute

I got this message

ERROR: for app no matching manifest for linux/arm64/v8 in the manifest list entries
ERROR: no matching manifest for linux/arm64/v8 in the manifest list entries

Group Messages and Logout

When I terminate a session, it doesn't seem to logout of the session on the whatsapp, it still shows on mobile app as paired. is that right or am I doing something wrong?

also how do I fetch group messages, I haven't been able to find a way, when I use a serialized chatid(###########-##########@g.us) the fetchMessages doesn't like it and throws a 404 error. is there a way of doing it that I missed?

thanks for the awesome project!

Can we Use WebSocket to Reduce Chrome Uses

Sir,
Chrome Take High Memory resources. some plugings using WebSocket. Not running Selenium or Chromimum saves you like half a gig of ram. How it can be possible here ?

Buttons

I was testing the api today, I thought it was really cool, congratulations, I would like to ask a question in case I can't send the buttons, am I doing something wrong or it still doesn't work? my wpp is business
image

Puppeteer Evaluation Failed

I encountered the following error when trying to send a message:

{"success": false, "error": "Evaluation failed: TypeError: Cannot read properties of undefined (reading 'createWid')\n at __puppeteer_evaluation_script__:2:53"}

Add a contact

Hey,

I'm looking to know if a phone number is in-use on Whatsapp and get their profile picture. I can do that on my phone but I've been interested to know if it's possible with your library ?
I've looked at your swagger.json but I don't think I'm seeing something related. I did see /client/getProfilePicUrl/{sessionId} but I'm guessing anything starting with /client/ is for our account and not someone else account so I can't use it to lookup someone else profile's picture.

Something that seems like it could be what I'm looking for in your README, is "Is On Whatsapp ?" feature, however I'm not seeing something anything about it in the swagger.json

Impossible to get session

Today starting the server:

> [email protected] start c:\node\WAppAPI\whatsapp-api
> node server.js

Server running on port 8800
existing session detected session
Failed to send new message webhook: session loading_screen Request failed with status code 404 { percent: 0, message: 'WhatsApp' }
Failed to send new message webhook: session loading_screen Request failed with status code 404 { percent: 100, message: 'WhatsApp' }
Failed to send new message webhook: session authenticated Request failed with status code 404 undefined
Failed to send new message webhook: session ready Request failed with status code 404 undefined

After a while, it start receiving (very old) messages, but it's impossible to send one, with error:

Session state: session CONNECTED
TypeError: data.id.id.substring is not a function
    at Message._patch (c:\node\WAppAPI\whatsapp-api\node_modules\whatsapp-web.js\src\structures\Message.js:91:75)
    at new Message (c:\node\WAppAPI\whatsapp-api\node_modules\whatsapp-web.js\src\structures\Message.js:18:24)
    at Client.sendMessage (c:\node\WAppAPI\whatsapp-api\node_modules\whatsapp-web.js\src\Client.js:699:16)
    at runMicrotasks (<anonymous>)
    at processTicksAndRejections (internal/process/task_queues.js:95:5)
    at async sendMessage (c:\node\WAppAPI\whatsapp-api\src\controllers\clientController.js:29:22)

It was working until yesterday.

Create new future Reload popper or tabs session or services

Hi, can you tell me if it is possible to implement a new method or algorithm for checking the validity (activity of a particular session) in my practice there are cases when the container works, there are no errors in the logs, but when a request for session status is thrown out, it is simply expired after the waiting timeout, this applies to all aspects related to session administration, there are also cases when there are several sessions on one service, but one of which stops working in this way, while the other works fine, so the question is whether it is possible to implement a method of restarting a session or service of everything, or advice from your side?

Question regarding terminateInactiveSessions in production

Hi there, thanks for the amazing build. Am running well but need some feedbacks on the production.

for Production, it stated
Run periodically the /api/terminateInactiveSessions endpoint to prevent useless sessions to take up space and resources

in My Case, I'm only running 1 whatsapp instance using 1 session-id. Send message occasionally (probably 1-2 message per day).
Do I have to run that periodically?

At the moment, I only started the instance once, and will keep running unless server restart or so.

QRCODE

hello!

I was able to install it, but I am not able to show the QRCODE in a URL so that it can be scanned, how could I do that?

thanks.

Text Button

Sir,
Can you please add Text Button with Message ? If possible please do it

Prod Deployment issue

After deployed prod it is not working always give you

{
"success": false,
"message": "qr code not ready or already scanned"
}

want to ask

the development idea is really cool,

but I tried to run tests with the methods in swagger but many are still confusing or showing errors,

Does the one marked with ✅ mean it's ready to use?
or how?

I ask for an explanation..

I hope we'll see these features soon

Great job, Christophe! I hope we'll see these benefits soon."

Send Image Message
Send Video Message
Send Audio Message
Send Document Message
Send File URL
Send Button(Template) Message
Send Contact Message
Send List Message
Set Status
Send Button With Media
Is On Whatsapp?
Download Profile Pic
User Status
Block/Unblock User
Update Profile Picture

Create Group
Leave Group
All Groups
Invite User
Make Admin
Demote Admin
Group Invite Code
All Groups
Update Group Participants
Update Group Setting
Update Group Subject
Update Group Description

Thank you for your effort.

QRCode auth in Web

Hi, i would like to suggest to implement qrcode visibility in web browser (when accessing session start endpoint).
This project apparently works well on CasaOS Home assistance, all based in docker compose applications.
This way, i cant see qrcode on docker startup.

Qrcode Routes

any plan to route the QRCode, than we use webhook?

Https is not Working

I'm trying develop with HTTPS but it's failed, forbiden status when i change to http, it's normal.

i'm trying running production mode with nodejs command

node server.js

WhatsApp messages not sending

Is anyone experiencing an issue with whatsapp messages stop sending about 2 days ago. IT was working fine all along and then 2 days ago messages keep failing. Any ideas?

Unexpected message is delivered

Hi,

In my logs I see that the following message is delivered every time I start a new session, what is that?

Failed to send new message webhook: ABCD media Request failed with status code 413 {
  messageMedia: MessageMedia {
    mimetype: 'video/mp4',
    data: 'AAAAHGZ0eXBtcD.....'
message: Message {
    _data: {
      id: [Object],
      body: '',
      type: 'video',
      t: 1690598727,
      notifyName: '',
      from: 'status@broadcast',
      to: '[email protected]',
      author: '[email protected]',

After decoding the above message, I see this:
image

Thanks,

/client/archiveChat/{session}

I cannot figure out how to archive a chat.
I tryed to read whatsapp-web.js documentation with no success.
Can you help me?

Docker Builds versioning

Hi @chrishubert, first of all - thx for your solution, it's good!

But, could you please add some tags for the builds on Docker Hub?
Smth like this:

      - name: Build and push
        uses: docker/build-push-action@v4
        with:
          push: true
          tags:  | 
             'chrishubert/whatsapp-web-api:latest'
             'chrishubert/whatsapp-web-api:${{ env.SHORT_REF_NAME }}_${{ env.SHORT_SHA }}

It will be more convenient to use on K8S.

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.