Socket
Socket
Sign inDemoInstall

hydra-bot

Package Overview
Dependencies
449
Maintainers
1
Versions
30
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    hydra-bot

The most reliable WhatsApp tool for chatbots with advanced features. Hydra bot is an open source project developed by the JavaScript community with the aim of exporting functions from WhatsApp Web to the node js, . The most complete javascript library for


Version published
Weekly downloads
32
increased by1500%
Maintainers
1
Created
Weekly downloads
 

Changelog

Source

1.0.30 (2022-08-20)

Features

  • checkNumber (e75c31e)

<<<<<<< HEAD

Readme

Source

Status repository

npm version Downloads Average time to resolve an issue Percentage of issues still open

Our online channels

WhatsApp Group Discord YouTube Telegram Group

Welcome to Hydra Bot

This project was developed to help the community that uses whatsapp as a way to implement an API quickly and effectively, for companies and much more! Thank you for being part of this family.

You can use this project in two ways, the first is using Web Services using a set of well-defined operations, the POST, GET, PUT and DELETE methods, the second option is to use the bot in raw form, without using a Web Services.

Supporters

To maintain quality, we are receiving support! We thank you in advance for the opportunity to develop and maintain this project!

CompanyURLLogo
redrivehttps://redrive.com.br/
zaplushttps://zaplus.chat/
tabchathttps://tabchat.com.br/

WhatSapp Group

Do you have any doubt? Need help? Join our whatsapp group and ask your questions with other people!

Installation

Use the stable version:

> npm i --save hydra-bot

or for Nightly releases:

> npm i --save https://github.com/jonalan7/Hydra-bot/releases/download/nightly/hydra-nightly.tgz

Terminal Admin:

> yarn admin

Install yarn Ubuntu:

> curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add -
> echo "deb https://dl.yarnpkg.com/debian/ stable main" | sudo tee /etc/apt/sources.list.d/yarn.list
> sudo apt update && sudo apt install yarn
> yarn

Getting started Web Service

The service will be started on localhost on port 8080

const hydraBot = require('hydra-bot');
(async () => {
  // start Web Service
  const WS = await hydraBot.initWs();
})();

Getting started bot (the bot in raw form, without using a Web Services).

If you want to work in free mode, using only the bot, dry the necessary information!

const hydraBot = require('hydra-bot');
const mime = require('mime-types');
const fs = require('fs');

(async () => {
  let client;
  // start bot service
  const ev = await hydraBot.initServer();

  // return to current whatsapp interface
  ev.on('interfaceChange', (change) => {
    console.log('interfaceChange: ', change);
  });

  // return qrcode parameters
  ev.on('qrcode', (qrcode) => {
    console.log('qrcode: ', qrcode);
  });

  // return connection information
  ev.on('connection', async (conn) => {
    // browser information!
    if (conn.statusFind === 'browser') {
      console.log('info Browser: ', conn.text);
    }

    // Was connected to whatsapp chat
    if (conn.connect) {
      client = conn.client;
      // send a text message
      await client
        .sendMessage({
          to: '0000000000@c.us', // you can pass the contact number or group number
          body: "hi i'm hydra bot", // message text
          options: {
            type: 'sendText', // shipping type
          },
        })
        .then((result) => {
          console.log(result); // message result
        })
        .catch((error) => {
          console.log(error); // message error
        });
    }
  });

  // return receive new messages
  ev.on('newMessage', async (newMsg) => {
    // when is received
    if (!newMsg.result.isSentByMe) {
      // message received!
      console.log('NewMessageReceived: ', newMsg.result);
      // dowload files
      if (newMsg.result.isMedia === true || newMsg.result.isMMS === true) {
        const buffer = await client.decryptFile(newMsg.result);
        // At this point you can do whatever you want with the buffer
        // Most likely you want to write it into a file
        const fileName = `some-file-name.${mime.extension(
          newMsg.result.mimetype
        )}`;
        fs.writeFile(fileName, buffer, (err) => {
          if (err) {
            console.log(err);
          }
        });
      }
    }
    // when is it sent
    if (!!newMsg.result.isSentByMe) {
      // Message sent
      console.log('NewMessageSent: ', newMsg.result);
    }
  });

  // returns the status of each message
  ev.on('newOnAck', async (event) => {
    console.log('id Message: ', event.result.id._serialized); // message id
    console.log('Status Message: ', event.result.ack); // -7 = MD_DOWNGRADE, -6 = INACTIVE, -5 = CONTENT_UNUPLOADABLE, -4 = CONTENT_TOO_BIG, -3 = CONTENT_GONE, -2 = EXPIRED, -1 = FAILED, 0 = CLOCK, 1 = SENT, 2 = RECEIVED, 3 = READ, 4 = PLAYED
    console.log('From Message: ', event.result.from); // from message
    console.log('To Message: ', event.result.to); // to message
  });
})();

