該庫最初是阿育王大學 CS-2362的一個項目,與 WhatsApp 沒有任何關聯或認可。請自行決定使用。不要以此向人們發送垃圾郵件。我們不鼓勵使用任何追蹤軟體、大量或自動訊息。
正如 MIT 許可證中所述,Baileys 及其維護者不對濫用此應用程式承擔責任。 Baileys 的維護者不會以任何方式縱容使用此應用程式進行違反 WhatsApp 服務條款的行為。該應用程式的維護者呼籲其用戶承擔個人責任,以公平的方式使用該應用程序,因為它的用途是這樣的。
Baileys 不需要 Selenium 或任何其他瀏覽器與 WhatsApp Web 交互,它直接使用WebSocket來實現。不運行 Selenium 或 Chromimum 可以為您節省半個記憶體:/Baileys 支援與 WhatsApp 的多裝置和 Web 版本互動。感謝 @pokearaujo 寫下他對 WhatsApp 多裝置運作的觀察。另外,感謝 @Sigalor 撰寫了他對 WhatsApp Web 運作的觀察,並感謝 @Rhymen 的go實作。
原始儲存庫必須由原作者刪除 - 我們現在在此繼續在此儲存庫中進行開發。這是唯一的官方儲存庫,由社群維護。在這裡加入不和諧
請檢查並執行 example.ts 以查看該庫的範例用法。該腳本涵蓋了最常見的用例。若要執行範例腳本,請下載或複製儲存庫,然後在終端機中鍵入以下內容:
cd path/to/Baileys
yarn
yarn example
使用穩定版本:
yarn add @whiskeysockets/baileys
使用邊緣版本(不保證穩定性,但最新修復+功能)
yarn add github:WhiskeySockets/Baileys
然後使用以下命令導入您的程式碼:
import makeWASocket from '@whiskeysockets/baileys'
待辦事項
WhatsApp 提供了一個多裝置 API,允許透過使用手機上的 WhatsApp 掃描二維碼來將 Baileys 驗證為第二個 WhatsApp 用戶端。
import makeWASocket , { DisconnectReason } from '@whiskeysockets/baileys'
import { Boom } from '@hapi/boom'
async function connectToWhatsApp ( ) {
const sock = makeWASocket ( {
// can provide additional config here
printQRInTerminal : true
} )
sock . ev . on ( 'connection.update' , ( update ) => {
const { connection , lastDisconnect } = update
if ( connection === 'close' ) {
const shouldReconnect = ( lastDisconnect . error as Boom ) ?. output ?. statusCode !== DisconnectReason . loggedOut
console . log ( 'connection closed due to ' , lastDisconnect . error , ', reconnecting ' , shouldReconnect )
// reconnect if not logged out
if ( shouldReconnect ) {
connectToWhatsApp ( )
}
} else if ( connection === 'open' ) {
console . log ( 'opened connection' )
}
} )
sock . ev . on ( 'messages.upsert' , m => {
console . log ( JSON . stringify ( m , undefined , 2 ) )
console . log ( 'replying to' , m . messages [ 0 ] . key . remoteJid )
await sock . sendMessage ( m . messages [ 0 ] . key . remoteJid ! , { text : 'Hello there!' } )
} )
}
// run in main file
connectToWhatsApp ( )
如果連接成功,您將在終端螢幕上看到一個二維碼,並用手機上的 WhatsApp 掃描它即可登入!
您可以透過傳遞SocketConfig
物件來配置連線。
這裡提到了整個SocketConfig
結構,並帶有預設值:
type SocketConfig = {
/** the WS url to connect to WA */
waWebSocketUrl : string | URL
/** Fails the connection if the socket times out in this interval */
connectTimeoutMs : number
/** Default timeout for queries, undefined for no timeout */
defaultQueryTimeoutMs : number | undefined
/** ping-pong interval for WS connection */
keepAliveIntervalMs : number
/** proxy agent */
agent ?: Agent
/** pino logger */
logger : Logger
/** version to connect with */
version : WAVersion
/** override browser config */
browser : WABrowserDescription
/** agent used for fetch requests -- uploading/downloading media */
fetchAgent ?: Agent
/** should the QR be printed in the terminal */
printQRInTerminal : boolean
/** should events be emitted for actions done by this socket connection */
emitOwnEvents : boolean
/** provide a cache to store media, so does not have to be re-uploaded */
mediaCache ?: NodeCache
/** custom upload hosts to upload media to */
customUploadHosts : MediaConnInfo [ 'hosts' ]
/** time to wait between sending new retry requests */
retryRequestDelayMs : number
/** max msg retry count */
maxMsgRetryCount : number
/** time to wait for the generation of the next QR in ms */
qrTimeout ?: number ;
/** provide an auth state object to maintain the auth state */
auth : AuthenticationState
/** manage history processing with this control; by default will sync up everything */
shouldSyncHistoryMessage : ( msg : proto . Message . IHistorySyncNotification ) => boolean
/** transaction capability options for SignalKeyStore */
transactionOpts : TransactionCapabilityOptions
/** provide a cache to store a user's device list */
userDevicesCache ?: NodeCache
/** marks the client as online whenever the socket successfully connects */
markOnlineOnConnect : boolean
/**
* map to store the retry counts for failed messages;
* used to determine whether to retry a message or not */
msgRetryCounterMap ?: MessageRetryMap
/** width for link preview images */
linkPreviewImageThumbnailWidth : number
/** Should Baileys ask the phone for full history, will be received async */
syncFullHistory : boolean
/** Should baileys fire init queries automatically, default true */
fireInitQueries : boolean
/**
* generate a high quality link preview,
* entails uploading the jpegThumbnail to WA
* */
generateHighQualityLinkPreview : boolean
/** options for axios */
options : AxiosRequestConfig < any >
/**
* fetch a message from your store
* implement this so that messages failed to send (solves the "this message can take a while" issue) can be retried
* */
getMessage : ( key : proto . IMessageKey ) => Promise < proto . IMessage | undefined >
}
const conn = makeWASocket ( {
... otherOpts ,
// can use Windows, Ubuntu here too
browser : Browsers . macOS ( 'Desktop' ) ,
syncFullHistory : true
} )
您顯然不想每次連線時都掃描二維碼。
因此,您可以載入憑證以重新登入:
import makeWASocket , { BufferJSON , useMultiFileAuthState } from '@whiskeysockets/baileys'
import * as fs from 'fs'
// utility function to help save the auth state in a single folder
// this function serves as a good guide to help write auth & key states for SQL/no-SQL databases, which I would recommend in any production grade system
const { state , saveCreds } = await useMultiFileAuthState ( 'auth_info_baileys' )
// will use the given state to connect
// so if valid credentials are available -- it'll connect without QR
const conn = makeWASocket ( { auth : state } )
// this will be called as soon as the credentials are updated
conn . ev . on ( 'creds.update' , saveCreds )
注意:當接收/傳送訊息時,由於訊號會話需要更新,因此身份驗證金鑰( authState.keys
)將會更新。無論何時發生這種情況,您都必須儲存更新的金鑰(呼叫authState.keys.set()
)。不這樣做會阻止您的郵件到達收件人並導致其他意外後果。 useMultiFileAuthState
函數會自動處理此問題,但對於任何其他認真的實作 - 您將需要非常小心金鑰狀態管理。
Baileys 現在會觸發connection.update
事件,讓您知道連線中的某些內容已更新。此資料具有以下結構:
type ConnectionState = {
/** connection is now open, connecting or closed */
connection : WAConnectionState
/** the error that caused the connection to close */
lastDisconnect ?: {
error : Error
date : Date
}
/** is this a new login */
isNewLogin ?: boolean
/** the current QR code */
qr ?: string
/** has the device received all pending notifications while it was offline */
receivedPendingNotifications ?: boolean
}
注意:這也提供了 QR 的任何更新
Baileys 對事件使用 EventEmitter 語法。它們的輸入都很好,因此您使用 VS Code 等 Intellisense 編輯器應該不會有任何問題。
事件的類型如下所述:
export type BaileysEventMap = {
/** connection state has been updated -- WS closed, opened, connecting etc. */
'connection.update' : Partial < ConnectionState >
/** credentials updated -- some metadata, keys or something */
'creds.update' : Partial < AuthenticationCreds >
/** history sync, everything is reverse chronologically sorted */
'messaging-history.set' : {
chats : Chat [ ]
contacts : Contact [ ]
messages : WAMessage [ ]
isLatest : boolean
}
/** upsert chats */
'chats.upsert' : Chat [ ]
/** update the given chats */
'chats.update' : Partial < Chat > [ ]
/** delete chats with given ID */
'chats.delete' : string [ ]
'labels.association' : LabelAssociation
'labels.edit' : Label
/** presence of contact in a chat updated */
'presence.update' : { id : string , presences : { [ participant : string ] : PresenceData } }
'contacts.upsert' : Contact [ ]
'contacts.update' : Partial < Contact > [ ]
'messages.delete' : { keys : WAMessageKey [ ] } | { jid : string , all : true }
'messages.update' : WAMessageUpdate [ ]
'messages.media-update' : { key : WAMessageKey , media ?: { ciphertext : Uint8Array , iv : Uint8Array } , error ?: Boom } [ ]
/**
* add/update the given messages. If they were received while the connection was online,
* the update will have type: "notify"
* */
'messages.upsert' : { messages : WAMessage [ ] , type : MessageUpsertType }
/** message was reacted to. If reaction was removed -- then "reaction.text" will be falsey */
'messages.reaction' : { key : WAMessageKey , reaction : proto . IReaction } [ ]
'message-receipt.update' : MessageUserReceiptUpdate [ ]
'groups.upsert' : GroupMetadata [ ]
'groups.update' : Partial < GroupMetadata > [ ]
/** apply an action to participants in a group */
'group-participants.update' : { id : string , participants : string [ ] , action : ParticipantAction }
'blocklist.set' : { blocklist : string [ ] }
'blocklist.update' : { blocklist : string [ ] , type : 'add' | 'remove' }
/** Receive an update on a call, including when the call was received, rejected, accepted */
'call' : WACallEvent [ ]
}
您可以像這樣收聽這些事件:
const sock = makeWASocket ( )
sock . ev . on ( 'messages.upsert' , ( { messages } ) => {
console . log ( 'got messages' , messages )
} )
Baileys 並沒有提供用於聊天、聯絡人或訊息的事實上的儲存。然而,已經提供了一個簡單的記憶體中實作。商店監聽聊天更新、新訊息、訊息更新等,以始終擁有最新版本的資料。
它可以如下使用:
import makeWASocket , { makeInMemoryStore } from '@whiskeysockets/baileys'
// the store maintains the data of the WA connection in memory
// can be written out to a file & read from it
const store = makeInMemoryStore ( { } )
// can be read from a file
store . readFromFile ( './baileys_store.json' )
// saves the state to a file every 10s
setInterval ( ( ) => {
store . writeToFile ( './baileys_store.json' )
} , 10_000 )
const sock = makeWASocket ( { } )
// will listen from this socket
// the store can listen from a new socket once the current socket outlives its lifetime
store . bind ( sock . ev )
sock . ev . on ( 'chats.upsert' , ( ) => {
// can use "store.chats" however you want, even after the socket dies out
// "chats" => a KeyedDB instance
console . log ( 'got chats' , store . chats . all ( ) )
} )
sock . ev . on ( 'contacts.upsert' , ( ) => {
console . log ( 'got contacts' , Object . values ( store . contacts ) )
} )
該儲存空間還提供了一些簡單的功能,例如loadMessages
,利用該儲存空間來加速資料檢索。
注意:我強烈建議您建立自己的資料存儲,尤其是對於 MD 連接,因為將某人的整個聊天歷史記錄存儲在內存中會嚴重浪費 RAM。
使用單一函數發送所有類型的消息:
import { MessageType , MessageOptions , Mimetype } from '@whiskeysockets/baileys'
const id = '[email protected]' // the WhatsApp ID
// send a simple text!
const sentMsg = await sock . sendMessage ( id , { text : 'oh hello there' } )
// send a reply messagge
const sentMsg = await sock . sendMessage ( id , { text : 'oh hello there' } , { quoted : message } )
// send a mentions message
const sentMsg = await sock . sendMessage ( id , { text : '@12345678901' , mentions : [ '[email protected]' ] } )
// send a location!
const sentMsg = await sock . sendMessage (
id ,
{ location : { degreesLatitude : 24.121231 , degreesLongitude : 55.1121221 } }
)
// send a contact!
const vcard = 'BEGIN:VCARDn' // metadata of the contact card
+ 'VERSION:3.0n'
+ 'FN:Jeff Singhn' // full name
+ 'ORG:Ashoka Uni;n' // the organization of the contact
+ 'TEL;type=CELL;type=VOICE;waid=911234567890:+91 12345 67890n' // WhatsApp ID + phone number
+ 'END:VCARD'
const sentMsg = await sock . sendMessage (
id ,
{
contacts : {
displayName : 'Jeff' ,
contacts : [ { vcard } ]
}
}
)
const reactionMessage = {
react : {
text : "?" , // use an empty string to remove the reaction
key : message . key
}
}
const sendMsg = await sock . sendMessage ( id , reactionMessage )
link-preview-js
將yarn add link-preview-js
新增為專案的依賴項 // send a link
const sentMsg = await sock . sendMessage ( id , { text : 'Hi, this was sent using https://github.com/adiwajshing/baileys' } )
發送媒體(影片、貼紙、圖像)比以往更容易、更有效率。
import { MessageType , MessageOptions , Mimetype } from '@whiskeysockets/baileys'
// Sending gifs
await sock . sendMessage (
id ,
{
video : fs . readFileSync ( "Media/ma_gif.mp4" ) ,
caption : "hello!" ,
gifPlayback : true
}
)
await sock . sendMessage (
id ,
{
video : "./Media/ma_gif.mp4" ,
caption : "hello!" ,
gifPlayback : true ,
ptv : false // if set to true, will send as a `video note`
}
)
// send an audio file
await sock . sendMessage (
id ,
{ audio : { url : "./Media/audio.mp3" } , mimetype : 'audio/mp4' }
{ url : "Media/audio.mp3" } , // can send mp3, mp4, & ogg
)
id
是您要向其發送訊息的個人或群組的 WhatsApp ID。[country code][phone number]@s.whatsapp.net
[email protected]
。[email protected]
。[timestamp of creation]@broadcast
。status@broadcast
。yarn add jimp
或yarn add sharp
在專案中新增jimp
或sharp
作為依賴項,則可以自動產生影像和貼紙的縮圖。影片的縮圖也可以自動生成,但您需要在系統上安裝ffmpeg
。 const info : MessageOptions = {
quoted : quotedMessage , // the message you want to quote
contextInfo : { forwardingScore : 2 , isForwarded : true } , // some random context info (can show a forwarded message with this too)
timestamp : Date ( ) , // optional, if you want to manually set the timestamp of the message
caption : "hello there!" , // (for media messages) the caption to send with the media (cannot be sent with stickers though)
jpegThumbnail : "23GD#4/==" , /* (for location & media messages) has to be a base 64 encoded JPEG if you want to send a custom thumb,
or set to null if you don't want to send a thumbnail.
Do not enter this field if you want to automatically generate a thumb
*/
mimetype : Mimetype . pdf , /* (for media messages) specify the type of media (optional for all media types except documents),
import {Mimetype} from '@whiskeysockets/baileys'
*/
fileName : 'somefile.pdf' , // (for media messages) file name for the media
/* will send audio messages as voice notes, if set to true */
ptt : true ,
/** Should it send as a disappearing messages.
* By default 'chat' -- which follows the setting of the chat */
ephemeralExpiration : WA_DEFAULT_EPHEMERAL
}
const msg = getMessageFromStore ( '[email protected]' , 'HSJHJWH7323HSJSJ' ) // implement this on your end
await sock . sendMessage ( '[email protected]' , { forward : msg } ) // WA forward the message!
一組訊息鍵必須明確標記為「現在已讀」。在多設備中,您無法像使用 Baileys Web 那樣將整個「聊天」標記為已讀。這意味著您必須追蹤未讀訊息。
const key = {
remoteJid : '[email protected]' ,
id : 'AHASHH123123AHGA' , // id of the message you want to read
participant : '[email protected]' // the ID of the user that sent the message (undefined for individual chats)
}
// pass to readMessages function
// can pass multiple keys to read multiple messages as well
await sock . readMessages ( [ key ] )
訊息 ID 是您標記為已讀取的訊息的唯一識別碼。在WAMessage
上,可以使用messageID = message.key.id
存取messageID
。
await sock . sendPresenceUpdate ( 'available' , id )
這可以讓有id
的人/群組知道您是否在線上、離線、打字等。
presence
可以是以下其中之一:
type WAPresence = 'unavailable' | 'available' | 'composing' | 'recording' | 'paused'
大約 10 秒後,該狀態就會消失。
注意:在 WhatsApp 的多裝置版本中 - 如果桌面用戶端處於活動狀態,WA 不會向裝置發送推播通知。如果您想接收上述通知 - 使用sock.sendPresenceUpdate('unavailable')
將您的 Baileys 用戶端標記為離線
如果您想儲存收到的媒體
import { writeFile } from 'fs/promises'
import { downloadMediaMessage } from '@whiskeysockets/baileys'
sock . ev . on ( 'messages.upsert' , async ( { messages } ) => {
const m = messages [ 0 ]
if ( ! m . message ) return // if there is no text or media message
const messageType = Object . keys ( m . message ) [ 0 ] // get what type of message it is -- text, image, video
// if the message is an image
if ( messageType === 'imageMessage' ) {
// download the message
const buffer = await downloadMediaMessage (
m ,
'buffer' ,
{ } ,
{
logger ,
// pass this so that baileys can request a reupload of media
// that has been deleted
reuploadRequest : sock . updateMediaMessage
}
)
// save to file
await writeFile ( './my-download.jpeg' , buffer )
}
}
注意: WhatsApp 會自動從其伺服器中刪除舊媒體。對於要存取所述媒體的裝置-擁有該媒體的另一個裝置需要重新上傳。這可以使用以下方法來完成:
const updatedMediaMsg = await sock . updateMediaMessage ( msg )
const jid = '[email protected]' // can also be a group
const response = await sock . sendMessage ( jid , { text : 'hello!' } ) // send a message
// sends a message to delete the given message
// this deletes the message for everyone
await sock . sendMessage ( jid , { delete : response . key } )
注意:透過chatModify
支援自行刪除(下一節)
const jid = '[email protected]'
await sock . sendMessage ( jid , {
text : 'updated text goes here' ,
edit : response . key ,
} ) ;
WA 使用加密的通訊形式發送聊天/應用程式更新。這已大部分實施,您可以發送以下更新:
存檔聊天記錄
const lastMsgInChat = await getLastMessageInChat ( '[email protected]' ) // implement this on your end
await sock . chatModify ( { archive : true , lastMessages : [ lastMsgInChat ] } , '[email protected]' )
靜音/取消靜音聊天
// mute for 8 hours
await sock . chatModify ( { mute : 8 * 60 * 60 * 1000 } , '[email protected]' , [ ] )
// unmute
await sock . chatModify ( { mute : null } , '[email protected]' , [ ] )
將聊天標記為已讀/未讀
const lastMsgInChat = await getLastMessageInChat ( '[email protected]' ) // implement this on your end
// mark it unread
await sock . chatModify ( { markRead : false , lastMessages : [ lastMsgInChat ] } , '[email protected]' )
為我刪除一條訊息
await sock . chatModify (
{ clear : { messages : [ { id : 'ATWYHDNNWU81732J' , fromMe : true , timestamp : "1654823909" } ] } } ,
'[email protected]' ,
[ ]
)
刪除聊天記錄
const lastMsgInChat = await getLastMessageInChat ( '[email protected]' ) // implement this on your end
await sock . chatModify ( {
delete : true ,
lastMessages : [ { key : lastMsgInChat . key , messageTimestamp : lastMsgInChat . messageTimestamp } ]
} ,
'[email protected]' )
固定/取消固定聊天
await sock . chatModify ( {
pin : true // or `false` to unpin
} ,
'[email protected]' )
給訊息加星號/取消星標
await sock . chatModify ( {
star : {
messages : [ { id : 'messageID' , fromMe : true // or `false` }],
star : true // - true: Star Message; false: Unstar Message
} } , '[email protected]' ) ;
注意:如果您搞砸了其中一項更新,WA 可以將您從所有裝置中登出,並且您必須重新登入。
const jid = '[email protected]' // can also be a group
// turn on disappearing messages
await sock . sendMessage (
jid ,
// this is 1 week in seconds -- how long you want messages to appear for
{ disappearingMessagesInChat : WA_DEFAULT_EPHEMERAL }
)
// will send as a disappearing message
await sock . sendMessage ( jid , { text : 'hello' } , { ephemeralExpiration : WA_DEFAULT_EPHEMERAL } )
// turn off disappearing messages
await sock . sendMessage (
jid ,
{ disappearingMessagesInChat : false }
)
const id = '123456'
const [ result ] = await sock . onWhatsApp ( id )
if ( result . exists ) console . log ( ` ${ id } exists on WhatsApp, as jid: ${ result . jid } ` )
const status = await sock . fetchStatus ( "[email protected]" )
console . log ( "status: " + status )
const status = 'Hello World!'
await sock . updateProfileStatus ( status )
const name = 'My name'
await sock . updateProfileName ( name )
// for low res picture
const ppUrl = await sock . profilePictureUrl ( "[email protected]" )
console . log ( "download profile picture from: " + ppUrl )
// for high res picture
const ppUrl = await sock . profilePictureUrl ( "[email protected]" , 'image' )
const jid = '[email protected]' // can be your own too
await sock . updateProfilePicture ( jid , { url : './new-profile-picture.jpeg' } )
const jid = '[email protected]' // can be your own too
await sock . removeProfilePicture ( jid )
// the presence update is fetched and called here
sock . ev . on ( 'presence.update' , json => console . log ( json ) )
// request updates for a chat
await sock . presenceSubscribe ( "[email protected]" )
await sock . updateBlockStatus ( "[email protected]" , "block" ) // Block user
await sock . updateBlockStatus ( "[email protected]" , "unblock" ) // Unblock user
const profile = await sock . getBusinessProfile ( "[email protected]" )
console . log ( "business description: " + profile . description + ", category: " + profile . category )
當然,將xyz
替換為實際 ID。
建立群組
// title & participants
const group = await sock . groupCreate ( "My Fab Group" , [ "[email protected]" , "[email protected]" ] )
console . log ( "created group with id: " + group . gid )
sock . sendMessage ( group . id , { text : 'hello there' } ) // say hello to everyone on the group
將人員加入群組/從群組中刪除或將人員降級/晉升
// id & people to add to the group (will throw error if it fails)
const response = await sock . groupParticipantsUpdate (
"[email protected]" ,
[ "[email protected]" , "[email protected]" ] ,
"add" // replace this parameter with "remove", "demote" or "promote"
)
更改群組主題
await sock . groupUpdateSubject ( "[email protected]" , "New Subject!" )
更改組的描述
await sock . groupUpdateDescription ( "[email protected]" , "New Description!" )
更改組設定
// only allow admins to send messages
await sock . groupSettingUpdate ( "[email protected]" , 'announcement' )
// allow everyone to send messages
await sock . groupSettingUpdate ( "[email protected]" , 'not_announcement' )
// allow everyone to modify the group's settings -- like display picture etc.
await sock . groupSettingUpdate ( "[email protected]" , 'unlocked' )
// only allow admins to modify the group's settings
await sock . groupSettingUpdate ( "[email protected]" , 'locked' )
離開群組
await sock . groupLeave ( "[email protected]" ) // (will throw error if it fails)
取得群組的邀請碼
const code = await sock . groupInviteCode ( "[email protected]" )
console . log ( "group code: " + code )
撤銷群組邀請碼
const code = await sock . groupRevokeInvite ( "[email protected]" )
console . log ( "New group code: " + code )
查詢群組的元數據
const metadata = await sock . groupMetadata ( "[email protected]" )
console . log ( metadata . id + ", title: " + metadata . subject + ", description: " + metadata . desc )
使用邀請碼加入群組
const response = await sock . groupAcceptInvite ( "xxx" )
console . log ( "joined to: " + response )
當然,將xxx
替換為邀請碼。
透過邀請碼獲取群組訊息
const response = await sock . groupGetInviteInfo ( "xxx" )
console . log ( "group information: " + response )
使用 groupInviteMessage 加入群組
const response = await sock . groupAcceptInviteV4 ( "[email protected]" , groupInviteMessage )
console . log ( "joined to: " + response )
當然,將xxx
替換為邀請碼。
取得清單請求加入
const response = await sock . groupRequestParticipantsList ( "[email protected]" )
console . log ( response )
批准/拒絕加入請求
const response = await sock . groupRequestParticipantsUpdate (
"[email protected]" , // id group,
[ "[email protected]" , "[email protected]" ] ,
"approve" // replace this parameter with "reject"
)
console . log ( response )
const privacySettings = await sock . fetchPrivacySettings ( true )
console . log ( "privacy settings: " + privacySettings )
const value = 'all' // 'contacts' | 'contact_blacklist' | 'none'
await sock . updateLastSeenPrivacy ( value )
const value = 'all' // 'match_last_seen'
await sock . updateOnlinePrivacy ( value )
const value = 'all' // 'contacts' | 'contact_blacklist' | 'none'
await sock . updateProfilePicturePrivacy ( value )
const value = 'all' // 'contacts' | 'contact_blacklist' | 'none'
await sock . updateStatusPrivacy ( value )
const value = 'all' // 'none'
await sock . updateReadReceiptsPrivacy ( value )
const value = 'all' // 'contacts' | 'contact_blacklist'
await sock . updateGroupsAddPrivacy ( value )
const duration = 86400 // 604800 | 7776000 | 0
await sock . updateDefaultDisappearingMode ( duration )
訊息可以發送到廣播和故事。您需要在 sendMessage 中新增以下訊息選項,如下所示:
sock . sendMessage ( jid , { image : { url : url } , caption : caption } , { backgroundColor : backgroundColor , font : font , statusJidList : statusJidList , broadcast : true } )
訊息正文可以是擴充的TextMessage或imageMesage或videoMessage或voiceMessage
您可以在訊息選項中新增背景顏色和其他選項
Broadcast: true 啟用廣播模式
statusJidList:您需要提供的可以取得的人員列表,哪些人將收到此狀態訊息。
您可以像向群組和個人聊天發送訊息一樣向廣播清單發送訊息。
目前,WA Web 不支援建立廣播列表,但您仍然可以刪除它們。
廣播 ID 的格式為12345678@broadcast
查詢廣播清單的收件者和姓名:
const bList = await sock . getBroadcastListInfo ( "1234@broadcast" )
console . log ( `list name: ${ bList . name } , recps: ${ bList . recipients } ` )
Baileys 在編寫時考慮到了自訂功能。您可以簡單地編寫自己的擴展,而不是分叉項目並重寫內部結構。
首先,透過設定啟用記錄來自 WhatsApp 的未處理訊息:
const sock = makeWASocket ( {
logger : P ( { level : 'debug' } ) ,
} )
這將使您能夠在控制台中查看 WhatsApp 發送的各種訊息。
一些例子:
追蹤手機電池百分比的功能。啟用日誌記錄後,您將在控制台中看到一條有關電池彈出的訊息: {"level":10,"fromMe":false,"frame":{"tag":"ib","attrs":{"from":"@s.whatsapp.net"},"content":[{"tag":"edge_routing","attrs":{},"content":[{"tag":"routing_info","attrs":{},"content":{"type":"Buffer","data":[8,2,8,5]}}]}]},"msg":"communication"}
「幀」是接收到的訊息,它有三個組成部分:
tag
-這個框架是關於什麼的(例如,訊息將有「訊息」)attrs
-- 帶有一些元資料的字串鍵值對(通常包含訊息的 ID)content
-- 實際資料(例如,訊息節點將包含實際的訊息內容)您可以使用以下命令註冊事件的回調:
// for any message with tag 'edge_routing'
sock . ws . on ( `CB:edge_routing` , ( node : BinaryNode ) => { } )
// for any message with tag 'edge_routing' and id attribute = abcd
sock . ws . on ( `CB:edge_routing,id:abcd` , ( node : BinaryNode ) => { } )
// for any message with tag 'edge_routing', id attribute = abcd & first content node routing_info
sock . ws . on ( `CB:edge_routing,id:abcd,routing_info` , ( node : BinaryNode ) => { } )
此外,該儲存庫現在已獲得 GPL 3 許可,因為它使用 libsignal-node