Update README.md

This commit is contained in:
Adhiraj Singh
2020-06-13 12:57:25 +05:30
parent 5aedc028e0
commit b023546210

192
README.md
View File

@@ -14,8 +14,7 @@
const WhatsAppWeb = require('baileys') const WhatsAppWeb = require('baileys')
``` ```
## Connecting ## Connecting
``` javascript
``` javascript
const client = new WhatsAppWeb() const client = new WhatsAppWeb()
client.connect() client.connect()
.then (([user, chats, contacts, unread]) => { .then (([user, chats, contacts, unread]) => {
@@ -24,11 +23,12 @@
console.log ("you have " + chats.length + " chats") console.log ("you have " + chats.length + " chats")
}) })
.catch (err => console.log("unexpected error: " + err) ) .catch (err => console.log("unexpected error: " + err) )
``` ```
If the connection is successful, you will see a QR code printed on your terminal screen, scan it with WhatsApp on your phone and you'll be logged in! If the connection is successful, you will see a QR code printed on your terminal screen, scan it with WhatsApp on your phone and you'll be logged in!
If you don't want to wait for WhatsApp to send all your chats while connecting, you can use the following function: If you don't want to wait for WhatsApp to send all your chats while connecting, you can use the following function:
``` javascript
``` javascript
const client = new WhatsAppWeb() const client = new WhatsAppWeb()
client.connectSlim() // does not wait for chats & contacts client.connectSlim() // does not wait for chats & contacts
.then (user => { .then (user => {
@@ -41,12 +41,11 @@
}) })
}) })
.catch (err => console.log("unexpected error: " + err)) .catch (err => console.log("unexpected error: " + err))
``` ```
## Handling Events ## Handling Events
Implement the following callbacks in your code:
Implement the following callbacks in your code: - Called when you have a pending unread message or recieve a new message
- Called when you have a pending unread message or recieve a new message
``` javascript ``` javascript
client.setOnUnreadMessage (m => { client.setOnUnreadMessage (m => {
const [notificationType, messageType] = client.getNotificationType(m) // get what type of notification it is -- message, group add notification etc. const [notificationType, messageType] = client.getNotificationType(m) // get what type of notification it is -- message, group add notification etc.
@@ -54,11 +53,11 @@
console.log("message type: " + messageType) // conversation, imageMessage, videoMessage, contactMessage etc. console.log("message type: " + messageType) // conversation, imageMessage, videoMessage, contactMessage etc.
}, false) // set to `true` if you want to receive outgoing messages that may be sent from your phone }, false) // set to `true` if you want to receive outgoing messages that may be sent from your phone
``` ```
- Called when you recieve an update on someone's presence, they went offline or online - Called when you recieve an update on someone's presence, they went offline or online
``` javascript ``` javascript
client.setOnPresenceUpdate (json => console.log(json.id + " presence is " + json.type)) client.setOnPresenceUpdate (json => console.log(json.id + " presence is " + json.type))
``` ```
- Called when your message gets delivered or read - Called when your message gets delivered or read
``` javascript ``` javascript
client.setOnMessageStatusChange (json => { client.setOnMessageStatusChange (json => {
let sent = json.to let sent = json.to
@@ -68,15 +67,39 @@
console.log(sent + " acknowledged message(s) " + json.ids + " as " + json.type + " at " + json.timestamp) console.log(sent + " acknowledged message(s) " + json.ids + " as " + json.type + " at " + json.timestamp)
}) })
``` ```
- Called when the connection gets disconnected (either the server loses internet or the phone gets unpaired) - Called when the connection gets disconnected (either the server loses internet or the phone gets unpaired)
``` javascript ``` javascript
client.setOnUnexpectedDisconnect (err => console.log ("disconnected unexpectedly: " + err) ) client.setOnUnexpectedDisconnect (err => console.log ("disconnected unexpectedly: " + err) )
``` ```
## Sending Messages ## Sending Messages
It's super simple
It's super simple - Called when you have a pending unread message or recieve a new message
``` javascript
- Send text messages using client.setOnUnreadMessage (m => {
const [notificationType, messageType] = client.getNotificationType(m) // get what type of notification it is -- message, group add notification etc.
console.log("got notification of type: " + notificationType) // message, groupAdd, groupLeave
console.log("message type: " + messageType) // conversation, imageMessage, videoMessage, contactMessage etc.
}, false) // set to `true` if you want to receive outgoing messages that may be sent from your phone
```
- Called when you recieve an update on someone's presence, they went offline or online
``` javascript
client.setOnPresenceUpdate (json => console.log(json.id + " presence is " + json.type))
```
- Called when your message gets delivered or read
``` javascript
client.setOnMessageStatusChange (json => {
let sent = json.to
if (json.participant) // participant exists when the message is from a group
sent += " ("+json.participant+")" // mention as the one sent to
// log that they acknowledged the message
console.log(sent + " acknowledged message(s) " + json.ids + " as " + json.type + " at " + json.timestamp)
})
```
- Called when the connection gets disconnected (either the server loses internet or the phone gets unpaired)
``` javascript
client.setOnUnexpectedDisconnect (err => console.log ("disconnected unexpectedly: " + err) )
```d text messages using
``` javascript ``` javascript
client.sendTextMessage(id, "oh hello there!") client.sendTextMessage(id, "oh hello there!")
``` ```
@@ -85,12 +108,40 @@
const options = {quoted: quotedMessage} const options = {quoted: quotedMessage}
client.sendTextMessage(id, "oh hello there", options) client.sendTextMessage(id, "oh hello there", options)
``` ```
``` quotedMessage ``` is a message object `Implement the following callbacks in your code:
- Send a location using
- Called when you have a pending unread message or recieve a new message
``` javascript
client.setOnUnreadMessage (m => {
const [notificationType, messageType] = client.getNotificationType(m) // get what type of notification it is -- message, group add notification etc.
console.log("got notification of type: " + notificationType) // message, groupAdd, groupLeave
console.log("message type: " + messageType) // conversation, imageMessage, videoMessage, contactMessage etc.
}, false) // set to `true` if you want to receive outgoing messages that may be sent from your phone
```
- Called when you recieve an update on someone's presence, they went offline or online
``` javascript
client.setOnPresenceUpdate (json => console.log(json.id + " presence is " + json.type))
```
- Called when your message gets delivered or read
``` javascript
client.setOnMessageStatusChange (json => {
let sent = json.to
if (json.participant) // participant exists when the message is from a group
sent += " ("+json.participant+")" // mention as the one sent to
// log that they acknowledged the message
console.log(sent + " acknowledged message(s) " + json.ids + " as " + json.type + " at " + json.timestamp)
})
```
- Called when the connection gets disconnected (either the server loses internet or the phone gets unpaired)
``` javascript
client.setOnUnexpectedDisconnect (err => console.log ("disconnected unexpectedly: " + err) )
```
` quotedMessage ` is a message object
- Send a location using
``` javascript ``` javascript
client.sendLocationMessage(id, 24.121231, 55.1121221) // the latitude, longitude of the location client.sendLocationMessage(id, 24.121231, 55.1121221) // the latitude, longitude of the location
``` ```
- Send a contact using - Send a contact using
``` javascript ``` javascript
// format the contact as a VCARD // format the contact as a VCARD
const vcard = 'BEGIN:VCARD\n' // metadata of the contact card const vcard = 'BEGIN:VCARD\n' // metadata of the contact card
@@ -101,7 +152,7 @@
+ 'END:VCARD' + 'END:VCARD'
client.sendContactMessage(id, "Jeff", vcard) client.sendContactMessage(id, "Jeff", vcard)
``` ```
- Send a media (image, video, sticker, pdf) message using - Send a media (image, video, sticker, pdf) message using
``` javascript ``` javascript
const buffer = fs.readFileSync("example/ma_gif.mp4") // load some gif const buffer = fs.readFileSync("example/ma_gif.mp4") // load some gif
const options = {gif: true, caption: "hello!"} // some metadata & caption const options = {gif: true, caption: "hello!"} // some metadata & caption
@@ -119,7 +170,7 @@
] ]
``` ```
- Tested formats: png, jpeg, webp (sticker), mp4, ogg - Tested formats: png, jpeg, webp (sticker), mp4, ogg
```options``` is a JSON object, providing some information about the message. It can have the following __optional__ values: `options` is a JSON object, providing some information about the message. It can have the following __optional__ values:
``` javascript ``` javascript
info = { info = {
caption: "hello there!", // (for media messages) the caption to send with the media (cannot be sent with stickers though) caption: "hello there!", // (for media messages) the caption to send with the media (cannot be sent with stickers though)
@@ -137,29 +188,34 @@
timestamp: Date() // optional, if you want to manually set the timestamp of the message timestamp: Date() // optional, if you want to manually set the timestamp of the message
} }
``` ```
``` id ``` is the WhatsApp id of the person or group you're sending the message to.
It must be in the format ```[country code][phone number]@s.whatsapp.net```, for example ```+19999999999@s.whatsapp.net``` for people. For groups, it must be in the format ``` 123456789-123345@g.us ```. **Do not attach** `@c.us` for individual people IDs, It won't work ``` id ``` is the WhatsApp id of the person or group you're sending the message to.
It must be in the format ```[country code][phone number]@s.whatsapp.net```, for example ```+19999999999@s.whatsapp.net``` for people. For groups, it must be in the format ``` 123456789-123345@g.us ```. **Do not attach** `@c.us` for individual people IDs, It won't work
## Sending Read Receipts ## Sending Read Receipts
``` javascript ``` javascript
client.sendReadReceipt(id, messageID) client.sendReadReceipt(id, messageID)
``` ```
The id is in the same format as mentioned earlier. The message ID is the unique identifier of the message that you are marking as read. On a message object, it can be accessed using ```messageID = message.key.id```. The id is in the same format as mentioned earlier. The message ID is the unique identifier of the message that you are marking as read. On a message object, it can be accessed using ```messageID = message.key.id```.
## Update Presence ## Update Presence
``` javascript ``` javascript
client.updatePresence(id, WhatsAppWeb.Presence.available) client.updatePresence(id, WhatsAppWeb.Presence.available)
``` ```
This lets the person/group with ``` id ``` know whether you're online, offline, typing etc. where ``` presence ``` can be one of the following: This lets the person/group with ``` id ``` know whether you're online, offline, typing etc. where ``` presence ``` can be one of the following:
``` javascript ``` javascript
[ [
WhatsAppWeb.Presence.available, // online WhatsAppWeb.Presence.available, // online
WhatsAppWeb.Presence.unavailable, // offline WhatsAppWeb.Presence.unavailable, // offline
WhatsAppWeb.Presence.composing, // typing... WhatsAppWeb.Presence.composing, // typing...
WhatsAppWeb.Presence.recording // recording... WhatsAppWeb.Presence.recording // recording...
] ]
``` ```
## Decoding Media ## Decoding Media
If you want to save & process some images, videos, documents or stickers you received If you want to save & process some images, videos, documents or stickers you received
``` javascript ``` javascript
client.setOnUnreadMessage (m => { client.setOnUnreadMessage (m => {
const messageType = client.getMessageType(m.message) // get what type of message it is -- text, image, video const messageType = client.getMessageType(m.message) // get what type of message it is -- text, image, video
// if the message is not a text message // if the message is not a text message
@@ -169,25 +225,27 @@
.catch (err => console.log("error in decoding message: " + err)) .catch (err => console.log("error in decoding message: " + err))
} }
} }
``` ```
## Restoring Sessions ## Restoring Sessions
Once you connect successfully, you can get your authentication credentials using Once you connect successfully, you can get your authentication credentials using
``` javascript ``` javascript
const authJSON = client.base64EncodedAuthInfo() const authJSON = client.base64EncodedAuthInfo()
``` ```
Then you can use this JSON to log back in without needing to scan a QR code using Then you can use this JSON to log back in without needing to scan a QR code using
``` javascript ``` javascript
const authJSON = JSON.parse( fs.readFileSync("auth_info.json") ) const authJSON = JSON.parse( fs.readFileSync("auth_info.json") )
client.connect (authJSON) client.connect (authJSON)
.then (([user, chats, contacts, unread]) => console.log ("yay connected")) .then (([user, chats, contacts, unread]) => console.log ("yay connected"))
``` ```
## Querying ## Querying
- To check if a given ID is on WhatsApp - To check if a given ID is on WhatsApp
``` javascript ``` javascript
client.isOnWhatsApp ("xyz@c.us") client.isOnWhatsApp ("xyz@c.us")
.then (([exists, id]) => console.log(id + (exists ? " exists " : " does not exist") + "on WhatsApp")) .then (([exists, id]) => console.log(id + (exists ? " exists " : " does not exist") + "on WhatsApp"))
``` ```
- To query chat history on a group or with someone - To query chat history on a group or with someone
``` javascript ``` javascript
client.loadConversation ("xyz-abc@g.us", 25) // query the last 25 messages (replace 25 with the number of messages you want to query) client.loadConversation ("xyz-abc@g.us", 25) // query the last 25 messages (replace 25 with the number of messages you want to query)
.then (messages => console.log("got back " + messages.length + " messages")) .then (messages => console.log("got back " + messages.length + " messages"))
@@ -197,31 +255,32 @@
client.loadEntireConversation ("xyz@c.us", (message) => console.log("Loaded message with ID: " + message.key.id)) client.loadEntireConversation ("xyz@c.us", (message) => console.log("Loaded message with ID: " + message.key.id))
.then (() => console.log("queried all messages")) // promise resolves once all messages are retreived .then (() => console.log("queried all messages")) // promise resolves once all messages are retreived
``` ```
- To get the status of some person - To get the status of some person
``` javascript ``` javascript
client.getStatus ("xyz@c.us") // leave empty to get your own client.getStatus ("xyz@c.us") // leave empty to get your own
.then ((json, q) => console.log("status: " + json.status)) .then ((json, q) => console.log("status: " + json.status))
``` ```
- To get the display picture of some person/group - To get the display picture of some person/group
``` javascript ``` javascript
client.getProfilePicture ("xyz@g.us") // leave empty to get your own client.getProfilePicture ("xyz@g.us") // leave empty to get your own
.then (([json, q]) => console.log("download profile picture from: " + json.eurl)) .then (([json, q]) => console.log("download profile picture from: " + json.eurl))
``` ```
- To get someone's presence (if they're typing, online) - To get someone's presence (if they're typing, online)
``` javascript ``` javascript
client.requestPresenceUpdate ("xyz@c.us") client.requestPresenceUpdate ("xyz@c.us")
// the presence update is fetched and called here // the presence update is fetched and called here
client.setOnPresenceUpdate (json => console.log(json.id + " presence is " + json.type)) client.setOnPresenceUpdate (json => console.log(json.id + " presence is " + json.type))
``` ```
Of course, replace ``` xyz ``` with an actual ID. Also, append ``` @c.us ``` for individuals & ``` @g.us ``` for groups. Of course, replace ``` xyz ``` with an actual ID. Also, append ``` @c.us ``` for individuals & ``` @g.us ``` for groups.
## Groups ## Groups
- To query the metadata of a group - To query the metadata of a group
``` javascript ``` javascript
client.groupMetadata ("abcd-xyz@g.us") client.groupMetadata ("abcd-xyz@g.us")
.then (([json, _]) => console.log(json.id + ", title: " + json.subject + ", description: " + json.desc)) .then (([json, _]) => console.log(json.id + ", title: " + json.subject + ", description: " + json.desc))
``` ```
- To create a group - To create a group
``` javascript ``` javascript
client.groupCreate ("My Fab Group", ["abcd@s.whatsapp.net", "efgh@s.whatsapp.net"]) // title & participants client.groupCreate ("My Fab Group", ["abcd@s.whatsapp.net", "efgh@s.whatsapp.net"]) // title & participants
.then (([json, _]) => { .then (([json, _]) => {
@@ -229,36 +288,37 @@
client.sendTextMessage(json.gid, "hello everyone") // say hello to everyone on the group client.sendTextMessage(json.gid, "hello everyone") // say hello to everyone on the group
}) })
``` ```
- To add people to a group - To add people to a group
``` javascript ``` javascript
client.groupAdd ("abcd-xyz@g.us", ["abcd@s.whatsapp.net", "efgh@s.whatsapp.net"]) // id & people to add to the group client.groupAdd ("abcd-xyz@g.us", ["abcd@s.whatsapp.net", "efgh@s.whatsapp.net"]) // id & people to add to the group
.then (([json, _]) => console.log("added successfully: " + (json.status===200))) .then (([json, _]) => console.log("added successfully: " + (json.status===200)))
``` ```
- To make someone admin on a group - To make someone admin on a group
``` javascript ``` javascript
client.groupMakeAdmin ("abcd-xyz@g.us", ["abcd@s.whatsapp.net", "efgh@s.whatsapp.net"]) // id & people to make admin client.groupMakeAdmin ("abcd-xyz@g.us", ["abcd@s.whatsapp.net", "efgh@s.whatsapp.net"]) // id & people to make admin
.then (([json, _]) => console.log("made admin successfully: " + (json.status===200))) .then (([json, _]) => console.log("made admin successfully: " + (json.status===200)))
``` ```
- To leave a group - To leave a group
``` javascript ``` javascript
client.groupLeave ("abcd-xyz@g.us") client.groupLeave ("abcd-xyz@g.us")
.then (([json, _]) => console.log("left group successfully: " + (json.status===200))) .then (([json, _]) => console.log("left group successfully: " + (json.status===200)))
``` ```
- To get the invite code for a group - To get the invite code for a group
``` javascript ``` javascript
client.groupInviteCode ("abcd-xyz@g.us") client.groupInviteCode ("abcd-xyz@g.us")
.then (code => console.log(code)) .then (code => console.log(code))
``` ```
## Writing Custom Functionality ## Writing Custom Functionality
Baileys is also written, keeping in mind, that you may require other functionality. Hence, instead of having to fork the project & re-write the internals, you can simply write extensions in your own code. Baileys is written, keeping in mind, that you may require other custom functionality. Hence, instead of having to fork the project & re-write the internals, you can simply write extensions in your own code.
First, enable the logging of unhandled messages from WhatsApp by setting First, enable the logging of unhandled messages from WhatsApp by setting
``` javascript ``` javascript
client.logUnhandledMessages = true client.logUnhandledMessages = true
``` ```
This will enable you to see all sorts of messages WhatsApp sends in the console. Some examples: This will enable you to see all sorts of messages WhatsApp sends in the console. Some examples:
1. Functionality to track of the battery percentage of your phone. 1. Functionality to track of the battery percentage of your phone.
You enable logging and you'll see a message about your battery pop up in the console: You enable logging and you'll see a message about your battery pop up in the console:
``` [Baileys] [Unhandled] s22, ["action",null,[["battery",{"live":"false","value":"52"},null]]] ``` ``` [Baileys] [Unhandled] s22, ["action",null,[["battery",{"live":"false","value":"52"},null]]] ```
@@ -278,7 +338,7 @@
``` ```
This callback will be fired any time a message is received matching the following criteria: This callback will be fired any time a message is received matching the following criteria:
``` message [0] === "action" && message [1] === null && message[2][0][0] === "battery" ``` ``` message [0] === "action" && message [1] === null && message[2][0][0] === "battery" ```
2. Functionality to keep track of the pushname changes on your phone. 2. Functionality to keep track of the pushname changes on your phone.
You enable logging and you'll see an unhandled message about your pushanme pop up like this: You enable logging and you'll see an unhandled message about your pushanme pop up like this:
```[Baileys] [Unhandled] s24, ["Conn",{"pushname":"adiwajshing"}]``` ```[Baileys] [Unhandled] s24, ["Conn",{"pushname":"adiwajshing"}]```
@@ -299,14 +359,14 @@
This callback will be fired any time a message is received matching the following criteria: This callback will be fired any time a message is received matching the following criteria:
``` message [0] === "Conn" && message [1].pushname ``` ``` message [0] === "Conn" && message [1].pushname ```
A little more testing will reveal that almost all WhatsApp messages are in the format illustrated above. A little more testing will reveal that almost all WhatsApp messages are in the format illustrated above.
Note: except for the first parameter (in the above cases, ```"action"``` or ```"Conn"```), all the other parameters are optional. Note: except for the first parameter (in the above cases, ```"action"``` or ```"Conn"```), all the other parameters are optional.
## Example ## Example
Do check out & run [example.js](example/example.js) to see example usage of these functions. Do check out & run [example.js](example/example.js) to see example usage of these functions.
To run the example script, download or clone the repo and then type the following in terminal: To run the example script, download or clone the repo and then type the following in terminal:
1. ``` cd path/to/Baileys/example ``` 1. ``` cd path/to/Baileys/example ```
2. ``` node example.js ``` 2. ``` node example.js ```
### Note ### Note
I am in no way affiliated with WhatsApp. This was written for educational purposes. Use at your own discretion. I am in no way affiliated with WhatsApp. This was written for educational purposes. Use at your own discretion.