Downloading Files

Puppeteer takes care of the file downloading. The decryption is being done as fast as possible (outruns native methods). Supports big files!

const hydraBot = require('hydra-bot');
const fs = require('fs');
const mime = require('mime-types');

(async () => {
  let client;
  // start bot service
  const ev = await hydraBot.initServer();
  // return connection information
  ev.on('connection', async (conn) => {
    // Was connected to whatsapp chat
    if (conn.connect) {
      client = conn.client;
    }
  });
  ev.on('newMessage', async (newMsg) => {
    // when is received
    if (!newMsg.result.isSentByMe) {
      // message received!
      console.log('NewMessageReceived: ', newMsg.result);
      // dowload files
      if (newMsg.result.isMedia === true || newMsg.result.isMMS === true) {
        const buffer = await client.decryptFile(newMsg.result);
        // At this point you can do whatever you want with the buffer
        // Most likely you want to write it into a file
        const fileName = `some-file-name.${mime.extension(
          newMsg.result.mimetype
        )}`;
        fs.writeFile(fileName, buffer, (err) => {
          if (err) {
            console.log(err);
          }
        });
      }
    }
  });
})();

Optional create parameters (the bot in raw form, without using a Web Services)

const hydraBot = require('hydra-bot');

hydraBot.initServer({
  session: 'session', // Name of the token to be generated, a folder with all customer information will be created
  pathNameToken: 'token', // The path and name of the folder where the client tokens will be saved
  printQRInTerminal: true, // The QR CODE will be printed on the terminal if true
  updatesLog: true, // Logs info updates automatically in terminal
  timeAutoClose: 60000, // If you don't read the QR CODE by default 60 seconds, it will automatically close the client's browser to save memory, if you want to disable it, set 0 or false
  mkdirFolderToken: '', // Token folder path, only inside the project
  puppeteerOptions: {
    headless: true, // Start the project with the browser open or not!
    args: [], // Additional arguments to pass to the browser instance. adding any parameter you will replace the default args of the project
    executablePath: 'useChrome', // The browser that will be used for the project, you can specify a path, if you don't pass any parameters it will open the installed browser.
  },
});

Optional create parameters Web Services

const hydraBot = require('hydra-bot');

hydraBot.initWs({
  port: '8080',
  url: '', // point a URL to receive a callback!
  authentication: true, // ask for authentication in routes
  pathNameToken: 'token', // The path and name of the folder where the client tokens will be saved
  printQRInTerminal: true, // The QR CODE will be printed on the terminal if true
  updatesLog: true, // Logs info updates automatically in terminal
  timeAutoClose: 60000, // If you don't read the QR CODE by default 60 seconds, it will automatically close the client's browser to save memory, if you want to disable it, set 0 or false
  mkdirFolderToken: '', // Token folder path, only inside the project
  puppeteerOptions: {
    headless: true, // Start the project with the browser open or not!
    args: [], // Additional arguments to pass to the browser instance. adding any parameter you will replace the default args of the project
    executablePath: 'useChrome', // The browser that will be used for the project, you can specify a path, if you don't pass any parameters it will open the installed browser.
  },
});

Commands for administration via terminal

To start the administration interface use:

> yarn admin

List of commands in the terminal:

CommandDescription
/createCreate user
/deleteDelete user
/selectidShow user by id
/selectnameSelect user by name
/getallList all users
/deactivateDisable user
/activateActivate User
/changenameChange username
/passwordChange user password
/clsClear screen/terminal
/helpList all commands for administration in terminal
/exitExit manager

Routes for handling and querying users.

List of commands using REST API

All user wheels have a pattern of Headers, to be able to access them, to create a administrator
{
  "Content-Type": "application/json",
  "admin": "admin",
  "admin_pass": "admin"
}

List of routes for user management:

TypeRoute to browserDescriptionBody
POST/create_userCreate user{"name":"USE","password":"USER PASSWORD"}
DEL/delete_user/ID_USEDelete userEMPTY
GET/get_user_by_id/ID_USEShow user by IDEMPTY
GET/get_all_usersList all usersEMPTY
PUT/deactivate_userDisable user{"id":"USER ID"}
PUT/activate_userActivate User{"id":"USER ID"}
PUT/change_nameChange username{"id":"USER ID","name":"NEW USERNAME"}
PUT/change_passwordChange user password{"id":"USER ID","password":"NEW SECURE PASSWORD"}

Web Service Routes (more features still under development)

Note: Parameters can be changed during development!

List of routes for managing whatsapp:

All whatsapp connection wheels have a pattern of Headers of user (default, username = 'user', password = 'user').

The headers must be parameterized as :

{
  "Content-Type": "application/json",
  "user": "user",
  "user_pass": "user"
}

Using Webhook

if you want to receive a callback on a specific url, pass the url parameter in the connect route.

Methods POST

TypeRoute to browserDescriptionBody
POST/connectStart connection with Whatsapp{ "url": "http://localhost:8080/webhooktest" }
POST/sendtextSend a text to a number{ "to": "contact number", "body": "message"}
POST/sendFileSend file to a number{ "to": "contact number", "file_path": "https://docs.marklogic.com/guide/node-dev.pdf", "file_name": "node.js" }
POST/sendAudioSend audio{ "to": "contact number", "url_mp3": "https://cdn.freesound.org/previews/620/620094_4935038-lq.mp3", "file_name": "node.js" }
POST/sendImageSend image message{ "to": "contact number", "url_img": "https://i.pinimg.com/564x/a9/b1/18/a9b118761788b1ab260aae2835c468cd.jpg" }
POST/disconnectDisconnecting from the serverEMPTY
POST/check_userCheck if the entered user existsEMPTY

Methods GET

TypeRoute to browserDescriptionBody
GET/get_all_contactsRetrieve contactsEMPTY
GET/check_connectcheck if the client is connectedEMPTY
GET/last_qrcodeCheck if the QR-Code is activeEMPTY
GET/screenshotGet screenshotEMPTY

Basic send options functions (more features still under development)

You must be logged in to use these functions!

Here, to can be <phone Number>@c.us or <phone Number>-<groupId>@g.us or <phone Number><groupId>@g.us

you can send messages only using one function!

// send text message
await client
  .sendMessage({
    to: '0000000000@c.us', // you can pass the contact number or group number
    body: 'A message sent by hydra-bot', // message text
    options: {
      type: 'sendText', // shipping type
    },
  })
  .then((result) => {
    console.log(result); // message result
  })
  .catch((error) => {
    console.log(error); // message error
  });

// send files
await client
  .sendMessage({
    to: '0000000000@c.us', // you can pass the contact number or group number
    body: './file.pdf', // you can use a directory or use a url
    options: {
      type: 'sendFile', // shipping type
      filename: 'filename', // put the file name here
    },
  })
  .then((result) => {
    console.log(result); // message result
  })
  .catch((error) => {
    console.log(error); // message error
  });

// send file audio
await client
  .sendMessage({
    to: '0000000000@c.us', // you can pass the contact number or group number
    body: './file.mp3', // you can use a directory or use a url
    options: {
      type: 'sendAudio', // shipping type
    },
  })
  .then((result) => {
    console.log(result); // message result
  })
  .catch((error) => {
    console.log(error); // message error
  });

