├── src ├── api │ ├── sessiondata │ │ └── .gitkeep │ ├── helper │ │ ├── sleep.js │ │ ├── genVc.js │ │ ├── downloadMsg.js │ │ ├── connectMongoClient.js │ │ ├── processbtn.js │ │ └── mongoAuthState.js │ ├── errors │ │ ├── api.error.js │ │ └── extendable.error.js │ ├── models │ │ └── chat.model.js │ ├── middlewares │ │ ├── keyCheck.js │ │ ├── loginCheck.js │ │ ├── tokenCheck.js │ │ └── error.js │ ├── routes │ │ ├── index.js │ │ ├── instance.route.js │ │ ├── misc.route.js │ │ ├── message.route.js │ │ └── group.route.js │ ├── views │ │ └── qrcode.ejs │ ├── class │ │ ├── session.js │ │ └── instance.js │ └── controllers │ │ ├── misc.controller.js │ │ ├── message.controller.js │ │ ├── group.controller.js │ │ └── instance.controller.js ├── config │ ├── express.js │ └── config.js └── server.js ├── Procfile ├── .prettierignore ├── .github ├── FUNDING.yml ├── dependabot.yml └── workflows │ ├── node.js-test.yml │ ├── format.yml │ ├── stale.yml │ └── codeql-analysis.yml ├── .husky └── pre-commit ├── .prettierrc.json ├── nodemon.json ├── .gitignore ├── Dockerfile ├── .eslintrc.json ├── CONTRIBUTING.md ├── docker-compose.yml ├── .env.example ├── tests └── status.route.test.js ├── package.json ├── README.md ├── LICENSE └── whatsapp-api-nodejs.postman_collection.json /src/api/sessiondata/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Procfile: -------------------------------------------------------------------------------- 1 | web: npm run start 2 | -------------------------------------------------------------------------------- /.prettierignore: -------------------------------------------------------------------------------- 1 | whatsapp-api-nodejs.postman_collection.json 2 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | github: salman0ansari 2 | custom: https://www.buymeacoffee.com/salman0ansari 3 | -------------------------------------------------------------------------------- /.husky/pre-commit: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | . "$(dirname -- "$0")/_/husky.sh" 3 | 4 | npx --no-install lint-staged 5 | -------------------------------------------------------------------------------- /.prettierrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "trailingComma": "es5", 3 | "tabWidth": 4, 4 | "semi": false, 5 | "singleQuote": true 6 | } 7 | -------------------------------------------------------------------------------- /nodemon.json: -------------------------------------------------------------------------------- 1 | { 2 | "watch": ["src", ".env"], 3 | "ignore": [], 4 | "ext": "js", 5 | "exec": "node src/server.js" 6 | } 7 | -------------------------------------------------------------------------------- /src/api/helper/sleep.js: -------------------------------------------------------------------------------- 1 | module.exports = function sleep(ms) { 2 | return new Promise((resolve) => { 3 | setTimeout(resolve, ms) 4 | }) 5 | } 6 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: "npm" 4 | directory: "/" # Location of package manifests 5 | schedule: 6 | interval: "weekly" 7 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # NODE 2 | node_modules 3 | package-lock.json 4 | yarn.lock 5 | 6 | # APPLICATION 7 | .env 8 | sessiondata 9 | 10 | # IDEs 11 | .vscode/settings.json 12 | .idea 13 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM node:19-alpine 2 | 3 | ARG _WORKDIR=/home/node/app 4 | ARG PORT=3333 5 | 6 | USER root 7 | RUN apk add git 8 | 9 | WORKDIR ${_WORKDIR} 10 | 11 | ADD . ${_WORKDIR} 12 | RUN yarn install 13 | 14 | USER node 15 | EXPOSE ${PORT} 16 | 17 | CMD yarn start -------------------------------------------------------------------------------- /src/api/errors/api.error.js: -------------------------------------------------------------------------------- 1 | const ExtendableError = require('../errors/extendable.error') 2 | 3 | class APIError extends ExtendableError { 4 | constructor({ message, errors, status = 500 }) { 5 | super({ 6 | message, 7 | errors, 8 | status, 9 | }) 10 | } 11 | } 12 | 13 | module.exports = APIError 14 | -------------------------------------------------------------------------------- /src/api/errors/extendable.error.js: -------------------------------------------------------------------------------- 1 | class ExtendableError extends Error { 2 | constructor({ message, errors, status }) { 3 | super(message) 4 | this.name = this.constructor.name 5 | this.message = message 6 | this.errors = errors 7 | this.status = status 8 | } 9 | } 10 | 11 | module.exports = ExtendableError 12 | -------------------------------------------------------------------------------- /src/api/helper/genVc.js: -------------------------------------------------------------------------------- 1 | module.exports = function generateVC(data) { 2 | const result = 3 | 'BEGIN:VCARD\n' + 4 | 'VERSION:3.0\n' + 5 | `FN:${data.fullName}\n` + 6 | `ORG:${data.organization};\n` + 7 | `TEL;type=CELL;type=VOICE;waid=${data.phoneNumber}:${data.phoneNumber}\n` + 8 | 'END:VCARD' 9 | 10 | return result 11 | } 12 | -------------------------------------------------------------------------------- /src/api/models/chat.model.js: -------------------------------------------------------------------------------- 1 | const mongoose = require('mongoose') 2 | 3 | const chatSchema = new mongoose.Schema({ 4 | key: { 5 | type: String, 6 | required: [true, 'key is missing'], 7 | unique: true, 8 | }, 9 | chat: { 10 | type: Array, 11 | }, 12 | }) 13 | 14 | const Chat = mongoose.model('Chat', chatSchema) 15 | 16 | module.exports = Chat 17 | -------------------------------------------------------------------------------- /src/api/middlewares/keyCheck.js: -------------------------------------------------------------------------------- 1 | function keyVerification(req, res, next) { 2 | const key = req.query['key']?.toString() 3 | if (!key) { 4 | return res 5 | .status(403) 6 | .send({ error: true, message: 'no key query was present' }) 7 | } 8 | const instance = WhatsAppInstances[key] 9 | if (!instance) { 10 | return res 11 | .status(403) 12 | .send({ error: true, message: 'invalid key supplied' }) 13 | } 14 | next() 15 | } 16 | 17 | module.exports = keyVerification 18 | -------------------------------------------------------------------------------- /src/api/routes/index.js: -------------------------------------------------------------------------------- 1 | const express = require('express') 2 | const router = express.Router() 3 | const instanceRoutes = require('./instance.route') 4 | const messageRoutes = require('./message.route') 5 | const miscRoutes = require('./misc.route') 6 | const groupRoutes = require('./group.route') 7 | 8 | router.get('/status', (req, res) => res.send('OK')) 9 | router.use('/instance', instanceRoutes) 10 | router.use('/message', messageRoutes) 11 | router.use('/group', groupRoutes) 12 | router.use('/misc', miscRoutes) 13 | 14 | module.exports = router 15 | -------------------------------------------------------------------------------- /.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "root": true, 3 | "parserOptions": { 4 | "ecmaVersion": "latest", 5 | "sourceType": "module" 6 | }, 7 | "extends": ["eslint:recommended", "prettier"], 8 | "env": { 9 | "es2021": true, 10 | "node": true 11 | }, 12 | "rules": { 13 | "no-console": "warn", 14 | "no-undefined": "warn", 15 | "no-unused-vars": "warn" 16 | }, 17 | "globals": { 18 | "WhatsAppInstances": true, 19 | "describe": true, 20 | "it": true 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/api/helper/downloadMsg.js: -------------------------------------------------------------------------------- 1 | const { downloadContentFromMessage } = require('@whiskeysockets/baileys') 2 | 3 | module.exports = async function downloadMessage(msg, msgType) { 4 | let buffer = Buffer.from([]) 5 | try { 6 | const stream = await downloadContentFromMessage(msg, msgType) 7 | for await (const chunk of stream) { 8 | buffer = Buffer.concat([buffer, chunk]) 9 | } 10 | } catch { 11 | return console.log('error downloading file-message') 12 | } 13 | return buffer.toString('base64') 14 | } 15 | -------------------------------------------------------------------------------- /src/api/middlewares/loginCheck.js: -------------------------------------------------------------------------------- 1 | function loginVerification(req, res, next) { 2 | const key = req.query['key']?.toString() 3 | if (!key) { 4 | return res 5 | .status(403) 6 | .send({ error: true, message: 'no key query was present' }) 7 | } 8 | const instance = WhatsAppInstances[key] 9 | if (!instance.instance?.online) { 10 | return res 11 | .status(401) 12 | .send({ error: true, message: "phone isn't connected" }) 13 | } 14 | next() 15 | } 16 | 17 | module.exports = loginVerification 18 | -------------------------------------------------------------------------------- /src/api/middlewares/tokenCheck.js: -------------------------------------------------------------------------------- 1 | const config = require('../../config/config') 2 | 3 | function tokenVerification(req, res, next) { 4 | const bearer = req.headers.authorization 5 | const token = bearer?.slice(7)?.toString() 6 | if (!token) { 7 | return res.status(403).send({ 8 | error: true, 9 | message: 'no bearer token header was present', 10 | }) 11 | } 12 | 13 | if (config.token !== token) { 14 | return res 15 | .status(403) 16 | .send({ error: true, message: 'invalid bearer token supplied' }) 17 | } 18 | next() 19 | } 20 | 21 | module.exports = tokenVerification 22 | -------------------------------------------------------------------------------- /src/api/views/qrcode.ejs: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | WhatsApp QrCode 8 | 15 | 16 | 17 |

Scan Code Below Using WhatsApp App

