Overview
makeWASocket is the primary function used to create a WhatsApp Web socket connection. It accepts a configuration object and returns a socket instance with all methods for interacting with the WhatsApp Web API.
Function Signature
const makeWASocket = (config: UserFacingSocketConfig) => WASocket
Parameters
Configuration object for the socket connection. This is a combination of
Partial<SocketConfig> with a required auth property.Show UserFacingSocketConfig properties
Show UserFacingSocketConfig properties
Authentication state object to maintain the auth state. Use
useMultiFileAuthState() to create this.WhatsApp Web version to connect with. Array of three numbers
[major, minor, patch].Browser description as a tuple
[OS, Browser, Version]. Use the Browsers constant for predefined configurations.The WebSocket URL to connect to WhatsApp.
Timeout in milliseconds for the connection. Fails the connection if the socket times out.
Default timeout for queries in milliseconds. Set to
undefined for no timeout.Ping-pong interval for WebSocket connection in milliseconds.
Logger instance for debugging and logging.
HTTPS proxy agent for the WebSocket connection.
Agent used for fetch requests when uploading/downloading media.
Whether events should be emitted for actions done by this socket connection.
Custom upload hosts to upload media to.
Time to wait between sending new retry requests in milliseconds.
Maximum retry count for failed messages.
Time to wait for the generation of the next QR code in milliseconds.
Function to manage history processing. Default syncs everything except FULL sync type.
Transaction capability options for SignalKeyStore.
Marks the client as online whenever the socket successfully connects.
Alphanumeric country code (e.g., USA -> US) for the number used.
Cache to store media, so it doesn’t have to be re-uploaded.
Map to store retry counts for failed messages; used to determine whether to retry a message.
Cache to store a user’s device list.
Cache to store call offers.
Cache to track placeholder resends.
Width for link preview images in pixels.
Whether Baileys should ask the phone for full history (received async).
Whether Baileys should fire init queries automatically.
Generate high quality link preview by uploading the jpegThumbnail to WhatsApp.
Enable automatic session recreation for failed messages.
Enable recent message caching for retry handling.
Function that returns if a JID should be ignored. No event for that JID will be triggered and messages from that JID will not be decrypted.
Optionally patch the message before sending out.
(msg: proto.IMessage, recipientJids?: string[]) =>
Promise<PatchedMessageWithRecipientJID[] | PatchedMessageWithRecipientJID> |
PatchedMessageWithRecipientJID[] | PatchedMessageWithRecipientJID
Options for HTTP fetch requests.
getMessage
(key: WAMessageKey) => Promise<proto.IMessage | undefined>
default:"async () => undefined"
Fetch a message from your store. Implement this so that messages that failed to send can be retried. Solves the “this message can take a while” issue.
cachedGroupMetadata
(jid: string) => Promise<GroupMetadata | undefined>
default:"async () => undefined"
Cached group metadata function to prevent redundant requests to WhatsApp and speed up message sending.
Function to create signal repository.
(auth: SignalAuthState, logger: ILogger,
pnToLIDFunc?: (jids: string[]) => Promise<LIDMapping[] | undefined>) =>
SignalRepositoryWithLIDStore
Return Value
Returns a socket instance with all methods for interacting with the WhatsApp Web API, including:
- Message sending and receiving
- Group management
- Contact management
- Media handling
- Event listeners
- And more
Basic Example
import makeWASocket, { useMultiFileAuthState } from '@whiskeysockets/baileys'
const { state, saveCreds } = await useMultiFileAuthState('auth_info_baileys')
const sock = makeWASocket({
auth: state,
printQRInTerminal: true
})
// Listen for connection updates
sock.ev.on('connection.update', (update) => {
const { connection, lastDisconnect } = update
if(connection === 'close') {
console.log('Connection closed')
} else if(connection === 'open') {
console.log('Connection opened')
}
})
// Save credentials when updated
sock.ev.on('creds.update', saveCreds)
Advanced Example with Caching
import makeWASocket, {
useMultiFileAuthState,
makeCacheableSignalKeyStore,
fetchLatestBaileysVersion
} from '@whiskeysockets/baileys'
import NodeCache from '@cacheable/node-cache'
import P from 'pino'
const logger = P({ level: 'trace' })
const msgRetryCounterCache = new NodeCache()
const { state, saveCreds } = await useMultiFileAuthState('baileys_auth_info')
const { version } = await fetchLatestBaileysVersion()
const sock = makeWASocket({
version,
logger,
auth: {
creds: state.creds,
keys: makeCacheableSignalKeyStore(state.keys, logger),
},
msgRetryCounterCache,
generateHighQualityLinkPreview: true,
getMessage: async (key) => {
// Implement message retrieval from your store
return undefined
}
})
sock.ev.on('creds.update', saveCreds)
Pairing Code Example
import makeWASocket, { useMultiFileAuthState } from '@whiskeysockets/baileys'
const { state, saveCreds } = await useMultiFileAuthState('auth_info')
const sock = makeWASocket({
auth: state,
printQRInTerminal: false // Must be false for pairing code
})
if (!sock.authState.creds.registered) {
const phoneNumber = '1234567890' // Without + or () or -
const code = await sock.requestPairingCode(phoneNumber)
console.log(`Pairing code: ${code}`)
}
sock.ev.on('creds.update', saveCreds)
Implementation Details
ThemakeWASocket function internally:
- Merges the provided config with
DEFAULT_CONNECTION_CONFIG - Creates a socket through the
makeCommunitiesSocketlayer - Returns the fully configured socket instance
const makeWASocket = (config: UserFacingSocketConfig) => {
const newConfig = {
...DEFAULT_CONNECTION_CONFIG,
...config
}
return makeCommunitiesSocket(newConfig)
}
See Also
- SocketConfig - Complete socket configuration reference
- Browsers - Browser configuration options
- Events - Available socket events