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.
Do you have any doubt? Need help? Join our whatsapp group and ask your questions with other people!
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
The service will be started on localhost on port 8080
const hydraBot = require('hydra-bot');(async () => { // start Web Service const WS = await hydraBot.initWs();})();
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 chatif (conn.connect) { client = conn.client; // class client from hydra-bot const getMe = await client.getHost(); const hostNumber = getMe.id._serialized; // number host console.log('Host Number: ', hostNumber); // send a text message await client.sendMessage({ to: hostNumber, // 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 receivedif (!newMsg.result.fromMe) { // message received! console.log('NewMessageReceived: ', newMsg.result); // dowload files if (newMsg.result.isMedia) {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 fileconst fileName = `some-file-name.${mime.extension( newMsg.result.mimetype )}`;fs.writeFile(fileName, buffer, (err) => { if (err) {console.log(err); }}); }}// when is it sentif (!!newMsg.result.fromMe) { // 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 idconsole.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 = PLAYEDconsole.log('From Message: ', event.result.from); // from messageconsole.log('To Message: ', event.result.to); // to message });})();
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 chatif (conn.connect) { client = conn.client;} }); ev.on('newMessage', async (newMsg) => {// when is receivedif (!newMsg.result.fromMe) { // message received! console.log('NewMessageReceived: ', newMsg.result); // dowload files if (newMsg.result.isMedia) {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 fileconst fileName = `some-file-name.${mime.extension( newMsg.result.mimetype )}`;fs.writeFile(fileName, buffer, (err) => { if (err) {console.log(err); }}); }} });})();
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 projectexecutablePath: '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. },});
const hydraBot = require('hydra-bot');hydraBot.initWs({ hostServer: 'http://localhost', 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 projectexecutablePath: '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. },});
To start the administration interface use:
> yarn admin
List of commands in the terminal:
Command | Description |
---|---|
/create | Create user |
/delete | Delete user |
/selectid | Show user by id |
/selectname | Select user by name |
/getall | List all users |
/deactivate | Disable user |
/activate | Activate User |
/changename | Change username |
/password | Change user password |
/cls | Clear screen/terminal |
/help | List all commands for administration in terminal |
/exit | Exit manager |
REST API
Headers
, to be able to access them, to create a administrator{ "Content-Type": "application/json", "admin": "admin", "admin_pass": "admin"}
Type | Route to browser | Description | Body |
---|---|---|---|
POST | /create_user | Create user | {"name":"USE","password":"USER PASSWORD"} |
DEL | /delete_user/ID_USE | Delete user | EMPTY |
GET | /get_user_by_id/ID_USE | Show user by ID | EMPTY |
GET | /get_all_users | List all users | EMPTY |
PUT | /deactivate_user | Disable user | {"id":"USER ID"} |
PUT | /activate_user | Activate User | {"id":"USER ID"} |
PUT | /change_name | Change username | {"id":"USER ID","name":"NEW USERNAME"} |
PUT | /change_password | Change user password | {"id":"USER ID","password":"NEW SECURE PASSWORD"} |
Note: Parameters can be changed during development!
Headers
of user (default, username = 'user', password = 'user').The headers must be parameterized as :
{ "Content-Type": "application/json", "user": "user", "user_pass": "user"}
if you want to receive a callback on a specific url, pass the url parameter in the connect route.
Type | Route to browser | Description | Body |
---|---|---|---|
POST | /connect | Start connection with Whatsapp | { "url": "http://localhost:8080/webhooktest" } |
POST | /sendtext | Send a text to a number | { "to": "contact number", "body": "message"} |
POST | /sendFile | Send file to a number | { "to": "contact number", "file_path": "https://docs.marklogic.com/guide/node-dev.pdf", "file_name": "node.js" } |
POST | /sendAudio | Send audio | { "to": "contact number", "url_mp3": "https://cdn.freesound.org/previews/620/620094_4935038-lq.mp3", "file_name": "node.js" } |
POST | /sendImage | Send image message | { "to": "contact number", "url_img": "https://i.pinimg.com/564x/a9/b1/18/a9b118761788b1ab260aae2835c468cd.jpg" } |
POST | /disconnect | Disconnecting from the server | EMPTY |
POST | /check_user | Check if the entered user exists | EMPTY |
Type | Route to browser | Description | Body |
---|---|---|---|
GET | /get_all_contacts | Retrieve contacts | EMPTY |
GET | /check_connect | check if the client is connected | EMPTY |
GET | /last_qrcode | Check if the QR-Code is active | EMPTY |
GET | /screenshot | Get screenshot | EMPTY |
You must be logged in to use these functions!
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 messageawait client .sendMessage({to: '[email protected]', // you can pass the contact number or group numberbody: 'A message sent by hydra-bot', // message textoptions: { type: 'sendText', // shipping type}, }) .then((result) => {console.log(result); // message result }) .catch((error) => {console.log(error); // message error });// send filesawait client .sendMessage({to: '[email protected]', // you can pass the contact number or group numberbody: './file.pdf', // you can use a directory or use a urloptions: { 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 audioawait client .sendMessage({to: '[email protected]', // you can pass the contact number or group numberbody: './file.mp3', // you can use a directory or use a urloptions: { type: 'sendAudio', // shipping type}, }) .then((result) => {console.log(result); // message result }) .catch((error) => {console.log(error); // message error });// Send audio file base64await client .sendMessage({to: '[email protected]', // you can pass the contact number or group numberbody: base64MP3, // you can use a directory or use a urloptions: { type: 'sendAudioBase64', // shipping type}, }) .then((result) => {console.log(result); // message result }) .catch((error) => {console.log(error); // message error });// Send image messageawait client .sendMessage({to: '[email protected]', // you can pass the contact number or group numberbody: './file.jpg', // you can use a directory or use a urloptions: { 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 Base64await client .sendMessage({to: '[email protected]', // you can pass the contact number or group numberbody: base64IMG, // you can use a directory or use a urloptions: { type: 'sendImageFromBase64', // shipping type caption: 'image text', // image text}, }) .then((result) => {console.log(result); // message result }) .catch((error) => {console.log(error); // message error });
// Sends a text message to given chatawait client .sendText('[email protected]', 'A message sent by hydra-bot') .then((result) => {console.log(result); // message result }) .catch((error) => {console.log(error); // message error });// Sends file from pathawait client .sendFile('[email protected]', './file.pdf', { filename: 'filename' }) .then((result) => {console.log(result); // message result }) .catch((error) => {console.log(error); // message error });// Send audio fileawait client .sendAudio('[email protected]', './file.mp3') .then((result) => {console.log(result); // message result }) .catch((error) => {console.log(error); // message error });// Send audio base64await client .sendAudioBase64('[email protected]', base64MP3) .then((result) => {console.log(result); // message result }) .catch((error) => {console.log(error); // message error });// Send image messageawait client .sendImage('[email protected]', './file.jpg', { caption: 'image text' }) .then((result) => {console.log(result); // message result }) .catch((error) => {console.log(error); // message error });// Send image base64await client .sendImageFromBase64('[email protected]', base64IMG, { caption: 'image text' }) .then((result) => {console.log(result); // message result }) .catch((error) => {console.log(error); // message error });
// Get device infoawait client.getHost();
// returns a list of contactsconst contacts = aw