// Send audio file base64
await client
  .sendMessage({
    to: '0000000000@c.us', // you can pass the contact number or group number
    body: base64MP3, // you can use a directory or use a url
    options: {
      type: 'sendAudioBase64', // shipping type
    },
  })
  .then((result) => {
    console.log(result); // message result
  })
  .catch((error) => {
    console.log(error); // message error
  });

// Send image message
await client
  .sendMessage({
    to: '0000000000@c.us', // you can pass the contact number or group number
    body: './file.jpg', // you can use a directory or use a url
    options: {
      type: 'sendImage', // shipping type
      caption: 'image text', // image text
    },
  })
  .then((result) => {
    console.log(result); // message result
  })
  .catch((error) => {
    console.log(error); // message error
  });

// Send image Base64
await client
  .sendMessage({
    to: '0000000000@c.us', // you can pass the contact number or group number
    body: base64IMG, // you can use a directory or use a url
    options: {
      type: 'sendImageFromBase64', // shipping type
      caption: 'image text', // image text
    },
  })
  .then((result) => {
    console.log(result); // message result
  })
  .catch((error) => {
    console.log(error); // message error
  });

Basic send functions

// Sends a text message to given chat
await client
  .sendText('0000000000@c.us', 'A message sent by hydra-bot')
  .then((result) => {
    console.log(result); // message result
  })
  .catch((error) => {
    console.log(error); // message error
  });

// Sends file from path
await client
  .sendFile('0000000000@c.us', './file.pdf', { filename: 'filename' })
  .then((result) => {
    console.log(result); // message result
  })
  .catch((error) => {
    console.log(error); // message error
  });

// Send audio file
await client
  .sendAudio('0000000000@c.us', './file.mp3')
  .then((result) => {
    console.log(result); // message result
  })
  .catch((error) => {
    console.log(error); // message error
  });

// Send audio base64
await client
  .sendAudioBase64('0000000000@c.us', base64MP3)
  .then((result) => {
    console.log(result); // message result
  })
  .catch((error) => {
    console.log(error); // message error
  });

// Send image message
await client
  .sendImage('0000000000@c.us', './file.jpg', { caption: 'image text' })
  .then((result) => {
    console.log(result); // message result
  })
  .catch((error) => {
    console.log(error); // message error
  });

// Send image base64
await client
  .sendImageFromBase64('0000000000@c.us', base64IMG, { caption: 'image text' })
  .then((result) => {
    console.log(result); // message result
  })
  .catch((error) => {
    console.log(error); // message error
  });

Profile Functions

// Get device info
await client.getHost();

Retrieving Data

// returns a list of contacts
const contacts = await client.getAllContacts();

Group Management

Group number example <phone Number>-<groupId>@g.us or <phone Number><groupId>@g.us

// Create group
await client
  .createGroup('Group name', ['111111111111@c.us', '222222222222@c.us'])
  .then((result) => {
    console.log(result); // message result
  })
  .catch((error) => {
    console.log(error); // message error
  });

// Add participant to Group
await client
  .addParticipant('00000000-000000@g.us', [
    '111111111111@c.us',
    '222222222222@c.us',
  ])
  .then((result) => {
    console.log(result); // message result
  })
  .catch((error) => {
    console.log(error); // message error
  });

// Change group description
await client
  .setGroupDescription('00000000-000000@g.us', 'group description')
  .then((result) => {
    console.log(result); // message result
  })
  .catch((error) => {
    console.log(error); // message error
  });

// Change group image
await client
  .setGroupImage('00000000000000@g.us', './file.jpg')
  .then((result) => {
    console.log(result); // message result
  })
  .catch((error) => {
    console.log(error); // message error
  });

Debugging

Building the hydra-bot is very simple

Development

To build the entire project just run

> npm run build

Test

run a test inside the project

> npm start

Maintainers

Maintainers are needed, I cannot keep with all the updates by myself. If you are interested please open a Pull Request.

Contributing

Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.

Keywords

FAQs

Last updated on 20 Aug 2022

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc