이 라이브러리는 원래 Ashoka University의 CS-2362 프로젝트였으며 WhatsApp과 제휴하거나 보증하지 않습니다. 귀하의 재량에 따라 사용하십시오. 이것으로 사람들에게 스팸을 보내지 마십시오. 스토커웨어, 대량 또는 자동 메시징 사용을 권장하지 않습니다.
Baileys와 그 유지관리자는 MIT 라이선스에 명시된 대로 이 애플리케이션의 오용에 대해 책임을 지지 않습니다. Baileys의 관리자는 WhatsApp의 서비스 약관을 위반하는 관행에 이 애플리케이션을 사용하는 것을 어떤 식으로든 용납하지 않습니다. 이 애플리케이션의 관리자는 이 애플리케이션이 원래 의도된 대로 공정한 방식으로 사용하도록 사용자에게 개인적인 책임을 묻습니다.
Baileys는 WhatsApp Web과 인터페이스하기 위해 Selenium이나 다른 브라우저를 요구하지 않으며 WebSocket을 사용하여 직접 인터페이스합니다. Selenium 또는 Chromimum을 실행하지 않으면 RAM을 절반 정도 절약할 수 있습니다. Baileys는 WhatsApp의 다중 장치 및 웹 버전과의 상호 작용을 지원합니다. WhatsApp Multi-Device의 작동에 대한 관찰 내용을 작성해 주신 @pokearaujo에게 감사드립니다. 또한 WhatsApp Web의 작동에 대한 관찰 내용을 작성해 주신 @Sigalor에게 감사드리며, go 구현을 도와주신 @Rhymen에게도 감사드립니다.
원래 저장소는 원래 작성자에 의해 제거되어야 했습니다. 이제 여기에서 이 저장소에서 개발을 계속합니다. 이것은 유일한 공식 저장소이며 커뮤니티에서 관리합니다. 여기에서 디스코드에 참여하세요
라이브러리의 예제 사용법을 보려면 example.ts를 확인하고 실행하세요. 이 스크립트는 가장 일반적인 사용 사례를 다룹니다. 예제 스크립트를 실행하려면 저장소를 다운로드하거나 복제한 후 터미널에 다음을 입력하세요.
cd path/to/Baileys
yarn
yarn example
안정적인 버전을 사용하세요.
yarn add @whiskeysockets/baileys
Edge 버전 사용(안정성은 보장되지 않지만 최신 수정 사항 + 기능)
yarn add github:WhiskeySockets/Baileys
그런 다음 다음을 사용하여 코드를 가져옵니다.
import makeWASocket from '@whiskeysockets/baileys'
TODO
WhatsApp은 휴대폰에서 WhatsApp으로 QR 코드를 스캔하여 Baileys를 두 번째 WhatsApp 클라이언트로 인증할 수 있는 다중 장치 API를 제공합니다.
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 ( )
연결에 성공하면 터미널 화면에 QR 코드가 인쇄되어 휴대폰의 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
} )
연결하려고 할 때마다 QR 코드를 계속 스캔하고 싶지는 않을 것입니다.
따라서 자격 증명을 로드하여 다시 로그인할 수 있습니다.
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
와 같은 몇 가지 간단한 기능을 제공합니다.
참고: 누군가의 전체 채팅 기록을 메모리에 저장하는 것은 RAM을 엄청나게 낭비하기 때문에 특히 MD 연결을 위해 자신만의 데이터 저장소를 구축하는 것이 좋습니다.
단일 기능으로 모든 유형의 메시지를 보냅니다.
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 )
yarn add link-preview-js
link-preview-js
사용하여 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 } )
메시지 본문은 ExtendedTextMessage, imageMessage, videoMessage 또는 voiceMessage일 수 있습니다.
메시지 옵션에 backgroundColor 및 기타 옵션을 추가할 수 있습니다.
방송: 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
- 이 프레임의 내용(예: 메시지에는 "message"가 포함됨)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 ) => { } )
또한 이 저장소는 libsignal-node를 사용하므로 이제 GPL 3에 따라 라이센스가 부여됩니다.