18 |
19 | 20 |
21 | 22 | -------------------------------------------------------------------------------- /src/api/middlewares/error.js: -------------------------------------------------------------------------------- 1 | /* eslint-disable no-unused-vars */ 2 | const APIError = require('../../api/errors/api.error') 3 | 4 | const handler = (err, req, res, next) => { 5 | const statusCode = err.statusCode ? err.statusCode : 500 6 | 7 | res.setHeader('Content-Type', 'application/json') 8 | res.status(statusCode) 9 | res.json({ 10 | error: true, 11 | code: statusCode, 12 | message: err.message, 13 | }) 14 | } 15 | 16 | exports.handler = handler 17 | 18 | exports.notFound = (req, res, next) => { 19 | const err = new APIError({ 20 | message: 'Not found', 21 | status: 404, 22 | }) 23 | return handler(err, req, res) 24 | } 25 | -------------------------------------------------------------------------------- /src/api/helper/connectMongoClient.js: -------------------------------------------------------------------------------- 1 | const { MongoClient } = require('mongodb') 2 | const logger = require('pino')() 3 | 4 | module.exports = async function connectToCluster(uri) { 5 | let mongoClient 6 | 7 | try { 8 | mongoClient = new MongoClient(uri, { 9 | useNewUrlParser: true, 10 | useUnifiedTopology: true, 11 | }) 12 | logger.info('STATE: Connecting to MongoDB') 13 | await mongoClient.connect() 14 | logger.info('STATE: Successfully connected to MongoDB') 15 | return mongoClient 16 | } catch (error) { 17 | logger.error('STATE: Connection to MongoDB failed!', error) 18 | process.exit() 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/api/routes/instance.route.js: -------------------------------------------------------------------------------- 1 | const express = require('express') 2 | const controller = require('../controllers/instance.controller') 3 | const keyVerify = require('../middlewares/keyCheck') 4 | const loginVerify = require('../middlewares/loginCheck') 5 | 6 | const router = express.Router() 7 | router.route('/init').get(controller.init) 8 | router.route('/qr').get(keyVerify, controller.qr) 9 | router.route('/qrbase64').get(keyVerify, controller.qrbase64) 10 | router.route('/info').get(keyVerify, controller.info) 11 | router.route('/restore').get(controller.restore) 12 | router.route('/logout').delete(keyVerify, loginVerify, controller.logout) 13 | router.route('/delete').delete(keyVerify, controller.delete) 14 | router.route('/list').get(controller.list) 15 | 16 | module.exports = router 17 | -------------------------------------------------------------------------------- /.github/workflows/node.js-test.yml: -------------------------------------------------------------------------------- 1 | name: 💉 Node.js CI 2 | 3 | on: 4 | push: 5 | branches: [main] 6 | pull_request: 7 | branches: [main] 8 | 9 | jobs: 10 | build: 11 | runs-on: ubuntu-latest 12 | 13 | strategy: 14 | matrix: 15 | node-version: [16.x] 16 | 17 | steps: 18 | - uses: actions/checkout@v3 19 | - name: 👨‍💻️ Use Node.js ${{ matrix.node-version }} 20 | uses: actions/setup-node@v3 21 | with: 22 | node-version: ${{ matrix.node-version }} 23 | - name: 📥 Installing packages 24 | run: yarn 25 | - name: 📝 Running test 26 | run: yarn test 27 | env: 28 | TOKEN: ${{ secrets.TOKEN }} 29 | -------------------------------------------------------------------------------- /.github/workflows/format.yml: -------------------------------------------------------------------------------- 1 | name: Prettier 2 | on: 3 | pull_request: 4 | push: 5 | branches: 6 | - main 7 | 8 | jobs: 9 | format: 10 | runs-on: ubuntu-latest 11 | steps: 12 | - uses: actions/checkout@v2 13 | with: 14 | token: ${{ secrets.TOKEN }} 15 | ref: ${{ github.head_ref }} 16 | 17 | - uses: actions/setup-node@v1 18 | with: 19 | node-version: '16.x' 20 | - run: npm i prettier -g 21 | - run: npm run format:write 22 | 23 | - name: Commit changes 24 | uses: stefanzweifel/git-auto-commit-action@v4 25 | with: 26 | branch: main 27 | commit_message: 'CI: fix formatting' 28 | -------------------------------------------------------------------------------- /src/config/express.js: -------------------------------------------------------------------------------- 1 | const express = require('express') 2 | const path = require('path') 3 | const exceptionHandler = require('express-exception-handler') 4 | exceptionHandler.handle() 5 | const app = express() 6 | const error = require('../api/middlewares/error') 7 | const tokenCheck = require('../api/middlewares/tokenCheck') 8 | const { protectRoutes } = require('./config') 9 | 10 | app.use(express.json()) 11 | app.use(express.json({ limit: '50mb' })) 12 | app.use(express.urlencoded({ extended: true })) 13 | app.set('view engine', 'ejs') 14 | app.set('views', path.join(__dirname, '../api/views')) 15 | global.WhatsAppInstances = {} 16 | 17 | const routes = require('../api/routes/') 18 | if (protectRoutes) { 19 | app.use(tokenCheck) 20 | } 21 | app.use('/', routes) 22 | app.use(error.handler) 23 | 24 | module.exports = app 25 | -------------------------------------------------------------------------------- /src/api/routes/misc.route.js: -------------------------------------------------------------------------------- 1 | const express = require('express') 2 | const controller = require('../controllers/misc.controller') 3 | const keyVerify = require('../middlewares/keyCheck') 4 | const loginVerify = require('../middlewares/loginCheck') 5 | 6 | const router = express.Router() 7 | 8 | router.route('/onwhatsapp').get(keyVerify, loginVerify, controller.onWhatsapp) 9 | router.route('/downProfile').get(keyVerify, loginVerify, controller.downProfile) 10 | router.route('/getStatus').get(keyVerify, loginVerify, controller.getStatus) 11 | router.route('/blockUser').get(keyVerify, loginVerify, controller.blockUser) 12 | router 13 | .route('/updateProfilePicture') 14 | .post(keyVerify, loginVerify, controller.updateProfilePicture) 15 | router 16 | .route('/getuserorgroupbyid') 17 | .get(keyVerify, loginVerify, controller.getUserOrGroupById) 18 | module.exports = router 19 | -------------------------------------------------------------------------------- /.github/workflows/stale.yml: -------------------------------------------------------------------------------- 1 | name: Mark stale issues and pull requests 2 | 3 | on: 4 | schedule: 5 | - cron: '30 1 * * *' 6 | 7 | permissions: 8 | pull-requests: read 9 | 10 | jobs: 11 | 12 | stale: 13 | runs-on: ubuntu-latest 14 | steps: 15 | - uses: actions/stale@v3 16 | with: 17 | repo-token: ${{ secrets.GITHUB_TOKEN }} 18 | stale-issue-message: 'This issue is stale because it has been open 6 days with no activity. Remove the stale label or comment or this will be closed in 2 days' 19 | stale-pr-message: 'This PR is stale because it has been open 6 days with no activity. Remove the stale label or comment or this will be closed in 2 days' 20 | days-before-stale: 6 21 | days-before-close: 2 22 | exempt-draft-pr: true 23 | -------------------------------------------------------------------------------- /src/api/helper/processbtn.js: -------------------------------------------------------------------------------- 1 | module.exports = function processButton(buttons) { 2 | const preparedButtons = [] 3 | 4 | buttons.map((button) => { 5 | if (button.type == 'replyButton') { 6 | preparedButtons.push({ 7 | quickReplyButton: { 8 | displayText: button.title ?? '', 9 | }, 10 | }) 11 | } 12 | 13 | if (button.type == 'callButton') { 14 | preparedButtons.push({ 15 | callButton: { 16 | displayText: button.title ?? '', 17 | phoneNumber: button.payload ?? '', 18 | }, 19 | }) 20 | } 21 | if (button.type == 'urlButton') { 22 | preparedButtons.push({ 23 | urlButton: { 24 | displayText: button.title ?? '', 25 | url: button.payload ?? '', 26 | }, 27 | }) 28 | } 29 | }) 30 | return preparedButtons 31 | } 32 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | We're really glad you're reading this, because we need developers to help this project. 👏 2 | 3 | ## If you would like to contribute, here are a few starters: 4 | 5 | - Bug Hunts. 6 | - Add sorts of examples. 7 | - Refactor Code. 8 | - Additional features/ More integrations. 9 | - TS support. 10 | 11 | ## Instructions 12 | 13 | These steps will guide you through contributing to this project: 14 | 15 | - Create an issue to discuss about the changes you want to do before starting to code. 16 | - Fork the repo 17 | - Clone it and install dependencies 18 | 19 | $ git clone https://github.com/https://github.com/salman0ansari/whatsapp-api-nodejs 20 | 21 | $ npm install 22 | 23 | - Make changes 24 | 25 | - Send a [GitHub Pull Request](https://github.com/salman0ansari/whatsapp-api-nodejs/compare?expand=1) with a clear list of what you've done (read more [about pull requests](https://help.github.com/articles/about-pull-requests/)). Make sure all of your commits are atomic (one feature per commit). 26 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '3.8' 2 | 3 | services: 4 | mongodb: 5 | container_name: mongodb 6 | image: mongo:latest 7 | restart: unless-stopped 8 | ports: 9 | - 27017:27017 10 | volumes: 11 | - db:/data/db 12 | app: 13 | container_name: api 14 | build: 15 | context: . 16 | dockerfile: Dockerfile 17 | args: 18 | - PORT=${PORT} 19 | depends_on: 20 | - mongodb 21 | restart: unless-stopped 22 | env_file: .env 23 | ports: 24 | - ${PORT}:${PORT} 25 | environment: 26 | - TOKEN=${TOKEN} 27 | - PORT=${PORT} 28 | - MONGODB_ENABLED=${MONGODB_ENABLED} 29 | - MONGODB_URL=mongodb://mongodb:27017 30 | - WEBHOOK_ENABLED=${WEBHOOK_ENABLED} 31 | - WEBHOOK_URL=${WEBHOOK_URL} 32 | - WEBHOOK_BASE64=${WEBHOOK_BASE64} 33 | volumes: 34 | - ./:/home/node/app 35 | - /home/node/app/node_modules/ 36 | 37 | volumes: 38 | db: 39 | -------------------------------------------------------------------------------- /.env.example: -------------------------------------------------------------------------------- 1 | # ================================== 2 | # SECURITY CONFIGURATION 3 | # ================================== 4 | TOKEN=RANDOM_STRING_HERE 5 | PROTECT_ROUTES=false 6 | 7 | # ================================== 8 | # APPLICATION CONFIGURATION 9 | # ================================== 10 | PORT=3333 11 | RESTORE_SESSIONS_ON_START_UP=false 12 | APP_URL=http://localhost:3333 13 | LOG_LEVEL=silent 14 | 15 | # ================================== 16 | # BROWSER CONFIGURATION 17 | # ================================== 18 | CLIENT_PLATFORM='Whatsapp MD' 19 | CLIENT_BROWSER='Chrome' 20 | CLIENT_VERSION='4.0.0' 21 | 22 | # ================================== 23 | # INSTANCE CONFIGURATION 24 | # ================================== 25 | INSTANCE_MAX_RETRY_QR=2 26 | 27 | # ================================== 28 | # DATABASE CONFIGURATION 29 | # ================================== 30 | MONGODB_ENABLED=false 31 | MONGODB_URL=mongodb://127.0.0.1:27017/whatsapp_api 32 | 33 | # ================================== 34 | # WEBHOOK CONFIGURATION 35 | # ================================== 36 | WEBHOOK_ENABLED=false 37 | WEBHOOK_URL=https://webhook.site/d0122a66-18a3-432d-b63f-4772b190dd72 38 | WEBHOOK_BASE64=false 39 | WEBHOOK_ALLOWED_EVENTS= 40 | 41 | # ================================== 42 | # MESSAGE CONFIGURATION 43 | # ================================== 44 | MARK_MESSAGES_READ=false -------------------------------------------------------------------------------- /src/api/routes/message.route.js: -------------------------------------------------------------------------------- 1 | const express = require('express') 2 | const controller = require('../controllers/message.controller') 3 | const keyVerify = require('../middlewares/keyCheck') 4 | const loginVerify = require('../middlewares/loginCheck') 5 | const multer = require('multer') 6 | 7 | const router = express.Router() 8 | const storage = multer.memoryStorage() 9 | const upload = multer({ storage: storage, inMemory: true }).single('file') 10 | 11 | router.route('/text').post(keyVerify, loginVerify, controller.Text) 12 | router.route('/image').post(keyVerify, loginVerify, upload, controller.Image) 13 | router.route('/video').post(keyVerify, loginVerify, upload, controller.Video) 14 | router.route('/audio').post(keyVerify, loginVerify, upload, controller.Audio) 15 | router.route('/doc').post(keyVerify, loginVerify, upload, controller.Document) 16 | router.route('/mediaurl').post(keyVerify, loginVerify, controller.Mediaurl) 17 | router.route('/button').post(keyVerify, loginVerify, controller.Button) 18 | router.route('/contact').post(keyVerify, loginVerify, controller.Contact) 19 | router.route('/list').post(keyVerify, loginVerify, controller.List) 20 | router.route('/setstatus').put(keyVerify, loginVerify, controller.SetStatus) 21 | router 22 | .route('/mediabutton') 23 | .post(keyVerify, loginVerify, controller.MediaButton) 24 | router.route("/read").post(keyVerify, loginVerify, controller.Read) 25 | router.route("/react").post(keyVerify, loginVerify, controller.React) 26 | 27 | module.exports = router 28 | -------------------------------------------------------------------------------- /tests/status.route.test.js: -------------------------------------------------------------------------------- 1 | const request = require('supertest') 2 | const assert = require('assert') 3 | const app = require('../src/server') 4 | const { protectRoutes } = require('../src/config/config') 5 | 6 | if (protectRoutes) { 7 | describe('instance endpoints', () => { 8 | it('should fail with no bearer token is present', (done) => { 9 | request(app) 10 | .get('/status') 11 | .expect(403) 12 | .then((res) => { 13 | assert(res.body.message, 'Initializing successfully') 14 | done() 15 | }) 16 | .catch((err) => done(err)) 17 | }) 18 | 19 | it('should fail with bearer token is mismatch', (done) => { 20 | request(app) 21 | .get('/status') 22 | .set('Authorization', `Bearer ${process.env.TOKEN}wrong`) 23 | .expect(403) 24 | .then((res) => { 25 | assert(res.body.message, 'invalid bearer token supplied') 26 | done() 27 | }) 28 | .catch((err) => done(err)) 29 | }) 30 | 31 | it('should successfully when bearer token is present and matched', (done) => { 32 | request(app) 33 | .get('/status') 34 | .set('Authorization', `Bearer ${process.env.TOKEN}`) 35 | .expect(200) 36 | .then((res) => { 37 | assert(res.body, 'OK') 38 | done() 39 | }) 40 | .catch((err) => done(err)) 41 | }) 42 | }) 43 | } 44 | -------------------------------------------------------------------------------- /src/server.js: -------------------------------------------------------------------------------- 1 | const dotenv = require('dotenv') 2 | const mongoose = require('mongoose') 3 | const logger = require('pino')() 4 | dotenv.config() 5 | 6 | const app = require('./config/express') 7 | const config = require('./config/config') 8 | 9 | const { Session } = require('./api/class/session') 10 | const connectToCluster = require('./api/helper/connectMongoClient') 11 | 12 | let server 13 | 14 | if (config.mongoose.enabled) { 15 | mongoose.set('strictQuery', true); 16 | mongoose.connect(config.mongoose.url, config.mongoose.options).then(() => { 17 | logger.info('Connected to MongoDB') 18 | }) 19 | } 20 | 21 | server = app.listen(config.port, async () => { 22 | logger.info(`Listening on port ${config.port}`) 23 | global.mongoClient = await connectToCluster(config.mongoose.url) 24 | if (config.restoreSessionsOnStartup) { 25 | logger.info(`Restoring Sessions`) 26 | const session = new Session() 27 | let restoreSessions = await session.restoreSessions() 28 | logger.info(`${restoreSessions.length} Session(s) Restored`) 29 | } 30 | }) 31 | 32 | const exitHandler = () => { 33 | if (server) { 34 | server.close(() => { 35 | logger.info('Server closed') 36 | process.exit(1) 37 | }) 38 | } else { 39 | process.exit(1) 40 | } 41 | } 42 | 43 | const unexpectedErrorHandler = (error) => { 44 | logger.error(error) 45 | exitHandler() 46 | } 47 | 48 | process.on('uncaughtException', unexpectedErrorHandler) 49 | process.on('unhandledRejection', unexpectedErrorHandler) 50 | 51 | process.on('SIGTERM', () => { 52 | logger.info('SIGTERM received') 53 | if (server) { 54 | server.close() 55 | } 56 | }) 57 | 58 | module.exports = server 59 | -------------------------------------------------------------------------------- /src/api/routes/group.route.js: -------------------------------------------------------------------------------- 1 | const express = require('express') 2 | const controller = require('../controllers/group.controller') 3 | const keyVerify = require('../middlewares/keyCheck') 4 | const loginVerify = require('../middlewares/loginCheck') 5 | 6 | const router = express.Router() 7 | 8 | router.route('/create').post(keyVerify, loginVerify, controller.create) 9 | router.route('/listall').get(keyVerify, loginVerify, controller.listAll) 10 | router.route('/leave').get(keyVerify, loginVerify, controller.leaveGroup) 11 | 12 | router 13 | .route('/inviteuser') 14 | .post(keyVerify, loginVerify, controller.addNewParticipant) 15 | router.route('/makeadmin').post(keyVerify, loginVerify, controller.makeAdmin) 16 | router 17 | .route('/demoteadmin') 18 | .post(keyVerify, loginVerify, controller.demoteAdmin) 19 | router 20 | .route('/getinvitecode') 21 | .get(keyVerify, loginVerify, controller.getInviteCodeGroup) 22 | router 23 | .route('/getinstanceinvitecode') 24 | .get(keyVerify, loginVerify, controller.getInstanceInviteCodeGroup) 25 | router 26 | .route('/getallgroups') 27 | .get(keyVerify, loginVerify, controller.getAllGroups) 28 | router 29 | .route('/participantsupdate') 30 | .post(keyVerify, loginVerify, controller.groupParticipantsUpdate) 31 | router 32 | .route('/settingsupdate') 33 | .post(keyVerify, loginVerify, controller.groupSettingUpdate) 34 | router 35 | .route('/updatesubject') 36 | .post(keyVerify, loginVerify, controller.groupUpdateSubject) 37 | router 38 | .route('/updatedescription') 39 | .post(keyVerify, loginVerify, controller.groupUpdateDescription) 40 | router 41 | .route('/inviteinfo') 42 | .post(keyVerify, loginVerify, controller.groupInviteInfo) 43 | router.route('/groupjoin').post(keyVerify, loginVerify, controller.groupJoin) 44 | module.exports = router 45 | -------------------------------------------------------------------------------- /src/api/class/session.js: -------------------------------------------------------------------------------- 1 | /* eslint-disable no-unsafe-optional-chaining */ 2 | const { WhatsAppInstance } = require('../class/instance') 3 | const logger = require('pino')() 4 | const config = require('../../config/config') 5 | 6 | class Session { 7 | async restoreSessions() { 8 | let restoredSessions = new Array() 9 | let allCollections = [] 10 | try { 11 | const db = mongoClient.db('whatsapp-api') 12 | const result = await db.listCollections().toArray() 13 | result.forEach((collection) => { 14 | allCollections.push(collection.name) 15 | }) 16 | 17 | allCollections.map((key) => { 18 | const query = {} 19 | db.collection(key) 20 | .find(query) 21 | .toArray(async (err, result) => { 22 | if (err) throw err 23 | const webhook = !config.webhookEnabled 24 | ? undefined 25 | : config.webhookEnabled 26 | const webhookUrl = !config.webhookUrl 27 | ? undefined 28 | : config.webhookUrl 29 | const instance = new WhatsAppInstance( 30 | key, 31 | webhook, 32 | webhookUrl 33 | ) 34 | await instance.init() 35 | WhatsAppInstances[key] = instance 36 | }) 37 | restoredSessions.push(key) 38 | }) 39 | } catch (e) { 40 | logger.error('Error restoring sessions') 41 | logger.error(e) 42 | } 43 | return restoredSessions 44 | } 45 | } 46 | 47 | exports.Session = Session 48 | -------------------------------------------------------------------------------- /src/api/controllers/misc.controller.js: -------------------------------------------------------------------------------- 1 | exports.onWhatsapp = async (req, res) => { 2 | // eslint-disable-next-line no-unsafe-optional-chaining 3 | const data = await WhatsAppInstances[req.query.key]?.verifyId( 4 | WhatsAppInstances[req.query.key]?.getWhatsAppId(req.query.id) 5 | ) 6 | return res.status(201).json({ error: false, data: data }) 7 | } 8 | 9 | exports.downProfile = async (req, res) => { 10 | const data = await WhatsAppInstances[req.query.key]?.DownloadProfile( 11 | req.query.id 12 | ) 13 | return res.status(201).json({ error: false, data: data }) 14 | } 15 | 16 | exports.getStatus = async (req, res) => { 17 | const data = await WhatsAppInstances[req.query.key]?.getUserStatus( 18 | req.query.id 19 | ) 20 | return res.status(201).json({ error: false, data: data }) 21 | } 22 | 23 | exports.blockUser = async (req, res) => { 24 | const data = await WhatsAppInstances[req.query.key]?.blockUnblock( 25 | req.query.id, 26 | req.query.block_status 27 | ) 28 | if (req.query.block_status == 'block') { 29 | return res 30 | .status(201) 31 | .json({ error: false, message: 'Contact Blocked' }) 32 | } else 33 | return res 34 | .status(201) 35 | .json({ error: false, message: 'Contact Unblocked' }) 36 | } 37 | 38 | exports.updateProfilePicture = async (req, res) => { 39 | const data = await WhatsAppInstances[req.query.key].updateProfilePicture( 40 | req.body.id, 41 | req.body.url 42 | ) 43 | return res.status(201).json({ error: false, data: data }) 44 | } 45 | 46 | exports.getUserOrGroupById = async (req, res) => { 47 | const data = await WhatsAppInstances[req.query.key].getUserOrGroupById( 48 | req.query.id 49 | ) 50 | return res.status(201).json({ error: false, data: data }) 51 | } 52 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "whatsapp-api-nodejs", 3 | "version": "3.0.8", 4 | "description": "whatsapp-api-nodejs is builton top of Baileys-MD.", 5 | "main": "server.js", 6 | "scripts": { 7 | "start": "node src/server.js", 8 | "dev": "nodemon", 9 | "format:check": "prettier --check .", 10 | "format:write": "prettier --write .", 11 | "lint:check": "eslint .", 12 | "lint:fix": "eslint --fix .", 13 | "test": "mocha tests/*.test.js --exit", 14 | "configure-husky": "npx husky install && npx husky add .husky/pre-commit \"npx --no-install lint-staged\"" 15 | }, 16 | "husky": { 17 | "hooks": { 18 | "pre-commit": "lint-staged" 19 | } 20 | }, 21 | "lint-staged": { 22 | "*.{js,jsx}": [ 23 | "prettier --write", 24 | "git add" 25 | ], 26 | "*.{html,css,less,ejs}": [ 27 | "prettier --write", 28 | "git add" 29 | ] 30 | }, 31 | "repository": "git@github.com:salman0ansari/whatsapp-api-nodejs.git", 32 | "author": "Mohd Salman Ansari ", 33 | "license": "MIT", 34 | "dependencies": { 35 | "@whiskeysockets/baileys": "^6.1.0", 36 | "@adiwajshing/keyed-db": "^0.2.4", 37 | "axios": "^1.1.3", 38 | "dotenv": "^16.0.3", 39 | "ejs": "^3.1.7", 40 | "express": "^4.18.2", 41 | "express-exception-handler": "^1.3.23", 42 | "link-preview-js": "^3.0.0", 43 | "mongodb": "^4.12.1", 44 | "mongoose": "^6.7.4", 45 | "multer": "^1.4.5-lts.1", 46 | "pino": "^8.7.0", 47 | "qrcode": "^1.5.1", 48 | "sharp": "^0.30.5", 49 | "uuid": "^9.0.0" 50 | }, 51 | "devDependencies": { 52 | "eslint": "^8.28.0", 53 | "eslint-config-prettier": "^8.5.0", 54 | "husky": "^8.0.2", 55 | "lint-staged": "^13.0.4", 56 | "mocha": "^10.1.0", 57 | "nodemon": "^2.0.20", 58 | "prettier": "^2.8.0", 59 | "supertest": "^6.3.1" 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/config/config.js: -------------------------------------------------------------------------------- 1 | // Port number 2 | const PORT = process.env.PORT || '3333' 3 | const TOKEN = process.env.TOKEN || '' 4 | const PROTECT_ROUTES = !!( 5 | process.env.PROTECT_ROUTES && process.env.PROTECT_ROUTES === 'true' 6 | ) 7 | 8 | const RESTORE_SESSIONS_ON_START_UP = !!( 9 | process.env.RESTORE_SESSIONS_ON_START_UP && 10 | process.env.RESTORE_SESSIONS_ON_START_UP === 'true' 11 | ) 12 | 13 | const APP_URL = process.env.APP_URL || false 14 | 15 | const LOG_LEVEL = process.env.LOG_LEVEL 16 | 17 | const INSTANCE_MAX_RETRY_QR = process.env.INSTANCE_MAX_RETRY_QR || 2 18 | 19 | const CLIENT_PLATFORM = process.env.CLIENT_PLATFORM || 'Whatsapp MD' 20 | const CLIENT_BROWSER = process.env.CLIENT_BROWSER || 'Chrome' 21 | const CLIENT_VERSION = process.env.CLIENT_VERSION || '4.0.0' 22 | 23 | // Enable or disable mongodb 24 | const MONGODB_ENABLED = !!( 25 | process.env.MONGODB_ENABLED && process.env.MONGODB_ENABLED === 'true' 26 | ) 27 | // URL of the Mongo DB 28 | const MONGODB_URL = 29 | process.env.MONGODB_URL || 'mongodb://127.0.0.1:27017/WhatsAppInstance' 30 | // Enable or disable webhook globally on project 31 | const WEBHOOK_ENABLED = !!( 32 | process.env.WEBHOOK_ENABLED && process.env.WEBHOOK_ENABLED === 'true' 33 | ) 34 | // Webhook URL 35 | const WEBHOOK_URL = process.env.WEBHOOK_URL 36 | // Receive message content in webhook (Base64 format) 37 | const WEBHOOK_BASE64 = !!( 38 | process.env.WEBHOOK_BASE64 && process.env.WEBHOOK_BASE64 === 'true' 39 | ) 40 | // allowed events which should be sent to webhook 41 | const WEBHOOK_ALLOWED_EVENTS = process.env.WEBHOOK_ALLOWED_EVENTS?.split(',') || ['all'] 42 | // Mark messages as seen 43 | const MARK_MESSAGES_READ = !!( 44 | process.env.MARK_MESSAGES_READ && process.env.MARK_MESSAGES_READ === 'true' 45 | ) 46 | 47 | module.exports = { 48 | port: PORT, 49 | token: TOKEN, 50 | restoreSessionsOnStartup: RESTORE_SESSIONS_ON_START_UP, 51 | appUrl: APP_URL, 52 | log: { 53 | level: LOG_LEVEL, 54 | }, 55 | instance: { 56 | maxRetryQr: INSTANCE_MAX_RETRY_QR, 57 | }, 58 | mongoose: { 59 | enabled: MONGODB_ENABLED, 60 | url: MONGODB_URL, 61 | options: { 62 | // useCreateIndex: true, 63 | useNewUrlParser: true, 64 | useUnifiedTopology: true, 65 | }, 66 | }, 67 | browser: { 68 | platform: CLIENT_PLATFORM, 69 | browser: CLIENT_BROWSER, 70 | version: CLIENT_VERSION, 71 | }, 72 | webhookEnabled: WEBHOOK_ENABLED, 73 | webhookUrl: WEBHOOK_URL, 74 | webhookBase64: WEBHOOK_BASE64, 75 | protectRoutes: PROTECT_ROUTES, 76 | markMessagesRead: MARK_MESSAGES_READ, 77 | webhookAllowedEvents: WEBHOOK_ALLOWED_EVENTS 78 | } 79 | -------------------------------------------------------------------------------- /.github/workflows/codeql-analysis.yml: -------------------------------------------------------------------------------- 1 | # For most projects, this workflow file will not need changing; you simply need 2 | # to commit it to your repository. 3 | # 4 | # You may wish to alter this file to override the set of languages analyzed, 5 | # or to provide custom queries or build logic. 6 | # 7 | # ******** NOTE ******** 8 | # We have attempted to detect the languages in your repository. Please check 9 | # the `language` matrix defined below to confirm you have the correct set of 10 | # supported CodeQL languages. 11 | # 12 | name: 'CodeQL' 13 | 14 | on: 15 | push: 16 | branches: ['main'] 17 | pull_request: 18 | # The branches below must be a subset of the branches above 19 | branches: ['main'] 20 | schedule: 21 | - cron: '15 23 * * 4' 22 | 23 | jobs: 24 | analyze: 25 | name: Analyze 26 | runs-on: ubuntu-latest 27 | permissions: 28 | actions: read 29 | contents: read 30 | security-events: write 31 | 32 | strategy: 33 | fail-fast: false 34 | matrix: 35 | language: ['javascript'] 36 | # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ] 37 | # Learn more about CodeQL language support at https://aka.ms/codeql-docs/language-support 38 | 39 | steps: 40 | - name: Checkout repository 41 | uses: actions/checkout@v3 42 | 43 | # Initializes the CodeQL tools for scanning. 44 | - name: Initialize CodeQL 45 | uses: github/codeql-action/init@v2 46 | with: 47 | languages: ${{ matrix.language }} 48 | # If you wish to specify custom queries, you can do so here or in a config file. 49 | # By default, queries listed here will override any specified in a config file. 50 | # Prefix the list here with "+" to use these queries and those in the config file. 51 | 52 | # Details on CodeQL's query packs refer to : https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs 53 | # queries: security-extended,security-and-quality 54 | 55 | # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). 56 | # If this step fails, then you should remove it and run the build manually (see below) 57 | - name: Autobuild 58 | uses: github/codeql-action/autobuild@v2 59 | 60 | # ℹ️ Command-line programs to run using the OS shell. 61 | # 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun 62 | 63 | # If the Autobuild fails above, remove it and uncomment the following three lines. 64 | # modify them (or add more) to build your code if your project, please refer to the EXAMPLE below for guidance. 65 | 66 | # - run: | 67 | # echo "Run, Build Application using script" 68 | # ./location_of_script_within_repo/buildscript.sh 69 | 70 | - name: Perform CodeQL Analysis 71 | uses: github/codeql-action/analyze@v2 72 | -------------------------------------------------------------------------------- /src/api/controllers/message.controller.js: -------------------------------------------------------------------------------- 1 | exports.Text = async (req, res) => { 2 | const data = await WhatsAppInstances[req.query.key].sendTextMessage( 3 | req.body.id, 4 | req.body.message 5 | ) 6 | return res.status(201).json({ error: false, data: data }) 7 | } 8 | 9 | exports.Image = async (req, res) => { 10 | const data = await WhatsAppInstances[req.query.key].sendMediaFile( 11 | req.body.id, 12 | req.file, 13 | 'image', 14 | req.body?.caption 15 | ) 16 | return res.status(201).json({ error: false, data: data }) 17 | } 18 | 19 | exports.Video = async (req, res) => { 20 | const data = await WhatsAppInstances[req.query.key].sendMediaFile( 21 | req.body.id, 22 | req.file, 23 | 'video', 24 | req.body?.caption 25 | ) 26 | return res.status(201).json({ error: false, data: data }) 27 | } 28 | 29 | exports.Audio = async (req, res) => { 30 | const data = await WhatsAppInstances[req.query.key].sendMediaFile( 31 | req.body.id, 32 | req.file, 33 | 'audio' 34 | ) 35 | return res.status(201).json({ error: false, data: data }) 36 | } 37 | 38 | exports.Document = async (req, res) => { 39 | const data = await WhatsAppInstances[req.query.key].sendMediaFile( 40 | req.body.id, 41 | req.file, 42 | 'document', 43 | '', 44 | req.body.filename 45 | ) 46 | return res.status(201).json({ error: false, data: data }) 47 | } 48 | 49 | exports.Mediaurl = async (req, res) => { 50 | const data = await WhatsAppInstances[req.query.key].sendUrlMediaFile( 51 | req.body.id, 52 | req.body.url, 53 | req.body.type, // Types are [image, video, audio, document] 54 | req.body.mimetype, // mimeType of mediaFile / Check Common mimetypes in `https://mzl.la/3si3and` 55 | req.body.caption 56 | ) 57 | return res.status(201).json({ error: false, data: data }) 58 | } 59 | 60 | exports.Button = async (req, res) => { 61 | // console.log(res.body) 62 | const data = await WhatsAppInstances[req.query.key].sendButtonMessage( 63 | req.body.id, 64 | req.body.btndata 65 | ) 66 | return res.status(201).json({ error: false, data: data }) 67 | } 68 | 69 | exports.Contact = async (req, res) => { 70 | const data = await WhatsAppInstances[req.query.key].sendContactMessage( 71 | req.body.id, 72 | req.body.vcard 73 | ) 74 | return res.status(201).json({ error: false, data: data }) 75 | } 76 | 77 | exports.List = async (req, res) => { 78 | const data = await WhatsAppInstances[req.query.key].sendListMessage( 79 | req.body.id, 80 | req.body.msgdata 81 | ) 82 | return res.status(201).json({ error: false, data: data }) 83 | } 84 | 85 | exports.MediaButton = async (req, res) => { 86 | const data = await WhatsAppInstances[req.query.key].sendMediaButtonMessage( 87 | req.body.id, 88 | req.body.btndata 89 | ) 90 | return res.status(201).json({ error: false, data: data }) 91 | } 92 | 93 | exports.SetStatus = async (req, res) => { 94 | const presenceList = [ 95 | 'unavailable', 96 | 'available', 97 | 'composing', 98 | 'recording', 99 | 'paused', 100 | ] 101 | if (presenceList.indexOf(req.body.status) === -1) { 102 | return res.status(400).json({ 103 | error: true, 104 | message: 105 | 'status parameter must be one of ' + presenceList.join(', '), 106 | }) 107 | } 108 | 109 | const data = await WhatsAppInstances[req.query.key]?.setStatus( 110 | req.body.status, 111 | req.body.id 112 | ) 113 | return res.status(201).json({ error: false, data: data }) 114 | } 115 | 116 | exports.Read = async (req, res) => { 117 | const data = await WhatsAppInstances[req.query.key].readMessage(req.body.msg) 118 | return res.status(201).json({ error: false, data: data }) 119 | } 120 | 121 | exports.React = async (req, res) => { 122 | const data = await WhatsAppInstances[req.query.key].reactMessage(req.body.id, req.body.key, req.body.emoji) 123 | return res.status(201).json({ error: false, data: data }) 124 | } 125 | -------------------------------------------------------------------------------- /src/api/controllers/group.controller.js: -------------------------------------------------------------------------------- 1 | exports.create = async (req, res) => { 2 | const data = await WhatsAppInstances[req.query.key].createNewGroup( 3 | req.body.name, 4 | req.body.users 5 | ) 6 | return res.status(201).json({ error: false, data: data }) 7 | } 8 | 9 | exports.addNewParticipant = async (req, res) => { 10 | const data = await WhatsAppInstances[req.query.key].addNewParticipant( 11 | req.body.id, 12 | req.body.users 13 | ) 14 | return res.status(201).json({ error: false, data: data }) 15 | } 16 | 17 | exports.makeAdmin = async (req, res) => { 18 | const data = await WhatsAppInstances[req.query.key].makeAdmin( 19 | req.body.id, 20 | req.body.users 21 | ) 22 | return res.status(201).json({ error: false, data: data }) 23 | } 24 | 25 | exports.demoteAdmin = async (req, res) => { 26 | const data = await WhatsAppInstances[req.query.key].demoteAdmin( 27 | req.body.id, 28 | req.body.users 29 | ) 30 | return res.status(201).json({ error: false, data: data }) 31 | } 32 | 33 | exports.listAll = async (req, res) => { 34 | const data = await WhatsAppInstances[req.query.key].getAllGroups( 35 | req.query.key 36 | ) 37 | return res.status(201).json({ error: false, data: data }) 38 | } 39 | 40 | exports.leaveGroup = async (req, res) => { 41 | const data = await WhatsAppInstances[req.query.key].leaveGroup(req.query.id) 42 | return res.status(201).json({ error: false, data: data }) 43 | } 44 | 45 | exports.getInviteCodeGroup = async (req, res) => { 46 | const data = await WhatsAppInstances[req.query.key].getInviteCodeGroup( 47 | req.query.id 48 | ) 49 | return res 50 | .status(201) 51 | .json({ error: false, link: 'https://chat.whatsapp.com/' + data }) 52 | } 53 | 54 | exports.getInstanceInviteCodeGroup = async (req, res) => { 55 | const data = await WhatsAppInstances[ 56 | req.query.key 57 | ].getInstanceInviteCodeGroup(req.query.id) 58 | return res 59 | .status(201) 60 | .json({ error: false, link: 'https://chat.whatsapp.com/' + data }) 61 | } 62 | 63 | exports.getAllGroups = async (req, res) => { 64 | const instance = WhatsAppInstances[req.query.key] 65 | let data 66 | try { 67 | data = await instance.groupFetchAllParticipating() 68 | } catch (error) { 69 | data = {} 70 | } 71 | return res.json({ 72 | error: false, 73 | message: 'Instance fetched successfully', 74 | instance_data: data, 75 | }) 76 | } 77 | 78 | exports.groupParticipantsUpdate = async (req, res) => { 79 | const data = await WhatsAppInstances[req.query.key].groupParticipantsUpdate( 80 | req.body.id, 81 | req.body.users, 82 | req.body.action 83 | ) 84 | return res.status(201).json({ error: false, data: data }) 85 | } 86 | 87 | exports.groupSettingUpdate = async (req, res) => { 88 | const data = await WhatsAppInstances[req.query.key].groupSettingUpdate( 89 | req.body.id, 90 | req.body.action 91 | ) 92 | return res.status(201).json({ error: false, data: data }) 93 | } 94 | 95 | exports.groupUpdateSubject = async (req, res) => { 96 | const data = await WhatsAppInstances[req.query.key].groupUpdateSubject( 97 | req.body.id, 98 | req.body.subject 99 | ) 100 | return res.status(201).json({ error: false, data: data }) 101 | } 102 | 103 | exports.groupUpdateDescription = async (req, res) => { 104 | const data = await WhatsAppInstances[req.query.key].groupUpdateDescription( 105 | req.body.id, 106 | req.body.description 107 | ) 108 | return res.status(201).json({ error: false, data: data }) 109 | } 110 | 111 | exports.groupInviteInfo = async (req, res) => { 112 | const data = await WhatsAppInstances[req.query.key].groupGetInviteInfo( 113 | req.body.code 114 | ) 115 | return res.status(201).json({ error: false, data: data }) 116 | } 117 | 118 | exports.groupJoin = async (req, res) => { 119 | const data = await WhatsAppInstances[req.query.key].groupAcceptInvite( 120 | req.body.code 121 | ) 122 | return res.status(201).json({ error: false, data: data }) 123 | } 124 | -------------------------------------------------------------------------------- /src/api/helper/mongoAuthState.js: -------------------------------------------------------------------------------- 1 | const { proto } = require('@whiskeysockets/baileys/WAProto') 2 | const { 3 | Curve, 4 | signedKeyPair, 5 | } = require('@whiskeysockets/baileys/lib/Utils/crypto') 6 | const { 7 | generateRegistrationId, 8 | } = require('@whiskeysockets/baileys/lib/Utils/generics') 9 | const { randomBytes } = require('crypto') 10 | 11 | const initAuthCreds = () => { 12 | const identityKey = Curve.generateKeyPair() 13 | return { 14 | noiseKey: Curve.generateKeyPair(), 15 | signedIdentityKey: identityKey, 16 | signedPreKey: signedKeyPair(identityKey, 1), 17 | registrationId: generateRegistrationId(), 18 | advSecretKey: randomBytes(32).toString('base64'), 19 | processedHistoryMessages: [], 20 | nextPreKeyId: 1, 21 | firstUnuploadedPreKeyId: 1, 22 | accountSettings: { 23 | unarchiveChats: false, 24 | }, 25 | } 26 | } 27 | 28 | const BufferJSON = { 29 | replacer: (k, value) => { 30 | if ( 31 | Buffer.isBuffer(value) || 32 | value instanceof Uint8Array || 33 | value?.type === 'Buffer' 34 | ) { 35 | return { 36 | type: 'Buffer', 37 | data: Buffer.from(value?.data || value).toString('base64'), 38 | } 39 | } 40 | 41 | return value 42 | }, 43 | 44 | reviver: (_, value) => { 45 | if ( 46 | typeof value === 'object' && 47 | !!value && 48 | (value.buffer === true || value.type === 'Buffer') 49 | ) { 50 | const val = value.data || value.value 51 | return typeof val === 'string' 52 | ? Buffer.from(val, 'base64') 53 | : Buffer.from(val || []) 54 | } 55 | 56 | return value 57 | }, 58 | } 59 | 60 | module.exports = useMongoDBAuthState = async (collection) => { 61 | const writeData = (data, id) => { 62 | return collection.replaceOne( 63 | { _id: id }, 64 | JSON.parse(JSON.stringify(data, BufferJSON.replacer)), 65 | { upsert: true } 66 | ) 67 | } 68 | const readData = async (id) => { 69 | try { 70 | const data = JSON.stringify(await collection.findOne({ _id: id })) 71 | return JSON.parse(data, BufferJSON.reviver) 72 | } catch (error) { 73 | return null 74 | } 75 | } 76 | const removeData = async (id) => { 77 | try { 78 | await collection.deleteOne({ _id: id }) 79 | } catch (_a) {} 80 | } 81 | const creds = (await readData('creds')) || (0, initAuthCreds)() 82 | return { 83 | state: { 84 | creds, 85 | keys: { 86 | get: async (type, ids) => { 87 | const data = {} 88 | await Promise.all( 89 | ids.map(async (id) => { 90 | let value = await readData(`${type}-${id}`) 91 | if (type === 'app-state-sync-key') { 92 | value = 93 | proto.Message.AppStateSyncKeyData.fromObject( 94 | data 95 | ) 96 | } 97 | data[id] = value 98 | }) 99 | ) 100 | return data 101 | }, 102 | set: async (data) => { 103 | const tasks = [] 104 | for (const category of Object.keys(data)) { 105 | for (const id of Object.keys(data[category])) { 106 | const value = data[category][id] 107 | const key = `${category}-${id}` 108 | tasks.push( 109 | value ? writeData(value, key) : removeData(key) 110 | ) 111 | } 112 | } 113 | await Promise.all(tasks) 114 | }, 115 | }, 116 | }, 117 | saveCreds: () => { 118 | return writeData(creds, 'creds') 119 | }, 120 | } 121 | } 122 | -------------------------------------------------------------------------------- /src/api/controllers/instance.controller.js: -------------------------------------------------------------------------------- 1 | const { WhatsAppInstance } = require('../class/instance') 2 | const fs = require('fs') 3 | const path = require('path') 4 | const config = require('../../config/config') 5 | const { Session } = require('../class/session') 6 | 7 | exports.init = async (req, res) => { 8 | const key = req.query.key 9 | const webhook = !req.query.webhook ? false : req.query.webhook 10 | const webhookUrl = !req.query.webhookUrl ? null : req.query.webhookUrl 11 | const appUrl = config.appUrl || req.protocol + '://' + req.headers.host 12 | const instance = new WhatsAppInstance(key, webhook, webhookUrl) 13 | const data = await instance.init() 14 | WhatsAppInstances[data.key] = instance 15 | res.json({ 16 | error: false, 17 | message: 'Initializing successfully', 18 | key: data.key, 19 | webhook: { 20 | enabled: webhook, 21 | webhookUrl: webhookUrl, 22 | }, 23 | qrcode: { 24 | url: appUrl + '/instance/qr?key=' + data.key, 25 | }, 26 | browser: config.browser, 27 | }) 28 | } 29 | 30 | exports.qr = async (req, res) => { 31 | try { 32 | const qrcode = await WhatsAppInstances[req.query.key]?.instance.qr 33 | res.render('qrcode', { 34 | qrcode: qrcode, 35 | }) 36 | } catch { 37 | res.json({ 38 | qrcode: '', 39 | }) 40 | } 41 | } 42 | 43 | exports.qrbase64 = async (req, res) => { 44 | try { 45 | const qrcode = await WhatsAppInstances[req.query.key]?.instance.qr 46 | res.json({ 47 | error: false, 48 | message: 'QR Base64 fetched successfully', 49 | qrcode: qrcode, 50 | }) 51 | } catch { 52 | res.json({ 53 | qrcode: '', 54 | }) 55 | } 56 | } 57 | 58 | exports.info = async (req, res) => { 59 | const instance = WhatsAppInstances[req.query.key] 60 | let data 61 | try { 62 | data = await instance.getInstanceDetail(req.query.key) 63 | } catch (error) { 64 | data = {} 65 | } 66 | return res.json({ 67 | error: false, 68 | message: 'Instance fetched successfully', 69 | instance_data: data, 70 | }) 71 | } 72 | 73 | exports.restore = async (req, res, next) => { 74 | try { 75 | const session = new Session() 76 | let restoredSessions = await session.restoreSessions() 77 | return res.json({ 78 | error: false, 79 | message: 'All instances restored', 80 | data: restoredSessions, 81 | }) 82 | } catch (error) { 83 | next(error) 84 | } 85 | } 86 | 87 | exports.logout = async (req, res) => { 88 | let errormsg 89 | try { 90 | await WhatsAppInstances[req.query.key].instance?.sock?.logout() 91 | } catch (error) { 92 | errormsg = error 93 | } 94 | return res.json({ 95 | error: false, 96 | message: 'logout successfull', 97 | errormsg: errormsg ? errormsg : null, 98 | }) 99 | } 100 | 101 | exports.delete = async (req, res) => { 102 | let errormsg 103 | try { 104 | await WhatsAppInstances[req.query.key].deleteInstance(req.query.key) 105 | delete WhatsAppInstances[req.query.key] 106 | } catch (error) { 107 | errormsg = error 108 | } 109 | return res.json({ 110 | error: false, 111 | message: 'Instance deleted successfully', 112 | data: errormsg ? errormsg : null, 113 | }) 114 | } 115 | 116 | exports.list = async (req, res) => { 117 | if (req.query.active) { 118 | let instance = [] 119 | const db = mongoClient.db('whatsapp-api') 120 | const result = await db.listCollections().toArray() 121 | result.forEach((collection) => { 122 | instance.push(collection.name) 123 | }) 124 | 125 | return res.json({ 126 | error: false, 127 | message: 'All active instance', 128 | data: instance, 129 | }) 130 | } 131 | 132 | let instance = Object.keys(WhatsAppInstances).map(async (key) => 133 | WhatsAppInstances[key].getInstanceDetail(key) 134 | ) 135 | let data = await Promise.all(instance) 136 | 137 | return res.json({ 138 | error: false, 139 | message: 'All instance listed', 140 | data: data, 141 | }) 142 | } 143 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Archive Notice 🔒 2 | After three years, I've decided to archive this open-source WhatsApp API project. Your support and contributions have been incredible! 3 | 4 | While I'm no longer actively maintaining this project, I've been working on something new and exciting. It's not open-source, but it's a powerful API that provides advanced features for those who need them. If you're interested in exploring this, feel free to reach out for more information. 5 | 6 | Thank you once again for being a part of this journey. Keep building amazing things with technology! 7 | 8 | Best regards, 9 | 10 | @salman0ansari 11 | - mailto:salman0ansariii@gmail.com 12 | - https://telegram.dog/salman0ansari 13 | 14 | 15 | 16 | 17 | 18 |

whatsapp-api-nodejs Multi Device

19 |
20 |

21 | 22 |

23 |

24 | 25 |

26 | 27 | 28 | 29 | 30 |

31 | 32 | 33 |
34 | 35 | Telegram Badge 36 | 37 | 38 | Skype Badge 39 | 40 |
41 | 42 |

43 |
44 | 45 | --- 46 | 47 | An implementation of [Baileys](https://github.com/WhiskeySockets/Baileys) as a simple RESTful API service with multi device support just `download`, `install`, and `start` using, `simple` as that. 48 | 49 | # Libraries Used 50 | 51 | - [Baileys](https://github.com/WhiskeySockets/Baileys) 52 | - [Express](https://github.com/expressjs/express) 53 | 54 | # Installation 55 | 56 | 1. Download or clone this repo. 57 | 2. Enter to the project directory. 58 | 3. Execute `yarn install` to install the dependencies. 59 | 4. Copy `.env.example` to `.env` and set the environment variables. 60 | 61 | # Docker Compose 62 | 63 | 1. Follow the [Installation](#installation) procedure. 64 | 2. Update `.env` and set 65 | 66 | ``` 67 | MONGODB_ENABLED=true 68 | MONGODB_URL=mongodb://mongodb:27017/whatsapp_api 69 | ``` 70 | 71 | 3. Set your `TOKEN=` to a random string. 72 | 4. Execute 73 | 74 | ``` 75 | docker-compose up -d 76 | ``` 77 | 78 | # Configuration 79 | 80 | Edit environment variables on `.env` 81 | 82 | ```a 83 | Important: You must set TOKEN= to a random string to protect the route. 84 | ``` 85 | 86 | ```env 87 | # ================================== 88 | # SECURITY CONFIGURATION 89 | # ================================== 90 | TOKEN=RANDOM_STRING_HERE 91 | ``` 92 | 93 | # Usage 94 | 95 | 1. `DEVELOPMENT:` Execute `yarn dev` 96 | 2. `PRODUCTION:` Execute `yarn start` 97 | 98 | ## Generate basic instance using random key. 99 | 100 | To generate an Instance Key 101 | Using the route: 102 | 103 | ```bash 104 | curl --location --request GET 'localhost:3333/instance/init' \ 105 | --data-raw '' 106 | ``` 107 | 108 | Response: 109 | 110 | ```json 111 | { 112 | "error": false, 113 | "message": "Initializing successfull", 114 | "key": "d7e2abff-3ac8-44a9-a738-1b28e0fca8a5" 115 | } 116 | ``` 117 | 118 | ## WEBHOOK_ALLOWED_EVENTS 119 | 120 | You can set which events you want to send to webhook by setting the environment variable `WEBHOOK_ALLOWED_EVENTS` 121 | 122 | Set a comma seperated list of events you want to get notified about. 123 | 124 | Default value is `all` which will forward all events. 125 | 126 | Allowed values: 127 | 128 | - `connection` - receive all connection events 129 | - `connection:open` - receive open connection events 130 | - `connection:close` - receive close connection events 131 | - `presense` - receive presence events 132 | - `messages` - receive all messages event 133 | - `call` - receive all events related to calls 134 | - `call:terminate` - receive call terminate events 135 | - `call:offer` - receive call terminate event 136 | - `groups` - receive all events related to groups 137 | - `group_participants` - receive all events related to group participants 138 | 139 | You can also use the Baileys event format example: `messages.upsert` 140 | 141 | ## Generate custom instance with custom key and custom webhook. 142 | 143 | To generate a Custom Instance 144 | Using the route: 145 | 146 | ```bash 147 | curl --location --request GET 'localhost:3333/instance/init?key=CUSTOM_INSTANCE_KEY_HERE&webhook=true&webhookUrl=https://webhook.site/d7114704-97f6-4562-9a47-dcf66b07266d' \ 148 | --data-raw '' 149 | ``` 150 | 151 | Response: 152 | 153 | ```json 154 | { 155 | "error": false, 156 | "message": "Initializing successfull", 157 | "key": "CUSTOM_INSTANCE_KEY_HERE" 158 | } 159 | ``` 160 | 161 | # Using Key 162 | 163 | Save the value of the `key` from response. Then use this value to call all the routes. 164 | 165 | ## Postman Docs 166 | 167 | All routes are available as a postman collection. 168 | 169 | - https://documenter.getpostman.com/view/12514774/UVsPQkBq 170 | 171 | ## QR Code 172 | 173 | Visit [http://localhost:3333/instance/qr?key=INSTANCE_KEY_HERE](http://localhost:3333/instance/qr?key=INSTANCE_KEY_HERE) to view the QR Code and scan with your device. If you take too long to scan the QR Code, you will have to refresh the page. 174 | 175 | ## Send Message 176 | 177 | ```sh 178 | # /message/text?key=INSTANCE_KEY_HERE&id=PHONE-NUMBER-WITH-COUNTRY-CODE&message=MESSAGE 179 | 180 | curl --location --request POST 'localhost:3333/message/text?key=INSTANCE_KEY_HERE' \ 181 | --header 'Content-Type: application/x-www-form-urlencoded' \ 182 | --data-urlencode 'id=919999999999' \ 183 | --data-urlencode 'message=Hello World' 184 | ``` 185 | 186 | ## Routes 187 | 188 | | Route | Source File | 189 | | -------------------- | -------------------------------------------------------------------------------------------------------------------- | 190 | | Instance Routes | [instance.route.js](https://github.com/salman0ansari/whatsapp-api-nodejs/blob/main/src/api/routes/instance.route.js) | 191 | | Message Routes | [message.route.js](https://github.com/salman0ansari/whatsapp-api-nodejs/blob/main/src/api/routes/message.route.js) | 192 | | Group Routes | [group.route.js](https://github.com/salman0ansari/whatsapp-api-nodejs/blob/main/src/api/routes/group.route.js) | 193 | | Miscellaneous Routes | [misc.route.js](https://github.com/salman0ansari/whatsapp-api-nodejs/blob/main/src/api/routes/misc.route.js) | 194 | 195 | See all routes here [src/api/routes](https://github.com/salman0ansari/whatsapp-api-nodejs/tree/main/src/api/routes) 196 | 197 | # Note 198 | 199 | I can't guarantee or can be held responsible if you get blocked or banned by using this software. WhatsApp does not allow bots using unofficial methods on their platform, so this shouldn't be considered totally safe. 200 | 201 | # Legal 202 | 203 | - This code is in no way affiliated, authorized, maintained, sponsored or endorsed by WA (WhatsApp) or any of its affiliates or subsidiaries. 204 | - 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. 205 | - This is an independent and unofficial software Use at your own risk. 206 | - Do not spam people with this. 207 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /src/api/class/instance.js: -------------------------------------------------------------------------------- 1 | /* eslint-disable no-unsafe-optional-chaining */ 2 | const QRCode = require('qrcode') 3 | const pino = require('pino') 4 | const { 5 | default: makeWASocket, 6 | DisconnectReason, 7 | } = require('@whiskeysockets/baileys') 8 | const { unlinkSync } = require('fs') 9 | const { v4: uuidv4 } = require('uuid') 10 | const path = require('path') 11 | const processButton = require('../helper/processbtn') 12 | const generateVC = require('../helper/genVc') 13 | const Chat = require('../models/chat.model') 14 | const axios = require('axios') 15 | const config = require('../../config/config') 16 | const downloadMessage = require('../helper/downloadMsg') 17 | const logger = require('pino')() 18 | const useMongoDBAuthState = require('../helper/mongoAuthState') 19 | 20 | class WhatsAppInstance { 21 | socketConfig = { 22 | defaultQueryTimeoutMs: undefined, 23 | printQRInTerminal: false, 24 | logger: pino({ 25 | level: config.log.level, 26 | }), 27 | } 28 | key = '' 29 | authState 30 | allowWebhook = undefined 31 | webhook = undefined 32 | 33 | instance = { 34 | key: this.key, 35 | chats: [], 36 | qr: '', 37 | messages: [], 38 | qrRetry: 0, 39 | customWebhook: '', 40 | } 41 | 42 | axiosInstance = axios.create({ 43 | baseURL: config.webhookUrl, 44 | }) 45 | 46 | constructor(key, allowWebhook, webhook) { 47 | this.key = key ? key : uuidv4() 48 | this.instance.customWebhook = this.webhook ? this.webhook : webhook 49 | this.allowWebhook = config.webhookEnabled 50 | ? config.webhookEnabled 51 | : allowWebhook 52 | if (this.allowWebhook && this.instance.customWebhook !== null) { 53 | this.allowWebhook = true 54 | this.instance.customWebhook = webhook 55 | this.axiosInstance = axios.create({ 56 | baseURL: webhook, 57 | }) 58 | } 59 | } 60 | 61 | async SendWebhook(type, body, key) { 62 | if (!this.allowWebhook) return 63 | this.axiosInstance 64 | .post('', { 65 | type, 66 | body, 67 | instanceKey: key, 68 | }) 69 | .catch(() => {}) 70 | } 71 | 72 | async init() { 73 | this.collection = mongoClient.db('whatsapp-api').collection(this.key) 74 | const { state, saveCreds } = await useMongoDBAuthState(this.collection) 75 | this.authState = { state: state, saveCreds: saveCreds } 76 | this.socketConfig.auth = this.authState.state 77 | this.socketConfig.browser = Object.values(config.browser) 78 | this.instance.sock = makeWASocket(this.socketConfig) 79 | this.setHandler() 80 | return this 81 | } 82 | 83 | setHandler() { 84 | const sock = this.instance.sock 85 | // on credentials update save state 86 | sock?.ev.on('creds.update', this.authState.saveCreds) 87 | 88 | // on socket closed, opened, connecting 89 | sock?.ev.on('connection.update', async (update) => { 90 | const { connection, lastDisconnect, qr } = update 91 | 92 | if (connection === 'connecting') return 93 | 94 | if (connection === 'close') { 95 | // reconnect if not logged out 96 | if ( 97 | lastDisconnect?.error?.output?.statusCode !== 98 | DisconnectReason.loggedOut 99 | ) { 100 | await this.init() 101 | } else { 102 | await this.collection.drop().then((r) => { 103 | logger.info('STATE: Droped collection') 104 | }) 105 | this.instance.online = false 106 | } 107 | 108 | if ( 109 | [ 110 | 'all', 111 | 'connection', 112 | 'connection.update', 113 | 'connection:close', 114 | ].some((e) => config.webhookAllowedEvents.includes(e)) 115 | ) 116 | await this.SendWebhook( 117 | 'connection', 118 | { 119 | connection: connection, 120 | }, 121 | this.key 122 | ) 123 | } else if (connection === 'open') { 124 | if (config.mongoose.enabled) { 125 | let alreadyThere = await Chat.findOne({ 126 | key: this.key, 127 | }).exec() 128 | if (!alreadyThere) { 129 | const saveChat = new Chat({ key: this.key }) 130 | await saveChat.save() 131 | } 132 | } 133 | this.instance.online = true 134 | if ( 135 | [ 136 | 'all', 137 | 'connection', 138 | 'connection.update', 139 | 'connection:open', 140 | ].some((e) => config.webhookAllowedEvents.includes(e)) 141 | ) 142 | await this.SendWebhook( 143 | 'connection', 144 | { 145 | connection: connection, 146 | }, 147 | this.key 148 | ) 149 | } 150 | 151 | if (qr) { 152 | QRCode.toDataURL(qr).then((url) => { 153 | this.instance.qr = url 154 | this.instance.qrRetry++ 155 | if (this.instance.qrRetry >= config.instance.maxRetryQr) { 156 | // close WebSocket connection 157 | this.instance.sock.ws.close() 158 | // remove all events 159 | this.instance.sock.ev.removeAllListeners() 160 | this.instance.qr = ' ' 161 | logger.info('socket connection terminated') 162 | } 163 | }) 164 | } 165 | }) 166 | 167 | // sending presence 168 | sock?.ev.on('presence.update', async (json) => { 169 | if ( 170 | ['all', 'presence', 'presence.update'].some((e) => 171 | config.webhookAllowedEvents.includes(e) 172 | ) 173 | ) 174 | await this.SendWebhook('presence', json, this.key) 175 | }) 176 | 177 | // on receive all chats 178 | sock?.ev.on('chats.set', async ({ chats }) => { 179 | this.instance.chats = [] 180 | const recivedChats = chats.map((chat) => { 181 | return { 182 | ...chat, 183 | messages: [], 184 | } 185 | }) 186 | this.instance.chats.push(...recivedChats) 187 | await this.updateDb(this.instance.chats) 188 | await this.updateDbGroupsParticipants() 189 | }) 190 | 191 | // on recive new chat 192 | sock?.ev.on('chats.upsert', (newChat) => { 193 | //console.log('chats.upsert') 194 | //console.log(newChat) 195 | const chats = newChat.map((chat) => { 196 | return { 197 | ...chat, 198 | messages: [], 199 | } 200 | }) 201 | this.instance.chats.push(...chats) 202 | }) 203 | 204 | // on chat change 205 | sock?.ev.on('chats.update', (changedChat) => { 206 | //console.log('chats.update') 207 | //console.log(changedChat) 208 | changedChat.map((chat) => { 209 | const index = this.instance.chats.findIndex( 210 | (pc) => pc.id === chat.id 211 | ) 212 | const PrevChat = this.instance.chats[index] 213 | this.instance.chats[index] = { 214 | ...PrevChat, 215 | ...chat, 216 | } 217 | }) 218 | }) 219 | 220 | // on chat delete 221 | sock?.ev.on('chats.delete', (deletedChats) => { 222 | //console.log('chats.delete') 223 | //console.log(deletedChats) 224 | deletedChats.map((chat) => { 225 | const index = this.instance.chats.findIndex( 226 | (c) => c.id === chat 227 | ) 228 | this.instance.chats.splice(index, 1) 229 | }) 230 | }) 231 | 232 | // on new mssage 233 | sock?.ev.on('messages.upsert', async (m) => { 234 | //console.log('messages.upsert') 235 | //console.log(m) 236 | if (m.type === 'prepend') 237 | this.instance.messages.unshift(...m.messages) 238 | if (m.type !== 'notify') return 239 | 240 | // https://adiwajshing.github.io/Baileys/#reading-messages 241 | if (config.markMessagesRead) { 242 | const unreadMessages = m.messages.map((msg) => { 243 | return { 244 | remoteJid: msg.key.remoteJid, 245 | id: msg.key.id, 246 | participant: msg.key?.participant, 247 | } 248 | }) 249 | await sock.readMessages(unreadMessages) 250 | } 251 | 252 | this.instance.messages.unshift(...m.messages) 253 | 254 | m.messages.map(async (msg) => { 255 | if (!msg.message) return 256 | 257 | const messageType = Object.keys(msg.message)[0] 258 | if ( 259 | [ 260 | 'protocolMessage', 261 | 'senderKeyDistributionMessage', 262 | ].includes(messageType) 263 | ) 264 | return 265 | 266 | const webhookData = { 267 | key: this.key, 268 | ...msg, 269 | } 270 | 271 | if (messageType === 'conversation') { 272 | webhookData['text'] = m 273 | } 274 | if (config.webhookBase64) { 275 | switch (messageType) { 276 | case 'imageMessage': 277 | webhookData['msgContent'] = await downloadMessage( 278 | msg.message.imageMessage, 279 | 'image' 280 | ) 281 | break 282 | case 'videoMessage': 283 | webhookData['msgContent'] = await downloadMessage( 284 | msg.message.videoMessage, 285 | 'video' 286 | ) 287 | break 288 | case 'audioMessage': 289 | webhookData['msgContent'] = await downloadMessage( 290 | msg.message.audioMessage, 291 | 'audio' 292 | ) 293 | break 294 | default: 295 | webhookData['msgContent'] = '' 296 | break 297 | } 298 | } 299 | if ( 300 | ['all', 'messages', 'messages.upsert'].some((e) => 301 | config.webhookAllowedEvents.includes(e) 302 | ) 303 | ) 304 | await this.SendWebhook('message', webhookData, this.key) 305 | }) 306 | }) 307 | 308 | sock?.ev.on('messages.update', async (messages) => { 309 | //console.log('messages.update') 310 | //console.dir(messages); 311 | }) 312 | sock?.ws.on('CB:call', async (data) => { 313 | if (data.content) { 314 | if (data.content.find((e) => e.tag === 'offer')) { 315 | const content = data.content.find((e) => e.tag === 'offer') 316 | if ( 317 | ['all', 'call', 'CB:call', 'call:offer'].some((e) => 318 | config.webhookAllowedEvents.includes(e) 319 | ) 320 | ) 321 | await this.SendWebhook( 322 | 'call_offer', 323 | { 324 | id: content.attrs['call-id'], 325 | timestamp: parseInt(data.attrs.t), 326 | user: { 327 | id: data.attrs.from, 328 | platform: data.attrs.platform, 329 | platform_version: data.attrs.version, 330 | }, 331 | }, 332 | this.key 333 | ) 334 | } else if (data.content.find((e) => e.tag === 'terminate')) { 335 | const content = data.content.find( 336 | (e) => e.tag === 'terminate' 337 | ) 338 | 339 | if ( 340 | ['all', 'call', 'call:terminate'].some((e) => 341 | config.webhookAllowedEvents.includes(e) 342 | ) 343 | ) 344 | await this.SendWebhook( 345 | 'call_terminate', 346 | { 347 | id: content.attrs['call-id'], 348 | user: { 349 | id: data.attrs.from, 350 | }, 351 | timestamp: parseInt(data.attrs.t), 352 | reason: data.content[0].attrs.reason, 353 | }, 354 | this.key 355 | ) 356 | } 357 | } 358 | }) 359 | 360 | sock?.ev.on('groups.upsert', async (newChat) => { 361 | //console.log('groups.upsert') 362 | //console.log(newChat) 363 | this.createGroupByApp(newChat) 364 | if ( 365 | ['all', 'groups', 'groups.upsert'].some((e) => 366 | config.webhookAllowedEvents.includes(e) 367 | ) 368 | ) 369 | await this.SendWebhook( 370 | 'group_created', 371 | { 372 | data: newChat, 373 | }, 374 | this.key 375 | ) 376 | }) 377 | 378 | sock?.ev.on('groups.update', async (newChat) => { 379 | //console.log('groups.update') 380 | //console.log(newChat) 381 | this.updateGroupSubjectByApp(newChat) 382 | if ( 383 | ['all', 'groups', 'groups.update'].some((e) => 384 | config.webhookAllowedEvents.includes(e) 385 | ) 386 | ) 387 | await this.SendWebhook( 388 | 'group_updated', 389 | { 390 | data: newChat, 391 | }, 392 | this.key 393 | ) 394 | }) 395 | 396 | sock?.ev.on('group-participants.update', async (newChat) => { 397 | //console.log('group-participants.update') 398 | //console.log(newChat) 399 | this.updateGroupParticipantsByApp(newChat) 400 | if ( 401 | [ 402 | 'all', 403 | 'groups', 404 | 'group_participants', 405 | 'group-participants.update', 406 | ].some((e) => config.webhookAllowedEvents.includes(e)) 407 | ) 408 | await this.SendWebhook( 409 | 'group_participants_updated', 410 | { 411 | data: newChat, 412 | }, 413 | this.key 414 | ) 415 | }) 416 | } 417 | 418 | async deleteInstance(key) { 419 | try { 420 | await Chat.findOneAndDelete({ key: key }) 421 | } catch (e) { 422 | logger.error('Error updating document failed') 423 | } 424 | } 425 | 426 | async getInstanceDetail(key) { 427 | return { 428 | instance_key: key, 429 | phone_connected: this.instance?.online, 430 | webhookUrl: this.instance.customWebhook, 431 | user: this.instance?.online ? this.instance.sock?.user : {}, 432 | } 433 | } 434 | 435 | getWhatsAppId(id) { 436 | if (id.includes('@g.us') || id.includes('@s.whatsapp.net')) return id 437 | return id.includes('-') ? `${id}@g.us` : `${id}@s.whatsapp.net` 438 | } 439 | 440 | async verifyId(id) { 441 | if (id.includes('@g.us')) return true 442 | const [result] = await this.instance.sock?.onWhatsApp(id) 443 | if (result?.exists) return true 444 | throw new Error('no account exists') 445 | } 446 | 447 | async sendTextMessage(to, message) { 448 | await this.verifyId(this.getWhatsAppId(to)) 449 | const data = await this.instance.sock?.sendMessage( 450 | this.getWhatsAppId(to), 451 | { text: message } 452 | ) 453 | return data 454 | } 455 | 456 | async sendMediaFile(to, file, type, caption = '', filename) { 457 | await this.verifyId(this.getWhatsAppId(to)) 458 | const data = await this.instance.sock?.sendMessage( 459 | this.getWhatsAppId(to), 460 | { 461 | mimetype: file.mimetype, 462 | [type]: file.buffer, 463 | caption: caption, 464 | ptt: type === 'audio' ? true : false, 465 | fileName: filename ? filename : file.originalname, 466 | } 467 | ) 468 | return data 469 | } 470 | 471 | async sendUrlMediaFile(to, url, type, mimeType, caption = '') { 472 | await this.verifyId(this.getWhatsAppId(to)) 473 | 474 | const data = await this.instance.sock?.sendMessage( 475 | this.getWhatsAppId(to), 476 | { 477 | [type]: { 478 | url: url, 479 | }, 480 | caption: caption, 481 | mimetype: mimeType, 482 | } 483 | ) 484 | return data 485 | } 486 | 487 | async DownloadProfile(of) { 488 | await this.verifyId(this.getWhatsAppId(of)) 489 | const ppUrl = await this.instance.sock?.profilePictureUrl( 490 | this.getWhatsAppId(of), 491 | 'image' 492 | ) 493 | return ppUrl 494 | } 495 | 496 | async getUserStatus(of) { 497 | await this.verifyId(this.getWhatsAppId(of)) 498 | const status = await this.instance.sock?.fetchStatus( 499 | this.getWhatsAppId(of) 500 | ) 501 | return status 502 | } 503 | 504 | async blockUnblock(to, data) { 505 | await this.verifyId(this.getWhatsAppId(to)) 506 | const status = await this.instance.sock?.updateBlockStatus( 507 | this.getWhatsAppId(to), 508 | data 509 | ) 510 | return status 511 | } 512 | 513 | async sendButtonMessage(to, data) { 514 | await this.verifyId(this.getWhatsAppId(to)) 515 | const result = await this.instance.sock?.sendMessage( 516 | this.getWhatsAppId(to), 517 | { 518 | templateButtons: processButton(data.buttons), 519 | text: data.text ?? '', 520 | footer: data.footerText ?? '', 521 | viewOnce: true, 522 | } 523 | ) 524 | return result 525 | } 526 | 527 | async sendContactMessage(to, data) { 528 | await this.verifyId(this.getWhatsAppId(to)) 529 | const vcard = generateVC(data) 530 | const result = await this.instance.sock?.sendMessage( 531 | await this.getWhatsAppId(to), 532 | { 533 | contacts: { 534 | displayName: data.fullName, 535 | contacts: [{ displayName: data.fullName, vcard }], 536 | }, 537 | } 538 | ) 539 | return result 540 | } 541 | 542 | async sendListMessage(to, data) { 543 | await this.verifyId(this.getWhatsAppId(to)) 544 | const result = await this.instance.sock?.sendMessage( 545 | this.getWhatsAppId(to), 546 | { 547 | text: data.text, 548 | sections: data.sections, 549 | buttonText: data.buttonText, 550 | footer: data.description, 551 | title: data.title, 552 | viewOnce: true, 553 | } 554 | ) 555 | return result 556 | } 557 | 558 | async sendMediaButtonMessage(to, data) { 559 | await this.verifyId(this.getWhatsAppId(to)) 560 | 561 | const result = await this.instance.sock?.sendMessage( 562 | this.getWhatsAppId(to), 563 | { 564 | [data.mediaType]: { 565 | url: data.image, 566 | }, 567 | footer: data.footerText ?? '', 568 | caption: data.text, 569 | templateButtons: processButton(data.buttons), 570 | mimetype: data.mimeType, 571 | viewOnce: true, 572 | } 573 | ) 574 | return result 575 | } 576 | 577 | async setStatus(status, to) { 578 | await this.verifyId(this.getWhatsAppId(to)) 579 | 580 | const result = await this.instance.sock?.sendPresenceUpdate(status, to) 581 | return result 582 | } 583 | 584 | // change your display picture or a group's 585 | async updateProfilePicture(id, url) { 586 | try { 587 | const img = await axios.get(url, { responseType: 'arraybuffer' }) 588 | const res = await this.instance.sock?.updateProfilePicture( 589 | id, 590 | img.data 591 | ) 592 | return res 593 | } catch (e) { 594 | //console.log(e) 595 | return { 596 | error: true, 597 | message: 'Unable to update profile picture', 598 | } 599 | } 600 | } 601 | 602 | // get user or group object from db by id 603 | async getUserOrGroupById(id) { 604 | try { 605 | let Chats = await this.getChat() 606 | const group = Chats.find((c) => c.id === this.getWhatsAppId(id)) 607 | if (!group) 608 | throw new Error( 609 | 'unable to get group, check if the group exists' 610 | ) 611 | return group 612 | } catch (e) { 613 | logger.error(e) 614 | logger.error('Error get group failed') 615 | } 616 | } 617 | 618 | // Group Methods 619 | parseParticipants(users) { 620 | return users.map((users) => this.getWhatsAppId(users)) 621 | } 622 | 623 | async updateDbGroupsParticipants() { 624 | try { 625 | let groups = await this.groupFetchAllParticipating() 626 | let Chats = await this.getChat() 627 | if (groups && Chats) { 628 | for (const [key, value] of Object.entries(groups)) { 629 | let group = Chats.find((c) => c.id === value.id) 630 | if (group) { 631 | let participants = [] 632 | for (const [ 633 | key_participant, 634 | participant, 635 | ] of Object.entries(value.participants)) { 636 | participants.push(participant) 637 | } 638 | group.participant = participants 639 | if (value.creation) { 640 | group.creation = value.creation 641 | } 642 | if (value.subjectOwner) { 643 | group.subjectOwner = value.subjectOwner 644 | } 645 | Chats.filter((c) => c.id === value.id)[0] = group 646 | } 647 | } 648 | await this.updateDb(Chats) 649 | } 650 | } catch (e) { 651 | logger.error(e) 652 | logger.error('Error updating groups failed') 653 | } 654 | } 655 | 656 | async createNewGroup(name, users) { 657 | try { 658 | const group = await this.instance.sock?.groupCreate( 659 | name, 660 | users.map(this.getWhatsAppId) 661 | ) 662 | return group 663 | } catch (e) { 664 | logger.error(e) 665 | logger.error('Error create new group failed') 666 | } 667 | } 668 | 669 | async addNewParticipant(id, users) { 670 | try { 671 | const res = await this.instance.sock?.groupAdd( 672 | this.getWhatsAppId(id), 673 | this.parseParticipants(users) 674 | ) 675 | return res 676 | } catch { 677 | return { 678 | error: true, 679 | message: 680 | 'Unable to add participant, you must be an admin in this group', 681 | } 682 | } 683 | } 684 | 685 | async makeAdmin(id, users) { 686 | try { 687 | const res = await this.instance.sock?.groupMakeAdmin( 688 | this.getWhatsAppId(id), 689 | this.parseParticipants(users) 690 | ) 691 | return res 692 | } catch { 693 | return { 694 | error: true, 695 | message: 696 | 'unable to promote some participants, check if you are admin in group or participants exists', 697 | } 698 | } 699 | } 700 | 701 | async demoteAdmin(id, users) { 702 | try { 703 | const res = await this.instance.sock?.groupDemoteAdmin( 704 | this.getWhatsAppId(id), 705 | this.parseParticipants(users) 706 | ) 707 | return res 708 | } catch { 709 | return { 710 | error: true, 711 | message: 712 | 'unable to demote some participants, check if you are admin in group or participants exists', 713 | } 714 | } 715 | } 716 | 717 | async getAllGroups() { 718 | let Chats = await this.getChat() 719 | return Chats.filter((c) => c.id.includes('@g.us')).map((data, i) => { 720 | return { 721 | index: i, 722 | name: data.name, 723 | jid: data.id, 724 | participant: data.participant, 725 | creation: data.creation, 726 | subjectOwner: data.subjectOwner, 727 | } 728 | }) 729 | } 730 | 731 | async leaveGroup(id) { 732 | try { 733 | let Chats = await this.getChat() 734 | const group = Chats.find((c) => c.id === id) 735 | if (!group) throw new Error('no group exists') 736 | return await this.instance.sock?.groupLeave(id) 737 | } catch (e) { 738 | logger.error(e) 739 | logger.error('Error leave group failed') 740 | } 741 | } 742 | 743 | async getInviteCodeGroup(id) { 744 | try { 745 | let Chats = await this.getChat() 746 | const group = Chats.find((c) => c.id === id) 747 | if (!group) 748 | throw new Error( 749 | 'unable to get invite code, check if the group exists' 750 | ) 751 | return await this.instance.sock?.groupInviteCode(id) 752 | } catch (e) { 753 | logger.error(e) 754 | logger.error('Error get invite group failed') 755 | } 756 | } 757 | 758 | async getInstanceInviteCodeGroup(id) { 759 | try { 760 | return await this.instance.sock?.groupInviteCode(id) 761 | } catch (e) { 762 | logger.error(e) 763 | logger.error('Error get invite group failed') 764 | } 765 | } 766 | 767 | // get Chat object from db 768 | async getChat(key = this.key) { 769 | let dbResult = await Chat.findOne({ key: key }).exec() 770 | let ChatObj = dbResult.chat 771 | return ChatObj 772 | } 773 | 774 | // create new group by application 775 | async createGroupByApp(newChat) { 776 | try { 777 | let Chats = await this.getChat() 778 | let group = { 779 | id: newChat[0].id, 780 | name: newChat[0].subject, 781 | participant: newChat[0].participants, 782 | messages: [], 783 | creation: newChat[0].creation, 784 | subjectOwner: newChat[0].subjectOwner, 785 | } 786 | Chats.push(group) 787 | await this.updateDb(Chats) 788 | } catch (e) { 789 | logger.error(e) 790 | logger.error('Error updating document failed') 791 | } 792 | } 793 | 794 | async updateGroupSubjectByApp(newChat) { 795 | //console.log(newChat) 796 | try { 797 | if (newChat[0] && newChat[0].subject) { 798 | let Chats = await this.getChat() 799 | Chats.find((c) => c.id === newChat[0].id).name = 800 | newChat[0].subject 801 | await this.updateDb(Chats) 802 | } 803 | } catch (e) { 804 | logger.error(e) 805 | logger.error('Error updating document failed') 806 | } 807 | } 808 | 809 | async updateGroupParticipantsByApp(newChat) { 810 | //console.log(newChat) 811 | try { 812 | if (newChat && newChat.id) { 813 | let Chats = await this.getChat() 814 | let chat = Chats.find((c) => c.id === newChat.id) 815 | let is_owner = false 816 | if (chat) { 817 | if (chat.participant == undefined) { 818 | chat.participant = [] 819 | } 820 | if (chat.participant && newChat.action == 'add') { 821 | for (const participant of newChat.participants) { 822 | chat.participant.push({ 823 | id: participant, 824 | admin: null, 825 | }) 826 | } 827 | } 828 | if (chat.participant && newChat.action == 'remove') { 829 | for (const participant of newChat.participants) { 830 | // remove group if they are owner 831 | if (chat.subjectOwner == participant) { 832 | is_owner = true 833 | } 834 | chat.participant = chat.participant.filter( 835 | (p) => p.id != participant 836 | ) 837 | } 838 | } 839 | if (chat.participant && newChat.action == 'demote') { 840 | for (const participant of newChat.participants) { 841 | if ( 842 | chat.participant.filter( 843 | (p) => p.id == participant 844 | )[0] 845 | ) { 846 | chat.participant.filter( 847 | (p) => p.id == participant 848 | )[0].admin = null 849 | } 850 | } 851 | } 852 | if (chat.participant && newChat.action == 'promote') { 853 | for (const participant of newChat.participants) { 854 | if ( 855 | chat.participant.filter( 856 | (p) => p.id == participant 857 | )[0] 858 | ) { 859 | chat.participant.filter( 860 | (p) => p.id == participant 861 | )[0].admin = 'superadmin' 862 | } 863 | } 864 | } 865 | if (is_owner) { 866 | Chats = Chats.filter((c) => c.id !== newChat.id) 867 | } else { 868 | Chats.filter((c) => c.id === newChat.id)[0] = chat 869 | } 870 | await this.updateDb(Chats) 871 | } 872 | } 873 | } catch (e) { 874 | logger.error(e) 875 | logger.error('Error updating document failed') 876 | } 877 | } 878 | 879 | async groupFetchAllParticipating() { 880 | try { 881 | const result = 882 | await this.instance.sock?.groupFetchAllParticipating() 883 | return result 884 | } catch (e) { 885 | logger.error('Error group fetch all participating failed') 886 | } 887 | } 888 | 889 | // update promote demote remove 890 | async groupParticipantsUpdate(id, users, action) { 891 | try { 892 | const res = await this.instance.sock?.groupParticipantsUpdate( 893 | this.getWhatsAppId(id), 894 | this.parseParticipants(users), 895 | action 896 | ) 897 | return res 898 | } catch (e) { 899 | //console.log(e) 900 | return { 901 | error: true, 902 | message: 903 | 'unable to ' + 904 | action + 905 | ' some participants, check if you are admin in group or participants exists', 906 | } 907 | } 908 | } 909 | 910 | // update group settings like 911 | // only allow admins to send messages 912 | async groupSettingUpdate(id, action) { 913 | try { 914 | const res = await this.instance.sock?.groupSettingUpdate( 915 | this.getWhatsAppId(id), 916 | action 917 | ) 918 | return res 919 | } catch (e) { 920 | //console.log(e) 921 | return { 922 | error: true, 923 | message: 924 | 'unable to ' + action + ' check if you are admin in group', 925 | } 926 | } 927 | } 928 | 929 | async groupUpdateSubject(id, subject) { 930 | try { 931 | const res = await this.instance.sock?.groupUpdateSubject( 932 | this.getWhatsAppId(id), 933 | subject 934 | ) 935 | return res 936 | } catch (e) { 937 | //console.log(e) 938 | return { 939 | error: true, 940 | message: 941 | 'unable to update subject check if you are admin in group', 942 | } 943 | } 944 | } 945 | 946 | async groupUpdateDescription(id, description) { 947 | try { 948 | const res = await this.instance.sock?.groupUpdateDescription( 949 | this.getWhatsAppId(id), 950 | description 951 | ) 952 | return res 953 | } catch (e) { 954 | //console.log(e) 955 | return { 956 | error: true, 957 | message: 958 | 'unable to update description check if you are admin in group', 959 | } 960 | } 961 | } 962 | 963 | // update db document -> chat 964 | async updateDb(object) { 965 | try { 966 | await Chat.updateOne({ key: this.key }, { chat: object }) 967 | } catch (e) { 968 | logger.error('Error updating document failed') 969 | } 970 | } 971 | 972 | async readMessage(msgObj) { 973 | try { 974 | const key = { 975 | remoteJid: msgObj.remoteJid, 976 | id: msgObj.id, 977 | participant: msgObj?.participant, // required when reading a msg from group 978 | } 979 | const res = await this.instance.sock?.readMessages([key]) 980 | return res 981 | } catch (e) { 982 | logger.error('Error read message failed') 983 | } 984 | } 985 | 986 | async reactMessage(id, key, emoji) { 987 | try { 988 | const reactionMessage = { 989 | react: { 990 | text: emoji, // use an empty string to remove the reaction 991 | key: key, 992 | }, 993 | } 994 | const res = await this.instance.sock?.sendMessage( 995 | this.getWhatsAppId(id), 996 | reactionMessage 997 | ) 998 | return res 999 | } catch (e) { 1000 | logger.error('Error react message failed') 1001 | } 1002 | } 1003 | } 1004 | 1005 | exports.WhatsAppInstance = WhatsAppInstance 1006 | -------------------------------------------------------------------------------- /whatsapp-api-nodejs.postman_collection.json: -------------------------------------------------------------------------------- 1 | { 2 | "info": { 3 | "_postman_id": "9db85f5b-971f-4218-8f0b-7eca66651a01", 4 | "name": "whatsapp-api-nodejs", 5 | "description": "## **API** Documentation\n\n### whatsapp-api-nodejs\n\n[https://github.com/salman0ansari/whatsapp-api-nodejs](https://github.com/salman0ansari/whatsapp-api-nodejs)\n\nAn implementation of [Baileys](https://github.com/adiwajshing/Baileys/) as a simple RESTful API service with multi device support just `download`, `install`, and `start` using, `simple` as that.\n\nBuild with NodeJs + Express\n\n* * *\n\n## Legal Notice\n\n* This code is in no way affiliated, authorized, maintained, sponsored or endorsed by WA(WhatsApp) or any of its affiliates or subsidiaries.\n* The official WhatsApp website can be found at [https://whatsapp.com](https://whatsapp.com). \"WhatsApp\" as well as related names, marks, emblems and images are registered trademarks of their respective owners.\n* This is an independent and unofficial software Use at your own risk.\n* Do not spam people with this.\n \n\n* * *\n\n## Contact\n\nDeveloper: [https://github.com/salman0ansari](https://github.com/salman0ansari)\n\nEmail: salman0ansari@pm.me\n\nTelegram: @salman0ansari", 6 | "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json" 7 | }, 8 | "item": [ 9 | { 10 | "name": "Instance", 11 | "item": [ 12 | { 13 | "name": "Init Instance", 14 | "protocolProfileBehavior": { 15 | "disableBodyPruning": true 16 | }, 17 | "request": { 18 | "method": "GET", 19 | "header": [], 20 | "body": { 21 | "mode": "raw", 22 | "raw": "" 23 | }, 24 | "url": { 25 | "raw": "{{baseUrl}}/instance/init?key=123&token=RANDOM_STRING_HERE", 26 | "host": [ 27 | "{{baseUrl}}" 28 | ], 29 | "path": [ 30 | "instance", 31 | "init" 32 | ], 33 | "query": [ 34 | { 35 | "key": "webhook", 36 | "value": "true", 37 | "description": "Allow Webhook\n(Optional) ", 38 | "disabled": true 39 | }, 40 | { 41 | "key": "key", 42 | "value": "123", 43 | "description": "Custom Instance Key\n(Optional)" 44 | }, 45 | { 46 | "key": "token", 47 | "value": "RANDOM_STRING_HERE" 48 | } 49 | ] 50 | }, 51 | "description": "Init a new WhatsApp instance" 52 | }, 53 | "response": [] 54 | }, 55 | { 56 | "name": "Scan QR", 57 | "request": { 58 | "method": "GET", 59 | "header": [], 60 | "url": { 61 | "raw": "{{baseUrl}}/instance/qr?key={{instance_key}}", 62 | "host": [ 63 | "{{baseUrl}}" 64 | ], 65 | "path": [ 66 | "instance", 67 | "qr" 68 | ], 69 | "query": [ 70 | { 71 | "key": "key", 72 | "value": "{{instance_key}}", 73 | "description": "Instance Key\n(Required)" 74 | } 75 | ] 76 | }, 77 | "description": "Get an instance QrCode" 78 | }, 79 | "response": [] 80 | }, 81 | { 82 | "name": "Get QR in Base64", 83 | "request": { 84 | "method": "GET", 85 | "header": [], 86 | "url": { 87 | "raw": "{{baseUrl}}/instance/qrbase64?key={{instance_key}}", 88 | "host": [ 89 | "{{baseUrl}}" 90 | ], 91 | "path": [ 92 | "instance", 93 | "qrbase64" 94 | ], 95 | "query": [ 96 | { 97 | "key": "key", 98 | "value": "{{instance_key}}", 99 | "description": "Instance Key\n(Required)" 100 | } 101 | ] 102 | } 103 | }, 104 | "response": [] 105 | }, 106 | { 107 | "name": "Instance Info", 108 | "request": { 109 | "method": "GET", 110 | "header": [], 111 | "url": { 112 | "raw": "{{baseUrl}}/instance/info?key={{instance_key}}", 113 | "host": [ 114 | "{{baseUrl}}" 115 | ], 116 | "path": [ 117 | "instance", 118 | "info" 119 | ], 120 | "query": [ 121 | { 122 | "key": "key", 123 | "value": "{{instance_key}}", 124 | "description": "Instance Key\n(Required)" 125 | } 126 | ] 127 | }, 128 | "description": "Get an instance info" 129 | }, 130 | "response": [] 131 | }, 132 | { 133 | "name": "Restore All Instances", 134 | "request": { 135 | "method": "GET", 136 | "header": [], 137 | "url": { 138 | "raw": "{{baseUrl}}/instance/restore", 139 | "host": [ 140 | "{{baseUrl}}" 141 | ], 142 | "path": [ 143 | "instance", 144 | "restore" 145 | ] 146 | } 147 | }, 148 | "response": [] 149 | }, 150 | { 151 | "name": "Delete Instance", 152 | "request": { 153 | "method": "DELETE", 154 | "header": [], 155 | "url": { 156 | "raw": "{{baseUrl}}/instance/delete?key={{instance_key}}", 157 | "host": [ 158 | "{{baseUrl}}" 159 | ], 160 | "path": [ 161 | "instance", 162 | "delete" 163 | ], 164 | "query": [ 165 | { 166 | "key": "key", 167 | "value": "{{instance_key}}", 168 | "description": "Instance Key\n(Required)" 169 | } 170 | ] 171 | }, 172 | "description": "Delete an instance" 173 | }, 174 | "response": [] 175 | }, 176 | { 177 | "name": "Logout Instance", 178 | "request": { 179 | "method": "DELETE", 180 | "header": [], 181 | "url": { 182 | "raw": "{{baseUrl}}/instance/logout?key={{instance_key}}", 183 | "host": [ 184 | "{{baseUrl}}" 185 | ], 186 | "path": [ 187 | "instance", 188 | "logout" 189 | ], 190 | "query": [ 191 | { 192 | "key": "key", 193 | "value": "{{instance_key}}", 194 | "description": "Instance Key\n(Required)" 195 | } 196 | ] 197 | }, 198 | "description": "Logout WhatsApp session from mobile" 199 | }, 200 | "response": [] 201 | }, 202 | { 203 | "name": "List All Sessions", 204 | "request": { 205 | "method": "GET", 206 | "header": [], 207 | "url": { 208 | "raw": "{{baseUrl}}/instance/list", 209 | "host": [ 210 | "{{baseUrl}}" 211 | ], 212 | "path": [ 213 | "instance", 214 | "list" 215 | ], 216 | "query": [ 217 | { 218 | "key": "active", 219 | "value": "true", 220 | "description": "List Active Instances\n(Optional) ", 221 | "disabled": true 222 | } 223 | ] 224 | }, 225 | "description": "List all Instances" 226 | }, 227 | "response": [] 228 | } 229 | ] 230 | }, 231 | { 232 | "name": "Message", 233 | "item": [ 234 | { 235 | "name": "Send Text Message", 236 | "request": { 237 | "method": "POST", 238 | "header": [], 239 | "body": { 240 | "mode": "urlencoded", 241 | "urlencoded": [ 242 | { 243 | "key": "id", 244 | "value": "", 245 | "description": "Recipient Id or Group Id\n(Required)", 246 | "type": "text" 247 | }, 248 | { 249 | "key": "message", 250 | "value": "", 251 | "description": "Message to Send\n(Required)", 252 | "type": "text" 253 | } 254 | ] 255 | }, 256 | "url": { 257 | "raw": "{{baseUrl}}/message/text?key={{instance_key}}", 258 | "host": [ 259 | "{{baseUrl}}" 260 | ], 261 | "path": [ 262 | "message", 263 | "text" 264 | ], 265 | "query": [ 266 | { 267 | "key": "key", 268 | "value": "{{instance_key}}", 269 | "description": "Instance Key\n(Required)" 270 | } 271 | ] 272 | }, 273 | "description": "Send a text message to WhatsApp User or Group" 274 | }, 275 | "response": [] 276 | }, 277 | { 278 | "name": "Send Image Message", 279 | "request": { 280 | "method": "POST", 281 | "header": [], 282 | "body": { 283 | "mode": "formdata", 284 | "formdata": [ 285 | { 286 | "key": "file", 287 | "description": "Image you want to send\n(Required) \n", 288 | "type": "file", 289 | "src": [] 290 | }, 291 | { 292 | "key": "id", 293 | "value": "", 294 | "description": "Recipient Id or Group Id\n(Required)", 295 | "type": "text" 296 | }, 297 | { 298 | "key": "caption", 299 | "value": "", 300 | "description": "Message Caption\n(Optional) ", 301 | "type": "text" 302 | } 303 | ] 304 | }, 305 | "url": { 306 | "raw": "{{baseUrl}}/message/image?key={{instance_key}}", 307 | "host": [ 308 | "{{baseUrl}}" 309 | ], 310 | "path": [ 311 | "message", 312 | "image" 313 | ], 314 | "query": [ 315 | { 316 | "key": "key", 317 | "value": "{{instance_key}}", 318 | "description": "Instance Key\n(Required)" 319 | }, 320 | { 321 | "key": "id", 322 | "value": "", 323 | "disabled": true 324 | }, 325 | { 326 | "key": "caption", 327 | "value": "", 328 | "disabled": true 329 | } 330 | ] 331 | }, 332 | "description": "Send an image message to WhatsApp User" 333 | }, 334 | "response": [] 335 | }, 336 | { 337 | "name": "Send Video Message", 338 | "request": { 339 | "method": "POST", 340 | "header": [], 341 | "body": { 342 | "mode": "formdata", 343 | "formdata": [ 344 | { 345 | "key": "file", 346 | "description": "Video You Want to Send\n(Required)", 347 | "type": "file", 348 | "src": [] 349 | }, 350 | { 351 | "key": "id", 352 | "value": "", 353 | "description": "Recipient Id or Group Id\n(Required)", 354 | "type": "text" 355 | }, 356 | { 357 | "key": "caption", 358 | "value": "", 359 | "description": "Message Caption\n(Optional) ", 360 | "type": "text" 361 | } 362 | ] 363 | }, 364 | "url": { 365 | "raw": "{{baseUrl}}/message/video?key={{instance_key}}", 366 | "host": [ 367 | "{{baseUrl}}" 368 | ], 369 | "path": [ 370 | "message", 371 | "video" 372 | ], 373 | "query": [ 374 | { 375 | "key": "key", 376 | "value": "{{instance_key}}", 377 | "description": "Instance Key\n(Required)" 378 | } 379 | ] 380 | }, 381 | "description": "Send a video message to WhatsApp User" 382 | }, 383 | "response": [] 384 | }, 385 | { 386 | "name": "Send Audio Message", 387 | "protocolProfileBehavior": { 388 | "disabledSystemHeaders": {} 389 | }, 390 | "request": { 391 | "method": "POST", 392 | "header": [], 393 | "body": { 394 | "mode": "formdata", 395 | "formdata": [ 396 | { 397 | "key": "file", 398 | "description": "Audio You Want to Send\n(Required)", 399 | "type": "file", 400 | "src": [] 401 | }, 402 | { 403 | "key": "id", 404 | "value": "", 405 | "description": "Recipient Id or Group Id\n(Required)", 406 | "type": "text" 407 | } 408 | ] 409 | }, 410 | "url": { 411 | "raw": "{{baseUrl}}/message/audio?key={{instance_key}}", 412 | "host": [ 413 | "{{baseUrl}}" 414 | ], 415 | "path": [ 416 | "message", 417 | "audio" 418 | ], 419 | "query": [ 420 | { 421 | "key": "key", 422 | "value": "{{instance_key}}", 423 | "description": "Instance Key\n(Required)" 424 | } 425 | ] 426 | }, 427 | "description": "Send an audio message to WhatsApp User" 428 | }, 429 | "response": [] 430 | }, 431 | { 432 | "name": "Send Document Message", 433 | "request": { 434 | "method": "POST", 435 | "header": [], 436 | "body": { 437 | "mode": "formdata", 438 | "formdata": [ 439 | { 440 | "key": "file", 441 | "description": "Document You Want to Send\n(Required)", 442 | "type": "file", 443 | "src": [] 444 | }, 445 | { 446 | "key": "id", 447 | "value": "", 448 | "description": "Recipient Id or Group Id\n(Required)", 449 | "type": "text" 450 | }, 451 | { 452 | "key": "filename", 453 | "value": "", 454 | "description": "Custom File Name\n(Optional)", 455 | "type": "text" 456 | } 457 | ] 458 | }, 459 | "url": { 460 | "raw": "{{baseUrl}}/message/doc?key={{instance_key}}", 461 | "host": [ 462 | "{{baseUrl}}" 463 | ], 464 | "path": [ 465 | "message", 466 | "doc" 467 | ], 468 | "query": [ 469 | { 470 | "key": "key", 471 | "value": "{{instance_key}}", 472 | "description": "Instance Key\n(Required)" 473 | } 474 | ] 475 | }, 476 | "description": "Send a document message to WhatsApp User" 477 | }, 478 | "response": [] 479 | }, 480 | { 481 | "name": "Send File URL", 482 | "request": { 483 | "method": "POST", 484 | "header": [], 485 | "body": { 486 | "mode": "urlencoded", 487 | "urlencoded": [ 488 | { 489 | "key": "id", 490 | "value": "", 491 | "description": "Recipient Id or Group Id\n(Required)", 492 | "type": "text" 493 | }, 494 | { 495 | "key": "url", 496 | "value": "", 497 | "description": "Direct URL of Media File\n(Required)", 498 | "type": "text" 499 | }, 500 | { 501 | "key": "type", 502 | "value": "", 503 | "description": "Message Type\n(Required)", 504 | "type": "text" 505 | }, 506 | { 507 | "key": "mimetype", 508 | "value": "", 509 | "description": "Mime Type \n(Sometimes Required)\n(Optional)\n\n", 510 | "type": "text" 511 | }, 512 | { 513 | "key": "caption", 514 | "value": "", 515 | "description": "Message Caption\n(Optional)\n", 516 | "type": "text" 517 | } 518 | ] 519 | }, 520 | "url": { 521 | "raw": "{{baseUrl}}/message/mediaurl?key={{instance_key}}", 522 | "host": [ 523 | "{{baseUrl}}" 524 | ], 525 | "path": [ 526 | "message", 527 | "mediaurl" 528 | ], 529 | "query": [ 530 | { 531 | "key": "key", 532 | "value": "{{instance_key}}", 533 | "description": "Instance Key\n(Required)" 534 | } 535 | ] 536 | }, 537 | "description": "Send a media message via a URL\n\n* Image\n* Video\n* Document" 538 | }, 539 | "response": [] 540 | }, 541 | { 542 | "name": "Send Button(Template) Message", 543 | "protocolProfileBehavior": { 544 | "disabledSystemHeaders": { 545 | "content-type": true 546 | } 547 | }, 548 | "request": { 549 | "method": "POST", 550 | "header": [ 551 | { 552 | "key": "Content-Type", 553 | "value": "application/json", 554 | "type": "text" 555 | } 556 | ], 557 | "body": { 558 | "mode": "raw", 559 | "raw": "{ \n \"id\": \"\",\n \"btndata\": {\n \"text\": \"title Head\",\n \"buttons\": [\n {\n \"type\": \"replyButton\",\n \"title\": \"Reply this text (REPLY)\"\n },\n {\n \"type\": \"urlButton\",\n \"title\": \"Click me (URL)\",\n \"payload\": \"https://google.com\"\n },\n {\n \"type\": \"callButton\",\n \"title\": \"Click to call (CALL)\",\n \"payload\": \"918788889688\"\n }\n ],\n \"footerText\": \"title footer\"\n }\n}", 560 | "options": { 561 | "raw": { 562 | "language": "json" 563 | } 564 | } 565 | }, 566 | "url": { 567 | "raw": "{{baseUrl}}/message/button?key={{instance_key}}", 568 | "host": [ 569 | "{{baseUrl}}" 570 | ], 571 | "path": [ 572 | "message", 573 | "button" 574 | ], 575 | "query": [ 576 | { 577 | "key": "key", 578 | "value": "{{instance_key}}", 579 | "description": "Instance Key\n(Required)" 580 | } 581 | ] 582 | }, 583 | "description": "Send an interactive template message to an WhatsApp User" 584 | }, 585 | "response": [] 586 | }, 587 | { 588 | "name": "Send Contact Message", 589 | "request": { 590 | "method": "POST", 591 | "header": [], 592 | "body": { 593 | "mode": "raw", 594 | "raw": "{ \n \"id\": \"\",\n \"vcard\": {\n \"fullName\": \"john doe\",\n \"displayName\": \"johndoe\",\n \"organization\": \"Men In Black\",\n \"phoneNumber\": \"919999999999\"\n }\n}", 595 | "options": { 596 | "raw": { 597 | "language": "json" 598 | } 599 | } 600 | }, 601 | "url": { 602 | "raw": "{{baseUrl}}/message/contact?key={{instance_key}}", 603 | "host": [ 604 | "{{baseUrl}}" 605 | ], 606 | "path": [ 607 | "message", 608 | "contact" 609 | ], 610 | "query": [ 611 | { 612 | "key": "key", 613 | "value": "{{instance_key}}", 614 | "description": "Instance Key\n(Required)" 615 | } 616 | ] 617 | }, 618 | "description": "Send an contact(vcard) message to an WhatsApp User" 619 | }, 620 | "response": [] 621 | }, 622 | { 623 | "name": "Send List Message", 624 | "request": { 625 | "method": "POST", 626 | "header": [], 627 | "body": { 628 | "mode": "raw", 629 | "raw": "{\n \"id\": \"\",\n \"msgdata\": {\n \"buttonText\": \"Button Text\",\n \"text\": \"Middle Text\",\n \"title\": \"Head Title\",\n \"description\": \"Footer Description\",\n \"sections\": [\n {\n \"title\": \"title\",\n \"rows\": [\n {\n \"title\": \"Title Option 1\",\n \"description\": \"Option Description\",\n \"rowId\": \"string\"\n }\n ]\n }\n ],\n \"listType\": 0\n }\n}", 630 | "options": { 631 | "raw": { 632 | "language": "json" 633 | } 634 | } 635 | }, 636 | "url": { 637 | "raw": "{{baseUrl}}/message/list?key={{instance_key}}", 638 | "host": [ 639 | "{{baseUrl}}" 640 | ], 641 | "path": [ 642 | "message", 643 | "list" 644 | ], 645 | "query": [ 646 | { 647 | "key": "key", 648 | "value": "{{instance_key}}", 649 | "description": "Instance Key\n(Required)" 650 | } 651 | ] 652 | }, 653 | "description": "Send an list button message to WhatsApp User" 654 | }, 655 | "response": [] 656 | }, 657 | { 658 | "name": "Set Status", 659 | "request": { 660 | "method": "PUT", 661 | "header": [], 662 | "body": { 663 | "mode": "formdata", 664 | "formdata": [ 665 | { 666 | "key": "status", 667 | "value": "", 668 | "description": "Status Value\n(Required)", 669 | "type": "text" 670 | } 671 | ] 672 | }, 673 | "url": { 674 | "raw": "{{baseUrl}}/message/setstatus?key={{instance_key}}", 675 | "host": [ 676 | "{{baseUrl}}" 677 | ], 678 | "path": [ 679 | "message", 680 | "setstatus" 681 | ], 682 | "query": [ 683 | { 684 | "key": "key", 685 | "value": "{{instance_key}}", 686 | "description": "Instance Key\n(Required)" 687 | } 688 | ] 689 | }, 690 | "description": "Send an list button message to WhatsApp User" 691 | }, 692 | "response": [] 693 | }, 694 | { 695 | "name": "Send Button With Media", 696 | "request": { 697 | "method": "POST", 698 | "header": [], 699 | "body": { 700 | "mode": "raw", 701 | "raw": "{\n \"id\": \"\",\n \"btndata\": {\n \"text\": \"Title of Message\",\n \"buttons\": [\n {\n \"type\": \"replyButton\",\n \"title\": \"this button reply\"\n },\n {\n \"type\": \"callButton\",\n \"title\": \"this button calls\",\n \"payload\": \"91999999999\"\n }\n ],\n \"footerText\": \"Footer text\",\n \"image\": \"https://picsum.photos/536/354\",\n \"mediaType\": \"image\",\n \"mimeType\": \"image/jpeg\"\n }\n}", 702 | "options": { 703 | "raw": { 704 | "language": "json" 705 | } 706 | } 707 | }, 708 | "url": { 709 | "raw": "{{baseUrl}}/message/MediaButton?key={{instance_key}}", 710 | "host": [ 711 | "{{baseUrl}}" 712 | ], 713 | "path": [ 714 | "message", 715 | "MediaButton" 716 | ], 717 | "query": [ 718 | { 719 | "key": "key", 720 | "value": "{{instance_key}}", 721 | "description": "Recipient Id or Group Id\n(Required)" 722 | }, 723 | { 724 | "key": "", 725 | "value": null, 726 | "disabled": true 727 | } 728 | ] 729 | }, 730 | "description": "Send an interactive template message with media to WhatsApp User" 731 | }, 732 | "response": [] 733 | } 734 | ] 735 | }, 736 | { 737 | "name": "Misc", 738 | "item": [ 739 | { 740 | "name": "Is On Whatsapp?", 741 | "request": { 742 | "method": "GET", 743 | "header": [], 744 | "url": { 745 | "raw": "{{baseUrl}}/misc/onwhatsapp?key={{instance_key}}&id=", 746 | "host": [ 747 | "{{baseUrl}}" 748 | ], 749 | "path": [ 750 | "misc", 751 | "onwhatsapp" 752 | ], 753 | "query": [ 754 | { 755 | "key": "key", 756 | "value": "{{instance_key}}", 757 | "description": "Instance Key\n(Required)" 758 | }, 759 | { 760 | "key": "id", 761 | "value": "", 762 | "description": "User Whatsapp Id\n(Required)" 763 | } 764 | ] 765 | }, 766 | "description": "Check if a number is registered on WhatsApp" 767 | }, 768 | "response": [] 769 | }, 770 | { 771 | "name": "Download Profile Pic", 772 | "request": { 773 | "method": "GET", 774 | "header": [], 775 | "url": { 776 | "raw": "{{baseUrl}}/misc/downProfile?key={{instance_key}}&id=", 777 | "host": [ 778 | "{{baseUrl}}" 779 | ], 780 | "path": [ 781 | "misc", 782 | "downProfile" 783 | ], 784 | "query": [ 785 | { 786 | "key": "key", 787 | "value": "{{instance_key}}", 788 | "description": "Instance Key\n(Required)" 789 | }, 790 | { 791 | "key": "id", 792 | "value": "", 793 | "description": "User Whatsapp Id\n(Required)" 794 | } 795 | ] 796 | }, 797 | "description": "Download Profile pic of an WhatsApp user" 798 | }, 799 | "response": [] 800 | }, 801 | { 802 | "name": "Get User Status", 803 | "request": { 804 | "method": "GET", 805 | "header": [], 806 | "url": { 807 | "raw": "{{baseUrl}}/misc/getStatus?key={{instance_key}}&id=", 808 | "host": [ 809 | "{{baseUrl}}" 810 | ], 811 | "path": [ 812 | "misc", 813 | "getStatus" 814 | ], 815 | "query": [ 816 | { 817 | "key": "key", 818 | "value": "{{instance_key}}", 819 | "description": "Instance Key\n(Required)" 820 | }, 821 | { 822 | "key": "id", 823 | "value": "", 824 | "description": "User Id\n(Required)" 825 | } 826 | ] 827 | }, 828 | "description": "Get user status (about)." 829 | }, 830 | "response": [] 831 | }, 832 | { 833 | "name": "Block/Unblock User", 834 | "request": { 835 | "method": "GET", 836 | "header": [], 837 | "url": { 838 | "raw": "{{baseUrl}}/misc/blockUser?key={{instance_key}}&id", 839 | "host": [ 840 | "{{baseUrl}}" 841 | ], 842 | "path": [ 843 | "misc", 844 | "blockUser" 845 | ], 846 | "query": [ 847 | { 848 | "key": "key", 849 | "value": "{{instance_key}}", 850 | "description": "Instance Key\n(Required)" 851 | }, 852 | { 853 | "key": "id", 854 | "value": null, 855 | "description": "User Id\n(Required)" 856 | } 857 | ] 858 | }, 859 | "description": "Block Or Unblock User." 860 | }, 861 | "response": [] 862 | }, 863 | { 864 | "name": "Update Profile Picture", 865 | "request": { 866 | "method": "POST", 867 | "header": [], 868 | "body": { 869 | "mode": "formdata", 870 | "formdata": [ 871 | { 872 | "key": "id", 873 | "value": "", 874 | "description": "Your Id or Group Id\n(Required)", 875 | "type": "text" 876 | }, 877 | { 878 | "key": "url", 879 | "value": "", 880 | "description": "Direct Image URl\n(Required)", 881 | "type": "text" 882 | } 883 | ] 884 | }, 885 | "url": { 886 | "raw": "{{baseUrl}}/misc/updateProfilePicture?key={{instance_key}}", 887 | "host": [ 888 | "{{baseUrl}}" 889 | ], 890 | "path": [ 891 | "misc", 892 | "updateProfilePicture" 893 | ], 894 | "query": [ 895 | { 896 | "key": "key", 897 | "value": "{{instance_key}}", 898 | "description": "Instance Key\n(Required)" 899 | } 900 | ] 901 | }, 902 | "description": "Block Or Unblock User." 903 | }, 904 | "response": [] 905 | } 906 | ] 907 | }, 908 | { 909 | "name": "Group", 910 | "item": [ 911 | { 912 | "name": "Create Group", 913 | "request": { 914 | "method": "POST", 915 | "header": [], 916 | "url": { 917 | "raw": "{{baseUrl}}/group/create?key={{instance_key}}", 918 | "host": [ 919 | "{{baseUrl}}" 920 | ], 921 | "path": [ 922 | "group", 923 | "create" 924 | ], 925 | "query": [ 926 | { 927 | "key": "key", 928 | "value": "{{instance_key}}" 929 | } 930 | ] 931 | }, 932 | "description": "Create a group" 933 | }, 934 | "response": [] 935 | }, 936 | { 937 | "name": "Leave Group", 938 | "request": { 939 | "method": "GET", 940 | "header": [], 941 | "url": { 942 | "raw": "{{baseUrl}}/group/leave?key={{instance_key}}&id", 943 | "host": [ 944 | "{{baseUrl}}" 945 | ], 946 | "path": [ 947 | "group", 948 | "leave" 949 | ], 950 | "query": [ 951 | { 952 | "key": "key", 953 | "value": "{{instance_key}}", 954 | "description": "Instance Key\n(Required)" 955 | }, 956 | { 957 | "key": "id", 958 | "value": null, 959 | "description": "Group Id\n(Required)" 960 | } 961 | ] 962 | }, 963 | "description": "Leave a group by its ID" 964 | }, 965 | "response": [] 966 | }, 967 | { 968 | "name": "Get All Groups", 969 | "request": { 970 | "method": "GET", 971 | "header": [], 972 | "url": { 973 | "raw": "{{baseUrl}}/group/listall?key={{instance_key}}", 974 | "host": [ 975 | "{{baseUrl}}" 976 | ], 977 | "path": [ 978 | "group", 979 | "listall" 980 | ], 981 | "query": [ 982 | { 983 | "key": "key", 984 | "value": "{{instance_key}}", 985 | "description": "Instance Key\n(Required)" 986 | } 987 | ] 988 | }, 989 | "description": "List all groups in which you are in" 990 | }, 991 | "response": [] 992 | }, 993 | { 994 | "name": "Invite User", 995 | "request": { 996 | "method": "POST", 997 | "header": [], 998 | "body": { 999 | "mode": "urlencoded", 1000 | "urlencoded": [ 1001 | { 1002 | "key": "id", 1003 | "value": "", 1004 | "description": "Group Id\n(Required)", 1005 | "type": "text" 1006 | }, 1007 | { 1008 | "key": "users", 1009 | "value": "", 1010 | "description": "Users Id\n(Required)", 1011 | "type": "text" 1012 | } 1013 | ] 1014 | }, 1015 | "url": { 1016 | "raw": "{{baseUrl}}/group/inviteuser?key={{instance_key}}", 1017 | "host": [ 1018 | "{{baseUrl}}" 1019 | ], 1020 | "path": [ 1021 | "group", 1022 | "inviteuser" 1023 | ], 1024 | "query": [ 1025 | { 1026 | "key": "key", 1027 | "value": "{{instance_key}}", 1028 | "description": "Instance Key\n(Required)" 1029 | } 1030 | ] 1031 | }, 1032 | "description": "Invite Users to Group" 1033 | }, 1034 | "response": [] 1035 | }, 1036 | { 1037 | "name": "Make Admin", 1038 | "request": { 1039 | "method": "POST", 1040 | "header": [], 1041 | "body": { 1042 | "mode": "urlencoded", 1043 | "urlencoded": [ 1044 | { 1045 | "key": "id", 1046 | "value": "", 1047 | "description": "Group Id\n(Required)", 1048 | "type": "text" 1049 | }, 1050 | { 1051 | "key": "users", 1052 | "value": "", 1053 | "description": "User Id\n(Required)", 1054 | "type": "text" 1055 | } 1056 | ] 1057 | }, 1058 | "url": { 1059 | "raw": "{{baseUrl}}/group/makeadmin?key={{instance_key}}", 1060 | "host": [ 1061 | "{{baseUrl}}" 1062 | ], 1063 | "path": [ 1064 | "group", 1065 | "makeadmin" 1066 | ], 1067 | "query": [ 1068 | { 1069 | "key": "key", 1070 | "value": "{{instance_key}}", 1071 | "description": "Instance Key\n(Required)" 1072 | } 1073 | ] 1074 | }, 1075 | "description": "Promote group users to admin" 1076 | }, 1077 | "response": [] 1078 | }, 1079 | { 1080 | "name": "Demote Admin", 1081 | "request": { 1082 | "method": "POST", 1083 | "header": [], 1084 | "body": { 1085 | "mode": "urlencoded", 1086 | "urlencoded": [ 1087 | { 1088 | "key": "id", 1089 | "value": "", 1090 | "description": "Group Id\n(Required)", 1091 | "type": "text" 1092 | }, 1093 | { 1094 | "key": "users", 1095 | "value": "", 1096 | "description": "User Id\n(Required)", 1097 | "type": "text" 1098 | } 1099 | ] 1100 | }, 1101 | "url": { 1102 | "raw": "{{baseUrl}}/group/demoteadmin?key={{instance_key}}", 1103 | "host": [ 1104 | "{{baseUrl}}" 1105 | ], 1106 | "path": [ 1107 | "group", 1108 | "demoteadmin" 1109 | ], 1110 | "query": [ 1111 | { 1112 | "key": "key", 1113 | "value": "{{instance_key}}", 1114 | "description": "Instance Key\n(Required)" 1115 | } 1116 | ] 1117 | }, 1118 | "description": "Demote group admin" 1119 | }, 1120 | "response": [] 1121 | }, 1122 | { 1123 | "name": "Get Group Invite Code", 1124 | "protocolProfileBehavior": { 1125 | "disableBodyPruning": true 1126 | }, 1127 | "request": { 1128 | "method": "GET", 1129 | "header": [], 1130 | "body": { 1131 | "mode": "urlencoded", 1132 | "urlencoded": [] 1133 | }, 1134 | "url": { 1135 | "raw": "{{baseUrl}}/group/getinvitecode?key={{instance_key}}&id", 1136 | "host": [ 1137 | "{{baseUrl}}" 1138 | ], 1139 | "path": [ 1140 | "group", 1141 | "getinvitecode" 1142 | ], 1143 | "query": [ 1144 | { 1145 | "key": "key", 1146 | "value": "{{instance_key}}", 1147 | "description": "Instance Key\n(Required)" 1148 | }, 1149 | { 1150 | "key": "id", 1151 | "value": null, 1152 | "description": "Group Id\n(Required)" 1153 | } 1154 | ] 1155 | }, 1156 | "description": "Get invite link of a group" 1157 | }, 1158 | "response": [] 1159 | }, 1160 | { 1161 | "name": "Get All Groups", 1162 | "protocolProfileBehavior": { 1163 | "disableBodyPruning": true 1164 | }, 1165 | "request": { 1166 | "method": "GET", 1167 | "header": [], 1168 | "body": { 1169 | "mode": "urlencoded", 1170 | "urlencoded": [] 1171 | }, 1172 | "url": { 1173 | "raw": "{{baseUrl}}/group/getallgroups?key={{instance_key}}", 1174 | "host": [ 1175 | "{{baseUrl}}" 1176 | ], 1177 | "path": [ 1178 | "group", 1179 | "getallgroups" 1180 | ], 1181 | "query": [ 1182 | { 1183 | "key": "key", 1184 | "value": "{{instance_key}}", 1185 | "description": "Instance Key\n(Required)" 1186 | }, 1187 | { 1188 | "key": "", 1189 | "value": null, 1190 | "disabled": true 1191 | } 1192 | ] 1193 | }, 1194 | "description": "Get invite link of a group" 1195 | }, 1196 | "response": [] 1197 | }, 1198 | { 1199 | "name": "Update Group Participants", 1200 | "request": { 1201 | "method": "POST", 1202 | "header": [], 1203 | "body": { 1204 | "mode": "formdata", 1205 | "formdata": [ 1206 | { 1207 | "key": "id", 1208 | "value": "", 1209 | "description": "Group Id\n(Required)", 1210 | "type": "text" 1211 | }, 1212 | { 1213 | "key": "users", 1214 | "value": "", 1215 | "description": "Users\n(Required)", 1216 | "type": "text" 1217 | }, 1218 | { 1219 | "key": "action", 1220 | "value": "", 1221 | "description": "Action\n(Required)", 1222 | "type": "text" 1223 | } 1224 | ] 1225 | }, 1226 | "url": { 1227 | "raw": "{{baseUrl}}/group/participantsupdate?key={{instance_key}}", 1228 | "host": [ 1229 | "{{baseUrl}}" 1230 | ], 1231 | "path": [ 1232 | "group", 1233 | "participantsupdate" 1234 | ], 1235 | "query": [ 1236 | { 1237 | "key": "key", 1238 | "value": "{{instance_key}}", 1239 | "description": "Instance Key\n(Required)" 1240 | }, 1241 | { 1242 | "key": "", 1243 | "value": null, 1244 | "disabled": true 1245 | } 1246 | ] 1247 | }, 1248 | "description": "Get invite link of a group" 1249 | }, 1250 | "response": [] 1251 | }, 1252 | { 1253 | "name": "Update Group Setting", 1254 | "request": { 1255 | "method": "POST", 1256 | "header": [], 1257 | "body": { 1258 | "mode": "formdata", 1259 | "formdata": [ 1260 | { 1261 | "key": "id", 1262 | "value": "", 1263 | "description": "Group Id\n(Required)", 1264 | "type": "text" 1265 | }, 1266 | { 1267 | "key": "action", 1268 | "value": "", 1269 | "description": "Action\n(Required)", 1270 | "type": "text" 1271 | } 1272 | ] 1273 | }, 1274 | "url": { 1275 | "raw": "{{baseUrl}}/group/settingsupdate?key={{instance_key}}", 1276 | "host": [ 1277 | "{{baseUrl}}" 1278 | ], 1279 | "path": [ 1280 | "group", 1281 | "settingsupdate" 1282 | ], 1283 | "query": [ 1284 | { 1285 | "key": "key", 1286 | "value": "{{instance_key}}", 1287 | "description": "Instance Key\n(Required)" 1288 | }, 1289 | { 1290 | "key": "", 1291 | "value": null, 1292 | "disabled": true 1293 | } 1294 | ] 1295 | }, 1296 | "description": "Get invite link of a group" 1297 | }, 1298 | "response": [] 1299 | }, 1300 | { 1301 | "name": "Update Group Subject", 1302 | "request": { 1303 | "method": "POST", 1304 | "header": [], 1305 | "body": { 1306 | "mode": "formdata", 1307 | "formdata": [ 1308 | { 1309 | "key": "id", 1310 | "value": "", 1311 | "description": "Group Id\n(Required)", 1312 | "type": "text" 1313 | }, 1314 | { 1315 | "key": "subject", 1316 | "value": "", 1317 | "description": "Subject\n(Required)", 1318 | "type": "text" 1319 | } 1320 | ] 1321 | }, 1322 | "url": { 1323 | "raw": "{{baseUrl}}/group/updatesubject?key={{instance_key}}", 1324 | "host": [ 1325 | "{{baseUrl}}" 1326 | ], 1327 | "path": [ 1328 | "group", 1329 | "updatesubject" 1330 | ], 1331 | "query": [ 1332 | { 1333 | "key": "key", 1334 | "value": "{{instance_key}}", 1335 | "description": "Instance Key\n(Required)" 1336 | }, 1337 | { 1338 | "key": "", 1339 | "value": null, 1340 | "disabled": true 1341 | } 1342 | ] 1343 | }, 1344 | "description": "Get invite link of a group" 1345 | }, 1346 | "response": [] 1347 | }, 1348 | { 1349 | "name": "Update Group Description", 1350 | "request": { 1351 | "method": "POST", 1352 | "header": [], 1353 | "body": { 1354 | "mode": "formdata", 1355 | "formdata": [ 1356 | { 1357 | "key": "id", 1358 | "value": "", 1359 | "description": "Group Id\n(Required)", 1360 | "type": "text" 1361 | }, 1362 | { 1363 | "key": "description", 1364 | "value": "", 1365 | "description": "Group Description\n(Required)", 1366 | "type": "text" 1367 | } 1368 | ] 1369 | }, 1370 | "url": { 1371 | "raw": "{{baseUrl}}/group/updatedescription?key={{instance_key}}", 1372 | "host": [ 1373 | "{{baseUrl}}" 1374 | ], 1375 | "path": [ 1376 | "group", 1377 | "updatedescription" 1378 | ], 1379 | "query": [ 1380 | { 1381 | "key": "key", 1382 | "value": "{{instance_key}}", 1383 | "description": "Instance Key\n(Required)" 1384 | }, 1385 | { 1386 | "key": "", 1387 | "value": null, 1388 | "disabled": true 1389 | } 1390 | ] 1391 | }, 1392 | "description": "Get invite link of a group" 1393 | }, 1394 | "response": [] 1395 | } 1396 | ] 1397 | } 1398 | ], 1399 | "event": [ 1400 | { 1401 | "listen": "prerequest", 1402 | "script": { 1403 | "type": "text/javascript", 1404 | "exec": [ 1405 | "" 1406 | ] 1407 | } 1408 | }, 1409 | { 1410 | "listen": "test", 1411 | "script": { 1412 | "type": "text/javascript", 1413 | "exec": [ 1414 | "" 1415 | ] 1416 | } 1417 | } 1418 | ], 1419 | "variable": [ 1420 | { 1421 | "key": "baseUrl", 1422 | "value": "localhost:3333" 1423 | }, 1424 | { 1425 | "key": "instance_key", 1426 | "value": "123" 1427 | } 1428 | ] 1429 | } 1430 | --------------------------------------------------------------------------------