Code Monkey home page Code Monkey logo

whatsapp-api's Introduction



Telegram Group Whatsapp Group License Support Support

Project Structure

WhatsApp-Api-NodeJs

This code is an implementation of WhiskeySockets, as a RestFull Api service, which controls whatsapp functions.
With this one you can create multiservice chats, service bots or any other system that uses whatsapp. With this code you don't need to know javascript for nodejs , just start the server and make the language requests that you feel most comfortable with.

Infrastructure

1. Docker installation

  • First, let's install Docker. Docker is a platform that allows us to quickly create, test and deploy applications in isolated environments called containers.
curl -fsSL https://get.docker.com -o get-docker.sh
sudo sh get-docker.sh
sudo usermod -aG docker ${USER}

2. Installing the database

PostgreSql [required]

  • Now, we have configured our PostgreSQL database using Docker Compose.
  • Access your postgre manager and create a database.

compose from postgres

3. Nvm installation

curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
# or
wget -qO- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash

After finishing, restart the terminal to load the new information.

3.1 Nodejs installation

  • Installing Node.js using NVM, a version manager that allows us to switch between different versions of Node.js easily.
nvm install 20

4. pm2 installation

npm i -g pm2

5. Application startup

Cloning the Repository

git clone https://github.com/code-chat-br/whatsapp-api.git

Go to the project directory and install all dependencies.

Give preference to npm as it has greater compatibility.

cd whatsapp-api-v2

npm install
# or
npm install --force

6. Environment variables

See additional settings that can be applied through the env file by clicking here.

⚠️Attention⚠️: copy the .env.dev file to .env.

cp .env.dev .env

7. Prism ORM

  • We're going to use Prisma ORM to manage our database. Prisma simplifies database access and ensures operations are secure and easy to maintain.
  • Commands and Explanations:
    • In development environment: npx prisma migrate dev
      • We use migrate dev in development to automatically create and apply migrations, making working with the database easier.
    • In production environment: npx prisma migrate deploy
      • In production, we use migrate deploy to apply migrations in a controlled and secure way.
    • Data visualization: npx prisma studio
      • Prisma Studio is a visual tool that helps us manage and visualize bank data in an intuitive way.

Define the DATABASE_URL environment variable for the database deployment.

bash deploy_db.sh

Finally, run the command below to start the application:

npm run start:dev

npm run start:prod

# pm2
pm2 start 'npm run start:prod' --name CodeChat_API_v1.3.0

Swagger - OpenAPI 3.0.0

Authentication

You can define two authentication types for the routes in the env file. Authentications must be inserted in the request header.

  1. jwt: A JWT is a standard for authentication and information exchange defined with a signature.

Authentications are generated at instance creation time.

Note: There is also the possibility to define a global api key, which can access and control all instances.

App in Docker

After building the application, in the same directory as the files above, run the following command:

docker-compose up

Send Messages

Send Text
Send Buttons
Send Template
Send Media: audio - video - image - document - gif

base64: true
Send Media File
Send Audio type WhatsApp
Send Audio type WhatsApp - File
Send Location
Send List
Send Link Preview
Send Contact
Send Reaction - emoji

Postman collections

  • Run in Postman

Webhook Events

Name Event TypeData Description
QRCODE_UPDATED qrcode.updated json Sends the base64 of the qrcode for reading
CONNECTION_UPDATE connection.update json Informs the status of the connection with whatsapp
MESSAGES_SET message.set json Sends a list of all your messages uploaded on whatsapp
This event occurs only once
MESSAGES_UPSERT message.upsert json Notifies you when a message is received
MESSAGES_UPDATE message.update json Tells you when a message is updated
SEND_MESSAGE send.message json Notifies when a message is sent
CONTACTS_SET contacts.set json Performs initial loading of all contacts
This event occurs only once
CONTACTS_UPSERT contacts.upsert json Reloads all contacts with additional information
This event occurs only once
CONTACTS_UPDATE contacts.update json Informs you when the chat is updated
PRESENCE_UPDATE presence.update json Informs if the user is online, if he is performing some action like writing or recording and his last seen
'unavailable'
CHATS_SET chats.set json Send a list of all loaded chats
CHATS_UPDATE chats.update json Informs you when the chat is updated
CHATS_UPSERT chats.upsert json Sends any new chat information
GROUPS_UPSERT groups.upsert JSON Notifies when a group is created
GROUPS_UPDATE groups.update JSON Notifies when a group has its information updated
GROUP_PARTICIPANTS_UPDATE group-participants.update JSON Notifies when an action occurs involving a participant
'add'
NEW_TOKEN new.jwt JSON Notifies when the token (jwt) is updated

SSL

To install the SSL certificate, follow the instructions below.

Note

This code is in no way affiliated with WhatsApp. Use at your own discretion. Don't spam this.

This code was produced based on the baileys library and it is still under development.

Donate to the project.

Pix: 2b526ada-4ef4-4db4-bbeb-f60da2421fce

PicPay


whatsapp-api's People

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

whatsapp-api's Issues

Empty return for chat route

When having to list the chats, it returns empty.

Route: {{baseUrl}}/chat/findChats/{{instance}}

Return

[
{
"body": [],
"headers": {
"x-powered-by": "Express",
"vary": "Origin, Accept-Encoding",
"access-control-allow-credentials": "true",
"content-type": "application/json; charset=utf-8",
"content-length": "2",
"etag": "W/"2-l9Fw4VUO7kr8CvBlt4zaMCqXZ0w"",
"date": "Sun, 20 Aug 2023 22:22:31 GMT",
"connection": "close"
},
"statusCode": 200,
"statusMessage": "OK"
}
]

Send List not working

I used the same suggestion for structure of Send List , but stay pending forever, not working for me, any idea?

Docker Jwt Expiry Cannot increase

we are not able to increase the JWT Expiry and it stick with 3600S === 1h.
it seem the issue with env.config.ts which using Number.isInteger function
for checking AUTHENTICATION_JWT_EXPIRIN_IN environment

"SessionError: No sessions"

Eu estou recebendo o seguinte erro:

{
    "status": 400,
    "error": "Bad Request",
    "message": [
        "SessionError: No sessions"
    ]
}

Para toda mensagem de desejo enviar.

  • Tenho uma instância criada
  • A instancia foi conectada
  • A conexão está aberta

Não sei se não encontrei, mas seria legal ter uma documentação

Disconnections occurring frequently

being precise, since 2023/06/28 there have been disconnections of instances already connected, I use docker + redis... it was working perfectly, but since the last 3 days disconnections have occurred for no reason, without origin, the user has to go there and connect again.

Get product order by message Id

Hi, I was wondering if we can implement a endpoint, where we can get all the products from order message ID like we have in wppconnect
https://wppconnect.io/swagger/wppconnect-server#tag/Catalog-and-Bussiness/paths/~1api~1%7Bsession%7D~1get-order-by-messageId/get

We can actually, get the order products, the meta product ID, the value and quantity.

Which is good, because I can get the products from the order, not only that, I can extract all products, if I create a order with all products, and do something with this information.

Share your toughts, btw thanks for your hardwork

sessões

bom dia

já aconteceu algumas vezes da sessão estar ativa no celular, mas a apikey gerada no momento da conexão não funcionar mais
existe como atualizar a apikey ou descobrir o porque disso?

"How can I download the audio file in the 'file.enc' format that is returned in the JSON?"

{
"event": "messages.upsert",
"instance": "teste",
"data": {
"key": {
"remoteJid": "[email protected]",
"fromMe": true,
"id": "7241C7B266A4557ECBC67D9944D21408"
},
"pushName": "Dr",
"message": {
"audioMessage": {
"url": "https://mmg.whatsapp.net/v/t62.7117-24/32515835_800028148102792_6985846481403803426_n.enc?ccb=11-4&oh=01_AdS_y9cSmdzkyTW7xpsdim14qD-pCnrwwc2qazTCW-QFzw&oe=64B192B5&mms3=true",
"mimetype": "audio/ogg; codecs=opus",
"fileSha256": "7DAltRApUj5cuTXiE5zhKYFFcUjbWYQf0AF58cOslts=",
"fileLength": "3463",
"seconds": 1,
"ptt": true,
"mediaKey": "EiicDE/kZ3rX5JhaLsODR6XejNt7lH+XkxLkrNVq0EI=",
"fileEncSha256": "/NSaOWnNg1kcLcskKuAlSx5LroWPbzEyQYP/g6USKFE=",
"directPath": "/v/t62.7117-24/32515835_800028148102792_6985846481403803426_n.enc?ccb=11-4&oh=01_AdS_y9cSmdzkyTW7xpsdim14qD-pCnrwwc2qazTCW-QFzw&oe=64B192B5",
"mediaKeyTimestamp": "1686778093",
"waveform": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJFhQRCQAAABcsLjExMC8wNDc3LhgTIS89RUhJR0M+Ny8jFQwEBA=="
}
},
"messageTimestamp": 1686778093,
"owner": "[email protected]",
"source": "android"
}
}

Problems with Too Many Connections to Redis

Hello @jrCleber, I found a scenario I wanted to share with you:

In April, Redis released version 7, which has a persistent session as one of its new features, that is, if there is no explicit timeout on the client or configured on the server, the connection remains open forever. By default Redis 7 is configured like this.

From the Redis Documentation:

By default recent versions of Redis don't close the connection with the client if the client is idle for many seconds: the connection will remain open forever.

https://redis.io/docs/reference/clients/#client-timeouts

Those who are still using Redis 6 can also enable persistent connections but the default is that connections are closed after a while.

Looking at the way CodeChat manages connections with Redis, with each new instance of the Redis class a new connection is created and is not closed afterwards, which causes a huge number of connection polls.

In the image below I have a CodeChat installation in a Managed Redis in Digital Ocean with 1 session started lasting 21 minutes and already has more than 3600 open connections in redis:

Captura de Tela 2023-07-02 às 15 27 37 - cópia

Redis has a default setting of 10000 concurrent connections, a simple installation on a number with little use managed to get 3600. I believe that a slightly busy session reaches this limit quickly. (Redis Max Clients)

With around 1000 connections it was enough for CodeChat to start receiving connection denials from Redis, causing a crash.

Redis is a very popular distributed database, and I believe it's essential to keep it working with Codechat, but with an implementation that doesn't require as many connections (or just do the disconnects).

I think it's a start to a discussion of how Redis can be used with Codechat.

audios mp3 enviados pelo anexo esta ficando mudo para a pessoa que recebe no celular

audios mp3 enviados pelo anexo esta ficando mudo para a pessoa que recebe no celular...

Quando anexamos um audio mp3 na conversa e enviamos ao contato... pelo celular o audio fica mudo, a pessoa nao consegue ouvir... o atendente consegue ouvir normal. nos testes também notei que se o cliente estiver usando a versão web whatsapp, ai ele consegue ouvir o audio anexado. O problema esta ocorrendo quando é ouvido por celular.

O erro acontece desde da verão [v2.16.0] do chatwoot .. na versão 2.17.1 a situação piorou... agora nem o audio gravado no proprio chat a pessoa consegue ouvir no celular...

Fetching Contact Push names

On the ios app when you can add a contact and see their push name.

Ideally when checking if a number exists I'd like to be able to do the same.
Is this possible currently with the api?

Audio .Wav is not accepted

Due to the integration with Chattwoot, the Audio Wav cannot be sent as normal audio or media to be played in WhatsApp, only sent as a document :(

groups in messages.set + Missing initials webhooks

Olá, gostaria de iniciar elogiando seu trabalho, amei seu projeto e estou desenvolvendo em cima dele um sistema.
Quando faço a conexão, recebo os seguintes webhooks:
chats.set, contacts.upsert e messages.set.
No messages.set há também mensagens de grupos, onde não é possível identificar quem é que enviou a mensagem, apenas de qual grupo a mensagem veio, e creio eu que esteja faltando webhooks iniciais.


Hello, I would like to start praising your work, I loved your project and I am developing a system based on it.
When I connect, I get the following webhooks:
chats.set, contacts.upsert and messages.set.
In messages.set there are also group messages, where it is not possible to identify who sent the message, only which group the message came from, and I believe that initial webhooks are missing.

Não é possível definir uma porta especifica para o container Docker

Olá!
Como posso definir uma porta especifica para um container Docker, utilizando a imagem oficial do CodeChat? Não encontrei essa especificação para as variáveis de ambiente.

Por padrão, a exposição é realizada para a porta 8083, más e se estiver rodando mais um container com a mesma imagem?

File upload endpoint not working with base64

Hey guys

I'm trying to use the endpoint POST {{baseUrl}}/message/sendMedia/{{instance}}, but when passing the base64 of a .pdf file, it's not working. It's returning me the message: "Owned media must be a url".

What am I doing wrong? can anybody help me?

image
image

SEND button not working

When sending a button, the message does not reach the other side, even if the response is positive.

To make it clear, I don't use Whatsapp Business on either side, neither who sends nor who receives

SEND AUDIO ERROR

audios working only on whatsapp web, anyone else with this problem?

Bug Issue Template

🔎 What is affected by this bug?

Ex. messages, instancies, groups, etc

Maybe a checklist here? Kind of:

  • Messages
  • Instancies
  • Groups
  • Critical
  • Webhooks

🕧 When does this occur?

Ex. After doing something when I call such route

🧱 How do we replicate the issue?

Please be specific as possible. Use dashes (-) or numbers (1.) to create a list of steps

✨ Expected behavior (i.e. solution)

What should have happened?

⚙ ENV File

Please leave here a copy of your ENV file blurring sensitive contents

Please leave env here blurring sensitive contents

📃📷 Logs and Screenshots

Please leave here any relevant logs and/or screenshots to help us understand and visualize easier what's the problem

📎 Other Comments

I was looking for a way to contribute to this project and as I have bare experience on OpenSource It showed up very challenging. The biggest projects have lots of docs and guidelines that guides developers to a specific way to apply their contribution effort. After some research I've came to this model of bug Issue template that is adapted to what I has seen here. I hope you aprecciate and modify as you think it suits better our needs. I'll open another issue about this topic soon with PR Template.

How to fetch user profile?

Hi,

Great library! Thanks. I want some enhancement.

  1. To get user profile like name & picture
  2. To check number is registered or not

Let me know if it possible to do with current code?

converter gravação de audio mp3 para ogg

em teoria a api funciona para enviar gravação de audio em mp3, mas, notei que não toca em iphone quando enviado em mp3, seria interessante ter uma forma já nativa de converter audios mp3 para ogg.

Reaction Messages stuck in pending

Passed in ID and jid of message to react to using postman collection.

Just returns a status of pending

{
"key": {
"remoteJid": "44***********@s.whatsapp.net",
"fromMe": true,
"id": "BA*****************"
},
"message": {
"reactionMessage": {
"key": {
"remoteJid": "44***********@s.whatsapp.net",
"fromMe": true,
"id": "3AF***************"
},
"text": "😒"
}
},
"messageTimestamp": "1683210254",
"status": "PENDING"
}

N8N - [Codechat To Chatwoot] e [Chatwoot To Codechat]

Vejo que conectores como WPPConnect já possuem a integração completa com o chatwoot, porém é um conector um pouco instavel, e mais pesado que o codechat.
Seria interessante ter os módulos do n8n para o Chatwoot disponível aqui no codechat, comecei a desenvolver aqui, mas estou tendo um pouco de dificuldades.

notificação não toca

Olá amigo blz, ao conectar na api whatsapp fica sem receber o som da notificação, ao desconectar volta a funcionar perfeitamente
Teria algo que eu poderia estar fazendo para voltar tocar as notificações de mensagens recebidas ?

Obrigado.

Problem scanning QR Code

When scanning the QrCode in the terminal in all 6 attempts it does not connect. Tested on normal whatsapp and whatsapp business.

What can I do to fix this?

k8 liveness endpoint

Hello folks,

first of all, congrats for this amazing project, it's really works for us sending transactions and marketing messages thought n8n workflows.

The last month we're deployed codechat in kubernetes infra, and it's working very well. But, for working 100% we need to define the liveness endpoint for k8.

Question: have any global endpoint to returns if all instances are connected and working well?

Thanks!

Refs: https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-startup-probes/#define-a-liveness-http-request

PR Template

Please tell us what you want to change in the title above

Description

Describe your changes in detail

Motivation and Context

Why is this change required? What problem does it solve?
If it fixes an open issue, please leave link to the issue below.

How has this been tested?

Please describe in detail how you tested your changes.
Include details of your testing environment, tests ran to see how your change affects other areas of the code, etc.

Screenshots (if appropriate):

Types of changes

What types of changes does your code introduce? Check all the boxes that apply:

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)

Checklist:

Go over all the following points, and put an x in all the boxes that apply.
If you're unsure about any of these, don't hesitate to ask. We're here to help!

  • My code follows the code style of this project.
  • My change requires a change to the documentation.
  • I have updated the documentation accordingly.

Check another issue related with this topic: Bug Issue Template

Error starting latest version

[email protected] start:prod
bash start.sh

removing dist

transpiling...

[email protected] build
tsc

src/whatsapp/controllers/instance.controller.ts:24:22 - error TS2554: Expected 4 arguments, but got 3.

24 const instance = new WAStartupService(
~~~~~~~~~~~~~~~~~~~~~
25 this.configService,
~~~~~~~~~~~~~~~~~~~~~~~~~
...
27 this.repository,
~~~~~~~~~~~~~~~~~~~~~~
28 );
~~~~~

src/whatsapp/services/whatsapp.service.ts:106:5
106 private readonly cache: RedisCache,
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
An argument for 'cache' was not provided.

Found 1 error in src/whatsapp/controllers/instance.controller.ts:24

Successfully build

Starting application...

node:internal/modules/cjs/loader:1080
throw err;
^

Error: Cannot find module '/root/whatsapp-api/dist/src/main.js'
at Module._resolveFilename (node:internal/modules/cjs/loader:1077:15)
at Module._load (node:internal/modules/cjs/loader:922:27)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
at node:internal/main/run_main_module:23:47 {
code: 'MODULE_NOT_FOUND',

Audio playing only Whatsapp Web

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.