Coder Social home page Coder Social logo

orkestral / venom Goto Github PK

View Code? Open in Web Editor NEW
5.7K 150.0 1.1K 15.47 MB

Venom is a high-performance system developed with JavaScript to create a bot for WhatsApp, support for creating any interaction, such as customer service, media sending, sentence recognition based on artificial intelligence and all types of design architecture for WhatsApp.

Home Page: https://orkestral.io

License: Apache License 2.0

TypeScript 46.23% JavaScript 53.77%
whatsapp sulla bot whatsapp-api whatsapp-bot zap-api zap-bot ai ai-bot bot-javascript

venom's Introduction

🕷Venom Bot🕸

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

Build Status Lint Status release-it

Venom is a high-performance system developed with JavaScript to create a bot for WhatsApp, support for creating any interaction, such as customer service, media sending, sentence recognition based on artificial intelligence and all types of design architecture for WhatsApp.

Get started fast and easy! Official API!

Full Documentation

It's a high-performance alternative API to whatzapp, you can send, text messages, files, images, videos and more.

Remember, the API was developed on a platform called RESTful Web services, providing interoperability between computer systems on the Internet.

It uses a set of well-defined operations that apply to all information resources: HTTP itself defines a small set of operations, the most important being POST, GET, PUT and DELETE.

Use it in your favorite language like PHP, Python, C# and others. as long as your language is supported with the HTTP protocol, you will save time and money. you don't need to know how Venom works, we have the complete API documentation, in a professional way!

Get our official API Venom ! Contact us!

Venom group support on Telegram

Venom group support on Discord

Meet the Superchats


SuperChats

SuperChats is a premium library with unique features that control Whatsapp functions with socket. With Superchats you can build service bots, multiservice chats or any system that uses Whatsapp

Superchats is a premium version of Venom, with exclusive features and support for companies and developers worldwide
https://github.com/orkestral/superchats

Buy a license Superchats

The value of the license is $50 monthly dollars, to acquire contact in whatsapp by clicking on the image below !!

🕷🕷 Functions Venom🕷🕷

🚻 Automatic QR Refresh
📁 Send text, image, video, audio and docs
👥 Get contacts, chats, groups, group members, Block List
📞 Send contacts
Send Buttons
Send stickers
Send stickers GIF
Multiple Sessions
⏩ Forward Messages
📥 Receive message
👤 insert user section
📍 Send location!!
🕸🕸 and much more

Documentation at https://orkestral.github.io/venom/index.html

Installation

> npm i --save venom-bot

or for Nightly releases:

> npm i --save https://github.com/orkestral/venom/releases/download/nightly/venom-bot-nightly.tgz

Installing the current repository "you can download the beta version from the current repository!"

> npm i github:orkestral/venom

Getting started

// Supports ES6
// import { create, Whatsapp } from 'venom-bot';
const venom = require('venom-bot');

venom
  .create({
    session: 'session-name' //name of session
  })
  .then((client) => start(client))
  .catch((erro) => {
    console.log(erro);
  });

function start(client) {
  client.onMessage((message) => {
    if (message.body === 'Hi' && message.isGroupMsg === false) {
      client
        .sendText(message.from, 'Welcome Venom 🕷')
        .then((result) => {
          console.log('Result: ', result); //return object success
        })
        .catch((erro) => {
          console.error('Error when sending: ', erro); //return object error
        });
    }
  });
}
After executing create() function, venom will create an instance of whatsapp web. If you are not logged in, it will print a QR code in the terminal. Scan it with your phone and you are ready to go!
Venom will remember the session so there is no need to authenticate everytime.
Multiples sessions can be created at the same time by pasing a session name to create() function:
// Init sales whatsapp bot
venom.create('sales').then((salesClient) => {...});

// Init support whatsapp bot
venom.create('support').then((supportClient) => {...});

Optional create parameters

Venom create() method third parameter can have the following optional parameters:

If you are using the Linux server do not forget to pass the args --user-agent Original parameters in browserArgs

const venom = require('venom-bot');

venom
  .create(
    //session
    'sessionName', //Pass the name of the client you want to start the bot
    //catchQR
    (base64Qrimg, asciiQR, attempts, urlCode) => {
      console.log('Number of attempts to read the qrcode: ', attempts);
      console.log('Terminal qrcode: ', asciiQR);
      console.log('base64 image string qrcode: ', base64Qrimg);
      console.log('urlCode (data-ref): ', urlCode);
    },
    // statusFind
    (statusSession, session) => {
      console.log('Status Session: ', statusSession); //return isLogged || notLogged || browserClose || qrReadSuccess || qrReadFail || autocloseCalled || desconnectedMobile || deleteToken || chatsAvailable || deviceNotConnected || serverWssNotConnected || noOpenBrowser || initBrowser || openBrowser || connectBrowserWs || initWhatsapp || erroPageWhatsapp || successPageWhatsapp || waitForLogin || waitChat || successChat
      //Create session wss return "serverClose" case server for close
      console.log('Session name: ', session);
    },
    // options
    {
      browserPathExecutable: '', // browser executable path
      folderNameToken: 'tokens', //folder name when saving tokens
      mkdirFolderToken: '', //folder directory tokens, just inside the venom folder, example:  { mkdirFolderToken: '/node_modules', } //will save the tokens folder in the node_modules directory
      headless: 'new', // you should no longer use boolean false or true, now use false, true or 'new' learn more https://developer.chrome.com/articles/new-headless/
      devtools: false, // Open devtools by default
      debug: false, // Opens a debug session
      logQR: true, // Logs QR automatically in terminal
      browserWS: '', // If u want to use browserWSEndpoint
      browserArgs: [''], // Original parameters  ---Parameters to be added into the chrome browser instance
      addBrowserArgs: [''], // Add broserArgs without overwriting the project's original
      puppeteerOptions: {}, // Will be passed to puppeteer.launch
      disableSpins: true, // Will disable Spinnies animation, useful for containers (docker) for a better log
      disableWelcome: true, // Will disable the welcoming message which appears in the beginning
      updatesLog: true, // Logs info updates automatically in terminal
      autoClose: 60000, // Automatically closes the venom-bot only when scanning the QR code (default 60 seconds, if you want to turn it off, assign 0 or false)
      createPathFileToken: false, // creates a folder when inserting an object in the client's browser, to work it is necessary to pass the parameters in the function create browserSessionToken
      addProxy: [''], // Add proxy server exemple : [e1.p.webshare.io:01, e1.p.webshare.io:01]
      userProxy: '', // Proxy login username
      userPass: '' // Proxy password
    },

    // BrowserInstance
    (browser, waPage) => {
      console.log('Browser PID:', browser.process().pid);
      waPage.screenshot({ path: 'screenshot.png' });
    }
  )
  .then((client) => {
    start(client);
  })
  .catch((erro) => {
    console.log(erro);
  });

Callback Status Session

Gets the return if the session is isLogged or notLogged or browserClose or qrReadSuccess or qrReadFail or autocloseCalled or desconnectedMobile or deleteToken or chatsAvailable or deviceNotConnected or serverWssNotConnected or noOpenBrowser or initBrowser or openBrowser or connectBrowserWs or initWhatsapp or erroPageWhatsapp or successPageWhatsapp or waitForLogin or waitChat or successChat or Create session wss return "serverClose" case server for close

Status Condition
isLogged When the user is already logged in to the browser
notLogged When the user is not connected to the browser, it is necessary to scan the QR code through the cell phone in the option WhatsApp Web
browserClose If the browser is closed this parameter is returned
qrReadSuccess If the user is not logged in, the QR code is passed on the terminal a callback is returned. After the correct reading by cell phone this parameter is returned
qrReadFail If the browser stops when the QR code scan is in progress, this parameter is returned
autocloseCalled The browser was closed using the autoClose command
desconnectedMobile Client has desconnected in to mobile
serverClose Client has desconnected in to wss
deleteToken If you pass true within the function
chatsAvailable When Venom is connected to the chat list
deviceNotConnected Chat not available because the phone is disconnected (Trying to connect to the phone)
serverWssNotConnected The address wss was not found!
noOpenBrowser It was not found in the browser, or some command is missing in args
initBrowser Starting the browser
openBrowser The browser has been successfully opened!
connectBrowserWs Connection with BrowserWs successfully done!
initWhatsapp Starting whatsapp!
erroPageWhatsapp Error accessing whatsapp page
successPageWhatsapp Page Whatsapp successfully accessed
waitForLogin Waiting for login verification!
waitChat Waiting for the chat to load
successChat Chat successfully loaded!
const venom = require('venom-bot');
venom
  .create('sessionName', undefined, (statusSession, session) => {
    console.log('Status Session: ', statusSession);
    //return isLogged || notLogged || browserClose || qrReadSuccess || qrReadFail || autocloseCalled || desconnectedMobile || deleteToken || chatsAvailable || deviceNotConnected || serverWssNotConnected || noOpenBrowser || initBrowser || openBrowser || connectBrowserWs || initWhatsapp || erroPageWhatsapp || successPageWhatsapp || waitForLogin || waitChat || successChat
    //Create session wss return "serverClose" case server for close
    console.log('Session name: ', session);
  })
  .then((client) => {
    start(client);
  })
  .catch((erro) => {
    console.log(erro);
  });

Exporting QR Code

By default QR code will appear on the terminal. If you need to pass the QR somewhere else heres how:

const fs = require('fs');
const venom = require('venom-bot');

venom
  .create(
    'sessionName',
    (base64Qr, asciiQR, attempts, urlCode) => {
      console.log(asciiQR); // Optional to log the QR in the terminal
      var matches = base64Qr.match(/^data:([A-Za-z-+\/]+);base64,(.+)$/),
        response = {};

      if (matches.length !== 3) {
        return new Error('Invalid input string');
      }
      response.type = matches[1];
      response.data = new Buffer.from(matches[2], 'base64');

      var imageBuffer = response;
      require('fs').writeFile(
        'out.png',
        imageBuffer['data'],
        'binary',
        function (err) {
          if (err != null) {
            console.log(err);
          }
        }
      );
    },
    undefined,
    { logQR: false }
  )
  .then((client) => {
    start(client);
  })
  .catch((erro) => {
    console.log(erro);
  });

Downloading Files

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

import fs = require('fs');
import mime = require('mime-types');

client.onMessage( async (message) => {
  if (message.isMedia === true || message.isMMS === true) {
    const buffer = await client.decryptFile(message);
    // 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(message.mimetype)}`;
    fs.writeFile(fileName, buffer, (err) => {
      ...
    });
  }
});

Basic Functions (usage)

Not every available function is listed, for further look, every function available can be found in here and here

Chatting

Here, chatId could be <phoneNumber>@c.us or <phoneNumber>-<groupId>@g.us
// Send Poll
const poll = {
  name: 'new poll',
  options: [
    {
      name: 'option 1'
    },
    {
      name: 'option 2'
    }
  ],
  selectableOptionsCount: 1
};
await client.sendPollCreation('[email protected]', poll)
.then((result) => {
    console.log('Result: ', result); //return object success
})
.catch((erro) => {
    console.error('Error when sending: ', erro); //return object error
});

// Send List menu
const list = [
    {
      title: "Pasta",
      rows: [
        {
          title: "Ravioli Lasagna",
          description: "Made with layers of frozen cheese",
        }
      ]
    },
    {
      title: "Dessert",
      rows: [
        {
          title: "Baked Ricotta Cake",
          description: "Sweets pecan baklava rolls",
        },
        {
          title: "Lemon Meringue Pie",
          description: "Pastry filled with lemonand meringue.",
        }
      ]
    }
  ];

await client.sendListMenu('[email protected]', 'Title', 'subTitle', 'Description', 'menu', list)
  .then((result) => {
    console.log('Result: ', result); //return object success
  })
  .catch((erro) => {
    console.error('Error when sending: ', erro); //return object error
  });

// Send Messages with Buttons Reply
const buttons = [
  {
    "buttonText": {
      "displayText": "Text of Button 1"
      }
    },
  {
    "buttonText": {
      "displayText": "Text of Button 2"
      }
    }
  ]
await client.sendButtons('[email protected]', 'Title', 'Description', buttons)
  .then((result) => {
    console.log('Result: ', result); //return object success
  })
  .catch((erro) => {
    console.error('Error when sending: ', erro); //return object error
  });
// Send audio file MP3
await client.sendVoice('[email protected]', './audio.mp3').then((result) => {
    console.log('Result: ', result); //return object success
  })
  .catch((erro) => {
    console.error('Error when sending: ', erro); //return object error
  });

// Send audio file base64
await client.sendVoiceBase64('[email protected]', base64MP3)
  .then((result) => {
    console.log('Result: ', result); //return object success
  })
  .catch((erro) => {
    console.error('Error when sending: ', erro); //return object error
  });

// Send contact
await client
  .sendContactVcard('[email protected]', '[email protected]', 'Name of contact')
  .then((result) => {
    console.log('Result: ', result); //return object success
  })
  .catch((erro) => {
    console.error('Error when sending: ', erro); //return object error
  });

// Send a list of contact cards
await client
  .sendContactVcardList('[email protected]', [
    '[email protected]',
    '[email protected]',
  ])
  .then((result) => {
    console.log('Result: ', result); //return object success
  })
  .catch((erro) => {
    console.error('Error when sending: ', erro); //return object error
  });

// Send basic text
await client
  .sendText('[email protected]', '👋 Hello from venom!')
  .then((result) => {
    console.log('Result: ', result); //return object success
  })
  .catch((erro) => {
    console.error('Error when sending: ', erro); //return object error
  });


// Send text message by injecting keystrokes into WhatsApp, thus maintaining the typing indicator
let success = await client.sendTextViaTyping('[email protected]', '👋 Hello from venom!');

// Send photo or video by injecting keystrokes
let success = await client.sendPhotoVideoViaTyping('[email protected]', 'path/to/file.jpg', 'Pretty sunset');

// Send location
await client
  .sendLocation('[email protected]', '-13.6561589', '-69.7309264', 'Brasil')
  .then((result) => {
    console.log('Result: ', result); //return object success
  })
  .catch((erro) => {
    console.error('Error when sending: ', erro); //return object error
  });

// Automatically sends a link with the auto generated link preview. You can also add a custom message to be added.
await client
  .sendLinkPreview(
    '[email protected]',
    'https://www.youtube.com/watch?v=V1bFr2SWP1I',
    'Kamakawiwo ole'
  )
  .then((result) => {
    console.log('Result: ', result); //return object success
  })
  .catch((erro) => {
    console.error('Error when sending: ', erro); //return object error
  });

// Send image (you can also upload an image using a valid HTTP protocol)
await client
  .sendImage(
    '[email protected]',
    'path/to/img.jpg',
    'image-name',
    'Caption text'
  )
  .then((result) => {
    console.log('Result: ', result); //return object success
  })
  .catch((erro) => {
    console.error('Error when sending: ', erro); //return object error
  });


// Send image file base64
await client.sendImageFromBase64('[email protected]', base64Image, "name file")
  .then((result) => {
    console.log('Result: ', result); //return object success
  })
  .catch((erro) => {
    console.error('Error when sending: ', erro); //return object error
  });

// Send file (venom will take care of mime types, just need the path)
// you can also upload an image using a valid HTTP protocol
await client
  .sendFile(
    '[email protected]',
    'path/to/file.pdf',
    'file_name',
    'See my file in pdf'
  )
  .then((result) => {
    console.log('Result: ', result); //return object success
  })
  .catch((erro) => {
    console.error('Error when sending: ', erro); //return object error
  });

// Sends file
// base64 parameter should have mime type already defined
await client
  .sendFileFromBase64(
    '[email protected]',
    base64PDF,
    'file_name.pdf',
    'See my file in pdf'
  )
  .then((result) => {
    console.log('Result: ', result); //return object success
  })
  .catch((erro) => {
    console.error('Error when sending: ', erro); //return object error
  });

// Generates sticker from the provided animated gif image and sends it (Send image as animated sticker)
// image path imageBase64 A valid gif and webp image is required. You can also send via http/https (http://www.website.com/img.gif)
await client
  .sendImageAsStickerGif('[email protected]', './image.gif')
  .then((result) => {
    console.log('Result: ', result); //return object success
  })
  .catch((erro) => {
    console.error('Error when sending: ', erro); //return object error
  });

