该库最初是阿育王大学 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,允许 Baileys 通过使用手机上的 WhatsApp 扫描二维码来作为第二个 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或imageMessage或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