// Generates sticker from given image and sends it (Send Image As Sticker)
// image path imageBase64 A valid png, jpg and webp image is required. You can also send via http/https (http://www.website.com/img.jpg)
await client
  .sendImageAsSticker('[email protected]', './image.jpg')
  .then((result) => {
    console.log('Result: ', result); //return object success
  })
  .catch((erro) => {
    console.error('Error when sending: ', erro); //return object error
  });

// Forwards messages
await client.forwardMessages(
  '[email protected]',
  ['[email protected]_B70847EE89E22D20FB86ECA0C1B11609','[email protected]_B70847EE89E22D20FB86ECA0C1B11777']
).then((result) => {
    console.log('Result: ', result); //return object success
})
.catch((erro) => {
    console.error('Error when sending: ', erro); //return object error
});

// Send @tagged message
await client.sendMentioned(
  '[email protected]',
  'Hello @5218113130740 and @5218243160777!',
  ['5218113130740', '5218243160777']
);

// Reply to a message
await client.reply(
  '[email protected]',
  'This is a reply!',
  '[email protected]_7C22WHCB6DKYHJKQIEN9'
).then((result) => {
    console.log('Result: ', result); //return object success
}).catch((erro) => {
    console.error('Error when sending: ', erro); //return object error
});

// Send message with options
await client.
        .sendMessageOptions(
          '[email protected]',
          'This is a reply!',
           {
              quotedMessageId: reply,
            }
        )
        .then((retorno) => {
          resp = retorno;
        })
        .catch((e) => {
          console.log(e);
        });

// Send gif
await client.sendVideoAsGif(
  '[email protected]',
  'path/to/video.mp4',
  'video.gif',
  'Gif image file'
);

//checks and returns whether a message and a reply
// exemple:
// await client.onMessage(async (message) => {
//     console.log(await client.returnReply(message)); // replicated message
//     console.log(message.body ); //customer message
//   })
checkReply = await client.returnReply(messagem);

// Send seen ✔️✔️
await client.sendSeen('[email protected]');

// Start typing...
await client.startTyping('[email protected]');

// Set chat state (0: Typing, 1: Recording, 2: Paused)
await client.setChatState('[email protected]', 0 | 1 | 2);

Retrieving Data

// Retrieve all chats
const chats = await client.getAllChats();

//Retrieves all chats new messages
const chatsAllNew = getAllChatsNewMsg();

//Retrieves all chats Contacts
const contacts = await client.getAllChatsContacts();

//Retrieve all contacts new messages
const contactNewMsg = await client.getChatContactNewMsg();

// Retrieve all groups
// you can pass the group id optional use, exemple: client.getAllChatsGroups('[email protected]')
const chats = await client.getAllChatsGroups();

//Retrieve all groups new messages
const groupNewMsg = await client.getChatGroupNewMsg();

//Retrieves all chats Transmission list
const transmission = await client.getAllChatsTransmission();

// Retrieve contacts
const contacts = await client.getAllContacts();

// Returns a list of mute and non-mute users
// "all" List all mutes
// "toMute" List all silent chats
// "noMute" List all chats without silence
const listMute = await client.getListMute('all');

// Calls your list of blocked contacts (returns an array)
const getBlockList = await client.getBlockList();

// Retrieve messages in chat
//chatID chat id
//includeMe will be by default true, if you do not want to pass false
//includeNotifications will be by default true, if you do not want to pass false
//const Messages = await client.getAllMessagesInChat(chatID, includeMe, includeNotifications)
const Messages = await client.getAllMessagesInChat('[email protected]');

// Retrieve more chat message
const moreMessages = await client.loadEarlierMessages('[email protected]');

// Retrieve all messages in chat
const allMessages = await client.loadAndGetAllMessagesInChat(
  '[email protected]'
);

// Retrieve contact status
const status = await client.getStatus('[email protected]');

// Retrieve user profile
// Please note that this function does not currently work due to a bug in WhatsApp itself.
// There is no telling if or when this function might work again.
const user = await client.getNumberProfile('[email protected]');

// Retrieve all unread message
const messages = await client.getUnreadMessages();

// Retrieve profile fic (as url)
const url = await client.getProfilePicFromServer('[email protected]');

// Retrieve chat/conversation
const chat = await client.getChat('[email protected]');

// Check if the number exists
const chat = await client
  .checkNumberStatus('[email protected]')
  .then((result) => {
    console.log('Result: ', result); //return object success
  })
  .catch((erro) => {
    console.error('Error when sending: ', erro); //return object error
  });

Group Functions

// groupId or chatId: leaveGroup [email protected]

//change group description
await client
  .setGroupDescription('[email protected]', 'group description')
  .then((result) => {
    console.log('Result: ', result); //return object success
  })
  .catch((erro) => {
    console.error('Error when sending: ', erro); //return object error
  });

// Leave group
await client.leaveGroup('[email protected]');

// Get group members
await client.getGroupMembers('[email protected]');

// Get group members ids
await client.getGroupMembersIds('[email protected]');

// Generate group invite url link
await client.getGroupInviteLink('[email protected]');

// Create group (title, participants to add)
await client.createGroup('Group name', [
  '[email protected]',
  '[email protected]'
]);

// Remove participant
await client.removeParticipant('[email protected]', '[email protected]');

// Add participant
await client.addParticipant('[email protected]', '[email protected]');

// Promote participant (Give admin privileges)
await client.promoteParticipant('[email protected]', '[email protected]');

// Demote particiapnt (Revoke admin privileges)
await client.demoteParticipant('[email protected]', '[email protected]');

// Get group admins
await client.getGroupAdmins('[email protected]');

// Return the group status, jid, description from it's invite link
await client.getGroupInfoFromInviteLink(InviteCode);

// Join a group using the group invite code
await client.joinGroup(InviteCode);

Profile Functions

// Set client status
await client.setProfileStatus('On vacations! ✈️');

// Set client profile name
await client.setProfileName('Venom bot');

// Set client profile photo
await client.setProfilePic('path/to/image.jpg');

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

Device Functions

// Disconnect from service
await client.logout();

// Delete the Service Worker
await client.killServiceWorker();

// Load the service again
await client.restartService();

// Get connection state
await client.getConnectionState();

// Get battery level
await client.getBatteryLevel();

// Is connected
await client.isConnected();

// Get whatsapp web version
await client.getWAVersion();

Events

//Listens to all new messages
//To receiver or recipient
client.onAnyMessage(message => {
  ...
};

// Listen to messages
client.onMessage(message => {
  ...
})

// Listen to state changes
client.onStateChange(state => {
  ...
});

// Listen to ack's
// See the status of the message when sent.
// When receiving the confirmation object, "ack" may return a number, look {@link AckType} for details:
// -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 =

client.onAck(ack => {
  ...
});

// Listen to live location
// chatId: '[email protected]'
client.onLiveLocation("[email protected]", (liveLocation) => {
  ...
});

// chatId looks like this: '[email protected]'
// Event interface is in here: https://github.com/s2click/venom/blob/master/src/api/model/participant-event.ts
client.onParticipantsChanged("[email protected]", (event) => {
  ...
});

// Listen when client has been added to a group
client.onAddedToGroup(chatEvent => {
  ...
});

Other

//Check if there is chat
await client
  .checkChat(chatId)
  .then((result) => {
    console.log('Result: ', result); //return object success
  })
  .catch((erro) => {
    console.error('Error when sending: ', erro); //return object error
  });

// Pin chat and Unpin chat messages with true or false
// Pin chat, non-existent (optional)
await client
  .pinChat(chatId, true, false)
  .then((result) => {
    console.log('Result: ', result); //return object success
  })
  .catch((erro) => {
    console.error('Error when sending: ', erro); //return object error
  });

///mute a contact
await client
  .sendMute(
    '[email protected]', //contact mute
    30, //duration of silence, example: 30 minutes
    'minutes' ///kind of silence "hours" "minutes" "year"
  )
  .then((result) => {
    console.log('Result: ', result); //return object success
  })
  .catch((erro) => {
    console.error('Error when sending: ', erro); //return object error
  });

///unmute contact
await client
  .sendMute(
    '[email protected]' //contact unmute
  )
  .then((result) => {
    console.log('Result: ', result); //return object success
  })
  .catch((erro) => {
    console.error('Error when sending: ', erro); //return object error
  });

// Change the theme
// string types "dark" or "light"
await client.setTheme('dark');

// Receive the current theme
// returns string light or dark
await client.getTheme();

// Delete chat
await client.deleteChat('[email protected]');

// Clear chat messages
await client.clearChatMessages('[email protected]');

// Archive and unarchive chat messages with true or false
await client.archiveChat(chatId, true);

// Delete message (last parameter: delete only locally)
await client
  .deleteMessage('[email protected]', [
    '[email protected]_B70847EE89E22D20FB86ECA0C1B11609',
    '[email protected]_B70847EE89E22D20FB86ECA0C1B11777'
  ])
  .then((result) => {
    console.log('Result: ', result); //return object success
  })
  .catch((erro) => {
    console.error('Error when sending: ', erro); //return object error
  });

// Mark chat as not seen (returns true if it works)
await client.markUnseenMessage('[email protected]');

// Blocks a user (returns true if it works)
await client.blockContact('[email protected]');

// Unlocks contacts (returns true if it works)
await client.unblockContact('[email protected]');

Misc

There are some tricks for a better usage of venom.

Keep session alive:

// function to detect conflits and change status
// Force it to keep the current session
// Possible state values:
// CONFLICT
// CONNECTED
// DEPRECATED_VERSION
// OPENING
// PAIRING
// PROXYBLOCK
// SMB_TOS_BLOCK
// TIMEOUT
// TOS_BLOCK
// UNLAUNCHED
// UNPAIRED
// UNPAIRED_IDLE
client.onStateChange((state) => {
  console.log('State changed: ', state);
  // force whatsapp take over
  if ('CONFLICT'.includes(state)) client.useHere();
  // detect disconnect on whatsapp
  if ('UNPAIRED'.includes(state)) console.log('logout');
});

// DISCONNECTED
// SYNCING
// RESUMING
// CONNECTED
let time = 0;
client.onStreamChange((state) => {
  console.log('State Connection Stream: ' + state);
  clearTimeout(time);
  if (state === 'DISCONNECTED' || state === 'SYNCING') {
    time = setTimeout(() => {
      client.close();
    }, 80000);
  }
});

// function to detect incoming call
client.onIncomingCall(async (call) => {
  console.log(call);
  client.sendText(call.peerJid, "Sorry, I still can't answer calls");
});

Closing (saving) sessions

Close the session properly to ensure the session is saved for the next time you log in (So it won't ask for QR scan again). So instead of CTRL+C,

// Catch ctrl+C
process.on('SIGINT', function() {
  client.close();
});

// Try-catch close
try {
   ...
} catch (error) {
   client.close();
}

Auto closing unsynced sessions

The auto close is enabled by default and the timeout is set to 60 sec. Receives the time in milliseconds to countdown until paired.

Use "autoClose: 0 | false" to disable auto closing.

Debugging

WhatsApp Web Versions

You can use cached versions of WhatsApp Web by passing the webVersion arguments as part of your venom options:

venom.create({
    session: 'sessionname', //name of session
    headless: false,
    logQR: true,
    webVersion: '2.2402.5'
  })
  .then((client) => {
    start(client);
  });

This feature can use any version available in the list at https://github.com/wppconnect-team/wa-version/tree/main/html

Development

Building venom is really simple altough it contains 3 main projects inside

  1. Wapi project
> npm run build:wapi
  1. Middleware
> npm run build:middleware
> npm run build:jsQR
  1. Venom
> npm run build:venom

To build the entire project just run

> npm run build

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.

venom's People

Contributors

9cb14c1ec0 avatar adierebel avatar alanmartines avatar antirek avatar blrocha avatar clovisdanielss avatar dependabot[bot] avatar dogcalas avatar edgardmessias avatar eriectanijaya avatar faeln1 avatar felipeescher avatar fredwuz avatar humbertorodrigues avatar joaosouz4dev avatar joedutra avatar jonalan7 avatar jrrcdev avatar limshengli avatar maico910 avatar micheltukker avatar ohadcn avatar orkestral avatar pezhvak avatar renandecarlo avatar sme12435 avatar steve2955 avatar tanderbolt avatar zafranf avatar ziadmontaser avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

venom's Issues

Is there a way to check if I'm sending a message?

I know there is a way to check if the customer has sent a message!

client.onMessage((message) => { ... });

Is there the reverse?

Check for example if I send a message by cell phone!
With the same authenticated

How to send mp3 as audio

Hi, I tried sending an mp3 file with sendFile () but the file was sent not as audio but as a normal file

image
*It was sent like that, instead of
image

QRCode is not working

My phone doesn't recognize the QR Code.

as a temporary solution I've used this options:
{ headless: false, logQR: false, useChrome: true } and read QRCode at Chrome Window, but it doesn't work at my terminal

Error after authentication

Im start the node.js and type the code

const venom = require('venom-bot');

venom.create().then((client) => start(client));

function start(client) {
  client.onMessage((message) => {
    if (message.body === 'Hi') {
      client.sendText(message.from, 'Welcome Venom 🕷');
    }
  });
}

After this, the script run, and show me the QR code.
I scan, get sucess message, and error in next.

See:

√ Checking for updates
√ ���Compilation Mutation���
√ Starting With Success!

(node:20168) UnhandledPromiseRejectionWarning: ReferenceError: start is not defined
    at repl:1:33
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:20168) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:20168) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

implementation support

good morning brother I hope you are very well, first I want to congratulate you for a great job. I have several implementation questions and I hope you can help me. I need to make an api where I can connect several sessions, therefore I need to do it in an orderly way. I explain to you I have several routes as I told you before, I have routes to start the session, I have routes to see contacts, I have routes to see groups, example

builder() {
this.router.get ('/ retrieve-all-messages /: chatId', homeController.retrieveAllMessages);
this.router.get ('/ new-message /: contactId /: message', homeController.newMessage);
this.router.get ('/ get-connections-state', homeController.getConnectionState);
this.router.get ('/ validate-number /: number', homeController.validateNumber);
this.router.get ('/ check-status-device', homeController.checkStatusDevices);
this.router.get ('/ get-battery-level', homeController.getBatteryLevel);
this.router.get ('/ get-host-devices', homeController.getHostDevice);
this.router.get ('/ contacts', homeController.contacts);
this.router.get ('/ groups', homeController.groups);
this.router.get ('/ unread', homeController.unread);
this.router.get ('/ test', homeController.test);
}

Now, at the session start which is test, I would like to return to the front client a token or something that allows me to identify the session and attach it to each request so that I do not have to make each request to create the 'client' intact but only Check if the session is active or not, and process the request. Why? good because currently all the methods that I use from your library are instantiated from the client object that the correct create method returns to me? so what does that mean? that for me to be able to obtain the contacts I execute the create method and then I pass it to that action so this always generates a delay in the responses from my server. so I wish I could optimize that process. Do you have any idea how I can do something like that?

/ auth return token
/ get-message /: token

for example something like this, where you don't need to create every time
get-message () {
token = req.params.token
if (token === valid) {
res.send (token.getContacts)
}
}
as well

venom.create ('test'). then (async (client: any) => {
client.sendText (req.params.contactId, req.params.message);
res.status (200) .send (message sent: $ {req.params.message});
});

because the venom.create ('') part I'm always doing

Label e primeira mensagem

Oi, tudo bem?

Gostaria de saber se existe suporte para:

  • Arquivar a mensagem.
  • Colocar Label na mensagem.
  • Saber se a mensagem recebida é a primeira (Para exibir uma lista de opções, por exemplo).

Abraços.

How to track exceptions

Edit: I forgot to mention that I've never used Node or Express before this, in my life. So please go easy on me.

Hey!

I am running this program through an API I made in Express. When I call the endpoint with my desired number and message, it should send the message to my desired number. This works fine on my local computer but when I upload this whole code to my server that I want to use it on, It stops working.

When I first upload it to the server, I was getting the messages but they stopped all of a sudden. I tried removing tokens and adding new Whatsapp accounts but that was to no avail. Also, before, my API was returning 200 when everything was working fine but now it returns a 404.

To be specific, here's my route so you have an idea of what I'm talking about:

app.get('/sendText/:number/:message', async function (req, res) {
	var number = req.params.number;
	var chatId = number + '@c.us';
	var message = req.params.message	
	
	await client.sendText(chatId, message);

	console.log(chatId)
	console.log(message)

	res.status(200).json({
		number: number,
		chatId: chatId,
	});
});

Also, I know there's nothing wrong with my server as it does print the chatId and message in the console when I call the API.

What's going on?

Build step update in Readme.md

Inside Readme Development section

i think it should be npm run build:middleware instead npm run build:build:middleware

PR for same : #14

Selection_075

Stuck at waiting

Hello, I try to make simple whatsapp bot, but I stuck at waiting, something wrong ?

I'm using WSL 2 (Ubuntu 20.04).
image

My app.js :

const venom = require('venom-bot');

venom.create("session-coba", {
                headless: true, // Headless chrome
                devtools: false, // Open devtools by default
                useChrome: true, // If false will use Chromium instance
                debug: false, // Opens a debug session
                logQR: true, // Logs QR automatically in terminal
                browserArgs: [''], // Parameters to be added into the chrome browser instance
                refreshQR: 15000, // Will refresh QR every 15 seconds, 0 will load QR once. Default is 30 seconds
          }).then((client) => {
                  start(client)
                }).catch(erro => console.log(erro))

function start(client) {
  client.onMessage((message) => {
    if (message.body === 'Hi') {
      client.sendText(message.from, 'Welcome Venom 🕷' );
    }
  });
}

Thanks

Function getBatteryLevel();

Hello,

As i did
async function f1() {
var bateria = await client.getBatteryLevel();
console.log(bateria);
res.send(bateria);
}

f1();

The error generated was

(node:11664) UnhandledPromiseRejectionWarning: Error: Evaluation failed: ReferenceError: output is not defined
at Object.window.WAPI.getBatteryLevel (C:\venom\node_modules\venom-bot\dist\lib\wapi\wapi.js:1:43845)
at puppeteer_evaluation_script:1:28
at ExecutionContext._evaluateInternal (C:\venom\node_modules\puppeteer\lib\ExecutionContext.js:102:19)
at processTicksAndRejections (internal/process/task_queues.js:97:5)
at async ExecutionContext.evaluate (C:\venom\node_modules\puppeteer\lib\ExecutionContext.js:33:16)
-- ASYNC --
at ExecutionContext. (C:\venom\node_modules\puppeteer\lib\helper.js:94:19)
at DOMWorld.evaluate (C:\venom\node_modules\puppeteer\lib\DOMWorld.js:89:24)
at processTicksAndRejections (internal/process/task_queues.js:97:5)
-- ASYNC --
at Frame. (C:\venom\node_modules\puppeteer\lib\helper.js:94:19)
at Page.evaluate (C:\venom\node_modules\puppeteer\lib\Page.js:612:14)
at Page. (C:\venom\node_modules\puppeteer\lib\helper.js:95:27)
at Whatsapp. (C:\venom\node_modules\venom-bot\dist\api\layers\host.layer.js:107:60)
at step (C:\venom\node_modules\venom-bot\dist\api\layers\host.layer.js:33:23)
at Object.next (C:\venom\node_modules\venom-bot\dist\api\layers\host.layer.js:14:53)
at C:\venom\node_modules\venom-bot\dist\api\layers\host.layer.js:8:71
at new Promise ()
at __awaiter (C:\venom\node_modules\venom-bot\dist\api\layers\host.layer.js:4:12)
at Whatsapp.HostLayer.getBatteryLevel (C:\venom\node_modules\venom-bot\dist\api\layers\host.layer.js:104:16)
-- ASYNC --
at Page. (C:\venom\node_modules\puppeteer\lib\helper.js:94:19)
at Whatsapp. (C:\venom\node_modules\venom-bot\dist\api\layers\host.layer.js:107:60)
at step (C:\venom\node_modules\venom-bot\dist\api\layers\host.layer.js:33:23)
at Object.next (C:\venom\node_modules\venom-bot\dist\api\layers\host.layer.js:14:53)
at C:\venom\node_modules\venom-bot\dist\api\layers\host.layer.js:8:71
at new Promise ()
at __awaiter (C:\venom\node_modules\venom-bot\dist\api\layers\host.layer.js:4:12)
at Whatsapp.HostLayer.getBatteryLevel (C:\venom\node_modules\venom-bot\dist\api\layers\host.layer.js:104:16)
at f1 (C:\venom\sucesso.js:35:28)
at C:\venom\sucesso.js:40:1
(node:11664) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:11664) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Thanks!

storage sesion with another query

hello brother I ask you, how can I export or respond to a front the client instance and pass it to another request so that it does not ask me to authenticate in each request, example I am implementing your library but in a node server to use angular in the frontend then for example

I have a path / login where I scan the qr code and log out

but i have another route / get-messages

and there when I access it asks me to rewrite the session because I am running the create method again to have the client instance, I need help how to optimize that process with an example and thanks

Error: Page crashed! How to catch it.

Error: Page crashed! at Page._onTargetCrashed (/home/whatsapp/node_modules/puppeteer/lib/Page.js:209:28) at CDPSession.<anonymous> (/home/whatsapp/node_modules/puppeteer/lib/Page.js:129:57) at CDPSession.emit (events.js:315:20) at CDPSession._onMessage (/home/whatsapp/node_modules/puppeteer/lib/Connection.js:166:18) at Connection._onMessage (/home/whatsapp/node_modules/puppeteer/lib/Connection.js:83:25) at WebSocket.<anonymous> (/home/whatsapp/node_modules/puppeteer/lib/WebSocketTransport.js:25:32) at WebSocket.onMessage (/home/whatsapp/node_modules/ws/lib/event-target.js:125:16) at WebSocket.emit (events.js:315:20) at Receiver.receiverOnMessage (/home/whatsapp/node_modules/ws/lib/websocket.js:800:20) at Receiver.emit (events.js:315:20)

how to catch it.

how to install

Good Morning
I'm not able to install on debian 8 with nodejs already installed ...
please if possible send me a detailed tutorial on how to install and make the basics sound better .. Thanks.

unable to reply

hi, i tried to send reply with some message.id format, but i got no luck..

here is my code..

    let from = message.from;
    let m_id = message.id;

    /* send reply 1 */
    let m_id1 = m_id.toString();
    let reply1 = await client.reply(from, 'This is a reply 1!', m_id1);
    console.log('ini mid1', m_id1);
    console.log('ini reply1', reply1);
    console.log('\n');

    /* send reply 2 */
    let m_id2 = m_id.toString() + '@c.us';
    let reply2 = await client.reply(from, 'This is a reply 2!', m_id2);
    console.log('ini mid2', m_id2);
    console.log('ini reply2', reply2);
    console.log('\n');

    /* send reply 3 */
    let m_id3 = m_id.toString().toString().replace('false_', '');
    let reply3 = await client.reply(from, 'This is a reply 3!', m_id3);
    console.log('ini mid3', m_id3);
    console.log('ini reply3', reply3);
    console.log('\n');

    /* send reply 34*/
    let m_id4 = m_id.toString().replace('false_' + from + '_', '');
    let reply4 = await client.reply(from, 'This is a reply 4!', m_id4);
    console.log('ini mid4', m_id4);
    console.log('ini reply4', reply4);
    console.log('\n');

    /* send reply 34*/
    let m_id5 = m_id.toString().replace('false_' + from + '_', '') + '@c.us';
    let reply5 = await client.reply(from, 'This is a reply 5!', m_id5);
    console.log('ini mid5', m_id5);
    console.log('ini reply5', reply5);
    console.log('\n');

and here is the results

ini mid1 [email protected]_3A54913E4FBBB4C58101
ini reply1 undefined

ini mid2 [email protected][email protected]
ini reply2 undefined

ini mid3 [email protected]_3A54913E4FBBB4C58101
ini reply3 undefined

ini mid4 3A54913E4FBBB4C58101
ini reply4 undefined

ini mid5 [email protected]
ini reply5 undefined

Always waiting when starting the Venom bot

I found something wrong when starting the Venom bot

(node:7380) UnhandledPromiseRejectionWarning: TimeoutError: Navigation timeout of 30000 ms exceeded at C:\xampp\htdocs\venom-bot\node_modules\puppeteer\lib\LifecycleWatcher.js:100:111 -- ASYNC -- at Frame.<anonymous> (C:\xampp\htdocs\venom-bot\node_modules\puppeteer\lib\helper.js:94:19) at Page.goto (C:\xampp\htdocs\venom-bot\node_modules\puppeteer\lib\Page.js:485:53) at Page.<anonymous> (C:\xampp\htdocs\venom-bot\node_modules\puppeteer\lib\helper.js:95:27) at Object.<anonymous> (C:\xampp\htdocs\venom-bot\node_modules\venom-bot\dist\controllers\browser.js:138:49) at step (C:\xampp\htdocs\venom-bot\node_modules\venom-bot\dist\controllers\browser.js:44:23) at Object.next (C:\xampp\htdocs\venom-bot\node_modules\venom-bot\dist\controllers\browser.js:25:53) at fulfilled (C:\xampp\htdocs\venom-bot\node_modules\venom-bot\dist\controllers\browser.js:16:58) at processTicksAndRejections (internal/process/task_queues.js:97:5) (node:7380) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwin g inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch() . To terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict( see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1) (node:7380) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise reje ctions that are not handled will terminate the Node.js process with a non-zero exit code.

Venom is timing out after 24 hours

I'm using Venom to run a chatbot. Everything works perfectly but after 24 hours, Venom shows a time out message and after restarting, it's stuck on "authenticating".

If I delete the 'tokens' directory and try again, I have to rescan the QR and it starts working again.

Is there a way to watch the 'TIMEOUT' event and reconnect, without having to scan the QR each time? Or is it a limitation with Whatsapp web that we'll have to reauth with a QR every 24 hours?

Múltiplos acessos

Pessoal, boa tarde.

Tenho uma dúvida:

Há a possibilidade de utilizar o Venom-Bot + Whatsapp web no PC?

Estou tentando aqui mas um derruba o outro, os 2 não conseguem coexistir.

Audio files need a modification to work

The message with audio files (opus) has "type":"ptt" and "isMedia":false, so the function downloadFile
on whatsapp.ts modeule checks the flag isMedia = true in order to download the audio file, if i remove this check the audio file is downloaded properly.
Thanks in advance.
Antonio

build venom-bot

Oi! Eu fiz uma aplicação com Electron e o venom-bot. O app funiona bem no VS Code, mas quando faço o build do electron o venom para de funiconar. Como faço o build do venom nesse caso?


Hi! I made an application with Electron and the venom-bot. The app works well on VS Code, but when I build the electron the venom stops working. How do I build venom in this case?

Sorry for my english "Google translator"

Error DEBIAN9.X

root@APOIO-DANIEL-NAO-APAGAR:~/BOT# npm start

[email protected] start /root/BOT
npm run build:venom & tsc app.ts && node app.js

[email protected] build:venom /root/BOT
tsc

(node:1722) UnhandledPromiseRejectionWarning: Error: Failed to launch the browser process!
[0610/202122.834338:ERROR:zygote_host_impl_linux.cc(89)] Running as root without --no-sandbox is not supported. See https://crbug.com/638180.

TROUBLESHOOTING: https://github.com/puppeteer/puppeteer/blob/master/docs/troubleshooting.md

at onClose (/root/BOT/node_modules/puppeteer/lib/launcher/BrowserRunner.js:159:20)
at Interface.<anonymous> (/root/BOT/node_modules/puppeteer/lib/launcher/BrowserRunner.js:149:65)
at Interface.emit (events.js:327:22)
at Interface.close (readline.js:424:8)
at Socket.onend (readline.js:202:10)
at Socket.emit (events.js:327:22)
at endReadableNT (_stream_readable.js:1224:12)
at processTicksAndRejections (internal/process/task_queues.js:84:21)

(Use node --trace-warnings ... to show where the warning was created)
(node:1722) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:1722) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
✓ Checking for updates
⠙ Creating whatsapp instace...

(node:124162) UnhandledPromiseRejectionWarning: Error: Page crashed!

Hey,

Thank you for providing this solution.

I raised this issue yesterday also in the whatsapp chat.
It does not make any sense to move issues and support into the whatsapp channel.

When i have an issue, i search the issues on the github page for other similar issues and possible solutions.

If you move the support into the whatsapp, you are going to have people asking the same issues over and over. because answers are going to be in a chat in whatsapp, that you cant search back in time.

Please can you keep this issue open. Its after happening again today...

NOT for me, but for everyone who comes looking for a solution

#30

(node:124162) UnhandledPromiseRejectionWarning: Error: Page crashed! at Page._onTargetCrashed (/home/dave/ashtangayogacork.ie-whatsbot/node_modules/puppeteer/lib/Page.js:209:28) at CDPSession.Page.client.on (/home/dave/ashtangayogacork.ie-whatsbot/node_modules/puppeteer/lib/Page.js:129:57) at CDPSession.emit (events.js:198:13) at CDPSession._onMessage (/home/dave/ashtangayogacork.ie-whatsbot/node_modules/puppeteer/lib/Connection.js:166:18) at Connection._onMessage (/home/dave/ashtangayogacork.ie-whatsbot/node_modules/puppeteer/lib/Connection.js:83:25) at WebSocketTransport._ws.addEventListener (/home/dave/ashtangayogacork.ie-whatsbot/node_modules/puppeteer/lib/WebSocketTransport.js:25:32) at WebSocket.onMessage (/home/dave/ashtangayogacork.ie-whatsbot/node_modules/ws/lib/event-target.js:125:16) at WebSocket.emit (events.js:198:13) at Receiver.receiverOnMessage (/home/dave/ashtangayogacork.ie-whatsbot/node_modules/ws/lib/websocket.js:800:20) at Receiver.emit (events.js:198:13) (node:124162) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1) (node:124162) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

client.close() function not found

When I try to invoke the function "client".close() it get the error: "client.close is not a function";
Any other way to close the session?

Error when using addParticipant

Hello i see something at the console when using addParticipant. it said that

"Hello i see something at the console when using addParticipant. it said that

Error: Evaluation failed: TypeError: n is not a function
    at myfilepath\venom-bot\dist\lib\wapi\wapi.js:1:28064
    at H (https://web.whatsapp.com/app.14adffa5e404bcc68e38.js:1:1016102)
    at MutationObserver.W (https://web.whatsapp.com/app.14adffa5e404bcc68e38.js:1:1015683)
    at ExecutionContext._evaluateInternal (myfilepath\node_modules\puppeteer\lib\ExecutionContext.js:102:19)        
    at processTicksAndRejections (internal/process/task_queues.js:94:5)
    at async ExecutionContext.evaluate (myfilepath\node_modules\puppeteer\lib\ExecutionContext.js:33:16)
  -- ASYNC --
    at ExecutionContext.<anonymous> (myfilepath\node_modules\puppeteer\lib\helper.js:94:19)
    at DOMWorld.evaluate (myfilepath\node_modules\puppeteer\lib\DOMWorld.js:89:24)
    at processTicksAndRejections (internal/process/task_queues.js:94:5)
  -- ASYNC --
    at Frame.<anonymous> (myfilepath\node_modules\puppeteer\lib\helper.js:94:19)
    at Page.evaluate (myfilepath\node_modules\puppeteer\lib\Page.js:612:14)
    at Page.<anonymous> (myfilepath\node_modules\puppeteer\lib\helper.js:95:27)
    at Whatsapp.<anonymous> (myfilepath\node_modules\venom-bot\dist\api\layers\group.layer.js:162:60)
    at step (myfilepath\node_modules\venom-bot\dist\api\layers\group.layer.js:46:23)
    at Object.next (myfilepath\node_modules\venom-bot\dist\api\layers\group.layer.js:27:53)
    at myfilepath\node_modules\venom-bot\dist\api\layers\group.layer.js:21:71
    at new Promise (<anonymous>)
    at __awaiter (myfilepath\node_modules\venom-bot\dist\api\layers\group.layer.js:17:12)
    at Whatsapp.GroupLayer.addParticipant (myfilepath\node_modules\venom-bot\dist\api\layers\group.layer.js:159:16) 
  -- ASYNC --
    at Page.<anonymous> (myfilepath\node_modules\puppeteer\lib\helper.js:94:19)
    at Whatsapp.<anonymous> (myfilepath\node_modules\venom-bot\dist\api\layers\group.layer.js:162:60)
    at Whatsapp.<anonymous> (myfilepath\node_modules\venom-bot\dist\api\layers\group.layer.js:162:60)
    at step (myfilepath\node_modules\venom-bot\dist\api\layers\group.layer.js:46:23)
    at Object.next (myfilepath\node_modules\venom-bot\dist\api\layers\group.layer.js:27:53)
    at myfilepath\node_modules\venom-bot\dist\api\layers\group.layer.js:21:71
    at new Promise (<anonymous>)
    at __awaiter (myfilepath\node_modules\venom-bot\dist\api\layers\group.layer.js:17:12)
    at Whatsapp.GroupLayer.addParticipant (myfilepath\node_modules\venom-bot\dist\api\layers\group.layer.js:159:16) 
    at myfilepath\index.js:118:26
    at processTicksAndRejections (internal/process/task_queues.js:94:5)"

and when using this function, can we check that add participant is success or not? Thanks.

section by token for node api

It's ready section by token!? For implementation?

Example

Path /login - > get Auth and response token

Path /get-messages - > get messages by token in active session,

Implementation in node server

Chatbot

Há algum jeito de fazer um chatbot com essa API? Eu estou tentando algo bem básico, mas sem sucesso...

Exemplo:

 await client.onMessage((message) => {
        io.emit('message-received', message)

        if (message.body.toLowerCase().includes('olá')) {
            var textArray = [ //random message
                `Olá, tudo bem? 
                Digite 1 para pegar a 2ª via do seu boleto ou
                Digite 2 para verificar suas pendências`,

                `Seja bem vindo!! 
                Digite 1 para pegar a 2ª via do seu boleto ou
                Digite 2 para verificar suas pendências`,
            ]

            var i = Math.floor(Math.random() * textArray.length)
            client.sendText(message.from, textArray[i]);

        } else if (message.body === '1' || message.body === 1) { //choice 1
            client.sendText(message.from, `Certo, você escolheu: *2ª via do boleto.*, você quer para este mês mesmo? Diga *sim* ou *não*`);
        } else if (message.body === '2') { //choice 2
            client.sendText(message.from, `Certo, aguarde um instante, estou verificando...`);
        }

Assim ele até funciona, mas quando chega na parte do "sim" ou "não" não tem o que ser feito, já que só da pra adicionar uma instancia de onMessage

Valeu!

How to read only a few messages?

Hi, I need to read the an amount of latest messages from a chat.
This amount can be 10 for sample.

I tried some samples posted here as:
loadAndGetAllMessagesInChat();
It works, but calls all chat messages
Is it possible?
Does someone could post a sample?

Cannot build the project running "npm run build", any tips ?

[08:58:50] Using gulpfile C:\Source\NodeJs\venom\src\lib\jsQR\gulpfile.js
[08:58:50] Starting 'default'...
[08:58:50] Finished 'default' after 47 ms
src/controllers/browser.ts:68:40 - error TS2345: Argument of type 'import("C:/Source/NodeJs/venom/node_modules/puppeteer-extra/node_modules/@types/puppeteer/index").Browser' is not assignable to parameter of type 'import("C:/Source/NodeJs/venom/node_modules/@types/puppeteer/index").Browser'.
Types of property 'on' are incompatible.
Type '<K extends "disconnected" | "targetchanged" | "targetcreated" | "targetdestroyed">(eventName: K, handler: (e: import("C:/Source/NodeJs/venom/node_modules/puppeteer-extra/node_modules/@types/puppeteer/index").BrowserEventObj[K], ...args: any[]) => void) => import("C:/Source/NodeJs/venom/node_modules/puppeteer-extra/n...' is not assignable to type '<K extends "disconnected" | "targetchanged" | "targetcreated" | "targetdestroyed">(eventName: K, handler: (e: import("C:/Source/NodeJs/venom/node_modules/@types/puppeteer/index").BrowserEventObj[K], ...args: any[]) => void) => import("C:/Source/NodeJs/venom/node_modules/@types/puppeteer/index").Browser'.
Types of parameters 'handler' and 'handler' are incompatible.
Types of parameters 'e' and 'e' are incompatible.
Type 'import("C:/Source/NodeJs/venom/node_modules/puppeteer-extra/node_modules/@types/puppeteer/index").BrowserEventObj[K]' is not assignable to type 'import("C:/Source/NodeJs/venom/node_modules/@types/puppeteer/index").BrowserEventObj[K]'.
Type 'import("C:/Source/NodeJs/venom/node_modules/puppeteer-extra/node_modules/@types/puppeteer/index").BrowserEventObj' is not assignable to type 'import("C:/Source/NodeJs/venom/node_modules/@types/puppeteer/index").BrowserEventObj'.
The types returned by 'targetchanged.browserContext().newPage()' are incompatible between these types.
Type 'Promise<import("C:/Source/NodeJs/venom/node_modules/puppeteer-extra/node_modules/@types/puppeteer/index").Page>' is not assignable to type 'Promise<import("C:/Source/NodeJs/venom/node_modules/@types/puppeteer/index").Page>'.
Type 'import("C:/Source/NodeJs/venom/node_modules/puppeteer-extra/node_modules/@types/puppeteer/index").Page' is not assignable to type 'import("C:/Source/NodeJs/venom/node_modules/@types/puppeteer/index").Page'.
Types of property 'on' are incompatible.
Type '<K extends "error" | "dialog" | "close" | "load" | "response" | "request" | "domcontentloaded" | "console" | "frameattached" | "framedetached" | "framenavigated" | "metrics" | "pageerror"
| ... 4 more ... | "workerdestroyed">(eventName: K, handler: (e: import("C:/Source/NodeJs/venom/node_modules/puppeteer-extra/node...' is not assignable to type '<K extends "error" | "dialog" | "close" | "load" | "response" | "request" | "domcontentloaded" | "console" | "frameattached" | "framedetached" | "framenavigated" | "metrics" | "pageerror" | ... 4 more ... | "workerdestroyed">(eventName: K, handler: (e: import("C:/Source/NodeJs/venom/node_modules/@types/puppeteer/ind...'.
Types of parameters 'handler' and 'handler' are incompatible.
Types of parameters 'e' and 'e' are incompatible.
Type 'import("C:/Source/NodeJs/venom/node_modules/puppeteer-extra/node_modules/@types/puppeteer/index").PageEventObj[K]' is not assignable to type 'import("C:/Source/NodeJs/venom/node_modules/@types/puppeteer/index").PageEventObj[K]'.
Type 'import("C:/Source/NodeJs/venom/node_modules/puppeteer-extra/node_modules/@types/puppeteer/index").PageEventObj' is not assignable to type 'import("C:/Source/NodeJs/venom/node_modules/@types/puppeteer/index").PageEventObj'.
The types returned by 'console.args()' are incompatible between these types.
Type 'import("C:/Source/NodeJs/venom/node_modules/puppeteer-extra/node_modules/@types/puppeteer/index").JSHandle[]' is not assignable to type 'import("C:/Source/NodeJs/venom/node_modules/@types/puppeteer/index").JSHandle[]'.
Type 'import("C:/Source/NodeJs/venom/node_modules/puppeteer-extra/node_modules/@types/puppeteer/index").JSHandle' is not assignable to type 'import("C:/Source/NodeJs/venom/node_modules/@types/puppeteer/index").JSHandle'.
The types returned by 'asElement().contentFrame()' are incompatible between these types.
Type 'Promise<import("C:/Source/NodeJs/venom/node_modules/puppeteer-extra/node_modules/@types/puppeteer/index").Frame>' is not assignable to type 'Promise<import("C:/Source/NodeJs/venom/node_modules/@types/puppeteer/index").Frame>'.
Type 'import("C:/Source/NodeJs/venom/node_modules/puppeteer-extra/node_modules/@types/puppeteer/index").Frame' is not assignable to type 'import("C:/Source/NodeJs/venom/node_modules/@types/puppeteer/index").Frame'.
The types returned by 'executionContext()' are incompatible between these types.
Type 'Promise' is missing the following properties from type 'ExecutionContext': queryObjects, evaluate, evaluateHandle
Type 'PageEventObj[K]' is not assignable to type 'never'.
Type 'Error | Dialog | ConsoleMessage | Worker | Frame | Request | Response | { title: string; metrics: Metrics; } | Page' is not assignable to type 'never'.
Type 'Error' is not assignable to type 'never'.
Type 'BrowserEventObj[K]' is not assignable to type 'undefined'.
Type 'Target' is not assignable to type 'undefined'.

68 const waPage = await getWhatsappPage(browser);
~~~~~~~

Found 1 error.

npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! [email protected] build: npm run build:wapi && npm run build:middleware && npm run build:jsQR && tsc
npm ERR! Exit status 2
npm ERR!
npm ERR! Failed at the [email protected] build script.

hiring developer for this

sorry if that's not allowed but i really need someone with knowledge on this to make some functions work

Persist token

I'm currently using Heroku and everytime my Dyno restarts I need to rescan the code. Is there a way to persist the token to a database, and not to a file?

Thanks. Amazing work.

Download ppt (push to talk)

I already sent this issue, the download file function cannot download ppt audio if testing the flag "message.isMedia" I need always to comment. Below the code, I got the last version and still that way,
thanks in advance.

/**

  • Decrypts message file

  • @param message Message object

  • @returns Decrypted file buffer (null otherwise)
    */
    public async downloadFile(message: Message) {
    //if (message.isMedia) {
    const url = message.clientUrl;
    const encBase64 = await this.page.evaluate((url: string) => {
    return fetch(url)
    .then((response) => response.arrayBuffer())
    .then((bytes) => WAPI.arrayBufferToBase64(bytes));
    }, url);

    return decrypt(encBase64, message);
    //} else {
    // return null;
    //}
    }
    }

Exported QR code is not recognized by the reader

Following the example "Exporting QR", it is possible to successfully generate the QR code .png file.

However, when trying to scan the QR code of the generated image, it is not recognized.

It is only possible to scan the QR code through the terminal.

Error sending csv file

await client.sendFile(chatId, 'path/to/file.csv', 'cv.csv', '');
when trying to send a csv
3992e4da-8db4-48a8-99be-632d73161c50

How to use it with Python?

Hey Orkestral!
Amazing piece of work. When all else failed, this worked.

Now, I have no experience with node what-so-ever but I was hoping anyone could help and guide me on how to use it with Python. I was to send messages using a Python script but I just don't know where to start. Can you help?

Authentication does not work (scanning QR code does nothing)

When I start a WhatsApp client using venom-bot I first get this log:

- Checking for updates...
- Checking for updates...
- Creating whatsapp instace...
Chrome not found, using chromium
- Checking for updates
- Creating whatsapp instace...
- Checking for updates
- Authenticating...
- Checking for updates
- Authenticate to continue

Then I get the QR code, which I scan. Then the phone acts as if the authentication was successful (short vibration and switch back to contact list), but the promise that creates the client object never returns. Just as if no authentication happened or as if venom-bot would not be able to detect the authentication. WhatsApp probably changed their web interface and broke venom-bot?

Versions:
venom-bot: 1.0.4
node: 10.16.3

node 12.18 LTS: browser.setMaxListeners is not a function

I tried to figure out the other bug that I've reported and upgraded node to the newest LTS version (12.18.0) and now I get this crash on startup:

TypeError: browser.setMaxListeners is not a function
    at StealthPlugin.onBrowser (/home/x/x/shared/node_modules/puppeteer-extra-plugin-stealth/index.js:155:13)
    at StealthPlugin._bindBrowserEvents (/home/x/x/shared/node_modules/puppeteer-extra-plugin/src/index.ts:527:36)
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
    at PuppeteerExtra.callPlugins (/home/x/x/shared/node_modules/puppeteer-extra/src/index.ts:449:7)
    at PuppeteerExtra.launch (/home/x/x/shared/node_modules/puppeteer-extra/src/index.ts:175:5)

Using pupeteer 4.0.0. Is that not the version I should use?

sendFile() is not sending a caption.

sendFile() is not sending a caption ou perhaps i am doing something wrong.
Do i must do any change on the caption string ? I am just sending 'test', but is no working, below the screen on my wa, the name it working ok:

image

venom doesn't go out of wait

I liked sulla very much, probably I would also like the venom, if it worked, I already reported a problem here, and it has not been solved: first issue
please do not want to have to look for another api, yours is very good:

anyway, the bot is only in the 'waiting', and does not come out of it

✓ Checking for updates
⠼ 🕷🕷🕷Waiting...🕷🕷🕷

if I try to restart, it returns:

(node:8732) UnhandledPromiseRejectionWarning: Error: Protocol error (Target.setDiscoverTargets): Target closed.
    at D:\Pessoal\Projetos\Projetos nodejs\Private\bot9ano\node_modules\puppeteer\lib\Connection.js:53:63      
    at new Promise (<anonymous>)
    at Connection.send (D:\Pessoal\Projetos\Projetos nodejs\Private\bot9ano\node_modules\puppeteer\lib\Connection.js:52:16)
    at Function.create (D:\Pessoal\Projetos\Projetos nodejs\Private\bot9ano\node_modules\puppeteer\lib\Browser.js:43:26)
    at ChromeLauncher.launch (D:\Pessoal\Projetos\Projetos nodejs\Private\bot9ano\node_modules\puppeteer\lib\Launcher.js:79:53)
    at processTicksAndRejections (internal/process/task_queues.js:93:5)
    at async PuppeteerExtra.launch (D:\Pessoal\Projetos\Projetos nodejs\Private\bot9ano\node_modules\puppeteer-extra\dist\index.cjs.js:129:25)
(node:8732) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:8732) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

ps: my code is the basics:

// Supports ES6
// import { create, Whatsapp } from 'venom-bot';
const venom = require('venom-bot');

venom.create().then((client) => start(client));

function start(client) {
  client.onMessage((message) => {
    if (message.body === 'Hi') {
      client.sendText(message.from, 'Welcome Venom 🕷');
    }
  });
}

sent message status

Is there any sent message status confirmation or other way to confirm that?

Como rodar no droplet?

Criei um chatbot e estou querendo subir a aplicação para um servidor ubuntu, porém não consigo startar o projeto:

image

Consegue me dar uma luz?

Já fiz a instalação das dependências do puppeteer.

Venom does not leave the "waiting"

I already used sulla for a few months, and I decided to migrate to venom, because of an authentication problem .. and here the same problem happens! my code is the simplest because i just went to test it

`// Supports ES6
// import { create, Whatsapp } from 'venom-bot';
const venom = require('venom-bot');

venom.create().then((client) => start(client));

function start(client) {
client.onMessage((message) => {
if (message.body === 'Hi') {
client.sendText(message.from, 'Welcome Venom 🕷');
}
});
}`

(I don't know how to use git very well)

Venom just breaks if has no authentication

Hi,

If I leave a sessions waiting for auth It breaks when auto close run. Even if I try reopen the same same session it won't work.

image

Won't work with catch block as well.

Btw, amazing work :D

UnhandledPromiseRejectionWarning:

Is there a way to catch these errors

(node:108995) UnhandledPromiseRejectionWarning: Error: Page crashed! at Page._onTargetCrashed (/home/dave/ashtangayogacork.ie-whatsbot/node_modules/puppeteer/lib/Page.js:209:28) at CDPSession.Page.client.on (/home/dave/ashtangayogacork.ie-whatsbot/node_modules/puppeteer/lib/Page.js:129:57) at CDPSession.emit (events.js:198:13) at CDPSession._onMessage (/home/dave/ashtangayogacork.ie-whatsbot/node_modules/puppeteer/lib/Connection.js:166:18) at Connection._onMessage (/home/dave/ashtangayogacork.ie-whatsbot/node_modules/puppeteer/lib/Connection.js:83:25) at WebSocketTransport._ws.addEventListener (/home/dave/ashtangayogacork.ie-whatsbot/node_modules/puppeteer/lib/WebSocketTransport.js:25:32) at WebSocket.onMessage (/home/dave/ashtangayogacork.ie-whatsbot/node_modules/ws/lib/event-target.js:125:16) at WebSocket.emit (events.js:198:13) at Receiver.receiverOnMessage (/home/dave/ashtangayogacork.ie-whatsbot/node_modules/ws/lib/websocket.js:800:20) at Receiver.emit (events.js:198:13) (node:108995) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1) (node:108995) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled wi ll terminate the Node.js process with a non-zero exit code.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.