Skip to Content
API Reference

API Reference

A grouped, quick-lookup index of every public export from the zaileys package. Everything below is re-exported from the package root, so a single import works for any symbol:

import { Client, MessageBuilder, SqliteAuthStore, SqliteMessageStore } from 'zaileys'

This page is a terse exports index. For full prose, options tables, and end-to-end examples follow the deep-links to the relevant guide page on each entry.

Client

The main entry point. See Client & Lifecycle and Configuration.

import { Client, MemoryAuthStore, MemoryMessageStore } from 'zaileys' const client = new Client({ sessionId: 'main', auth: new MemoryAuthStore(), store: new MemoryMessageStore(), authType: 'qr', qrTerminal: true, }) client.on('connection', (s) => console.log(s.status)) client.on('message', (msg) => { if (msg.text() === 'ping') client.send(msg.chatId()).text('pong') })
MemberSignatureDescription
new Client(opts?)(options?: ClientOptions)Construct a client; auto-connects unless autoConnect: false.
connect()(): Promise<void>Open the WhatsApp connection (QR or pairing).
disconnect()(): Promise<void>Close the socket without clearing auth.
logout()(): Promise<void>Log out and clear stored credentials.
get stateConnectionStateCurrent state (idle | connecting | connected | disconnected).
get socketBaileysSocket | undefinedUnderlying socket (escape hatch).
send(to)(to: string): MessageBuilder<'init'>Start a fluent message builder for a JID. See Sending Messages.
edit(key)(key: WAMessageKey): EditBuilderEdit a previously sent message.
delete(key, opts?)(key, opts?: DeleteOptions): Promise<void>Delete a message.
react(key, emoji)(key, emoji: string): Promise<WAMessageKey>React to a message.
forward(key, to)(key, to: string): Promise<WAMessageKey>Forward a message to a JID.
broadcast(jids, build, opts?)(jids: string[], build, opts?): Promise<BroadcastResult>Send to many recipients. See Broadcast & Schedule.
scheduleAt(date, build, opts?)(date: Date, build, opts?): Promise<ScheduleHandle>Schedule a message for later.
command(spec, handler)(spec: string, handler: CommandHandler): thisRegister a command. See Commands.
use(middleware)(middleware: Middleware): thisAdd command middleware.
get groupGroupModuleGroup management.
get privacyPrivacyModulePrivacy & blocking.
get newsletterNewsletterModuleNewsletter/channel management.
get communityCommunityModuleCommunity management.
get presencePresenceModulePresence updates.
on/once/off/emitinherited from TypedEventEmitterTyped event subscription. See Events.

Related client exports: TypedEventEmitter, TypedEventEmitterOptions.

Configuration Types

Types backing the Client constructor. See Configuration.

ExportKindDescription
ClientOptionsinterfaceAll constructor options (sessionId, auth, store, authType, phoneNumber, logger, cacheSignal, reconnect, qrTerminal, baileys, autoConnect, statusLog, commandPrefix, citation, ignoreMe).
ConnectionStatetypeidle | connecting | connected | disconnected (and reconnecting states).
ConnectionAuthTypetype'qr' | 'pairing'.
ReconnectOptionsinterfaceReconnect backoff configuration.
LoggerinterfacePluggable logger contract.
ClientEventMap / ClientEventNametypeFull event map (connection + inbound).
ConnectionEventMap / ConnectionEventName / ConnectionEventHandlertypeConnection-only event types.
BaileysSockettypeAlias for the underlying WASocket.

Auth Stores

Credential persistence. Pass an instance to Client’s auth option. See Storage Adapters.

import { Client, SqliteAuthStore } from 'zaileys' const client = new Client({ sessionId: 'main', auth: new SqliteAuthStore({ path: './session.db' }), })
ExportKindDescription
MemoryAuthStoreclassIn-memory creds (non-persistent).
FileAuthStoreclassFile-based store. Options: FileAuthStoreOptions.
SqliteAuthStoreclassSQLite-backed. Options: SqliteAuthStoreOptions.
PostgresAuthStoreclassPostgres-backed. Options: PostgresAuthStoreOptions.
RedisAuthStoreclassRedis-backed. Options: RedisAuthStoreOptions.
ConvexAuthStoreclassConvex-backed. Options: ConvexAuthStoreOptions.
makeCacheableAuthStore(...)functionWrap a store with an in-memory cache. Options: CacheableAuthStoreOptions.
AuthStoreBundleinterface{ creds: AuthCredsStore; signal: AuthStore } — the contract all adapters implement.
AuthStore / AuthCredsStoreinterfaceSignal-key and credential sub-stores.
AuthStoreKey / AuthStoreValuetypeSignal data key/value types.

Message Stores

Chat/message/contact/presence persistence. Pass to Client’s store option. See Storage Adapters.

ExportKindDescription
MemoryMessageStoreclassIn-memory message store.
SqliteMessageStoreclassSQLite-backed. Options: SqliteMessageStoreOptions.
PostgresMessageStoreclassPostgres-backed. Options: PostgresMessageStoreOptions.
RedisMessageStoreclassRedis-backed. Options: RedisMessageStoreOptions.
ConvexMessageStoreclassConvex-backed. Options: ConvexMessageStoreOptions.
MessageStoreinterfaceStore contract: saveMessage, getMessage, listMessages, saveChat, getChat, listChats, saveContact, getContact, listContacts, savePresence, getPresence, bind, clear, close, optional saveScheduledJob/listScheduledJobs/deleteScheduledJob.
MessageStoreListOptionstypePagination/filter options for listMessages.
ScheduledJobRecordtypePersisted scheduled-job row.
BaileysSocketLikeinterfaceMinimal socket shape consumed by MessageStore.bind.

Builder (Sending Messages)

Fluent message construction. See Sending Messages, Interactive Messages, Rich Responses.

client .send('628xxx@s.whatsapp.net') .text('Hello *world*') .reply(msg.message().key)

MessageBuilder<State>

MethodSignatureDescription
to(recipient)(recipient: string): MessageBuilder<'init'>Set recipient JID.
text(content, opts?)(content: string, opts?: TextOptions): MessageBuilder<'content-set'>Text message (opts.rich enables AIRich).
image(src, opts?)(src: MediaSource, opts?: ImageOptions)Image.
video(src, opts?)(src: MediaSource, opts?: VideoOptions)Video.
audio(src, opts?)(src: MediaSource, opts?: AudioOptions)Audio / voice note.
document(src, opts)(src: MediaSource, opts: DocumentOptions)Document.
sticker(src, opts?)(src: MediaSource, opts?: StickerOptions)Sticker.
buttons(...)interactive button messageSee Interactive.
carousel(...)carousel/cardsSee Interactive.
list(opts)(opts: ListOptions)List message.
poll(...)poll message (PollOptions)See Interactive.
location(...)location (LocationOptions)Share location.
contact(vcard)(vcard: string)Share a contact.
template(opts)(opts: TemplateOptions)Template message.
album(items)(items: AlbumItem[])Media album.
reply(quoted)(quoted: WAMessage | WAMessageKey)Quote a message.
mentions(jids)(jids: string[])Mention specific JIDs.
mentionAll()()Mention all group members.
disappearing(seconds)(seconds: number)Set disappearing timer.
then(...)thenableAwaiting the builder sends the message and resolves to a WAMessageKey.
sendMessage(...)low-level sendInternal/escape-hatch send.

EditBuilder

MethodSignatureDescription
text(content)(content: string): thisReplace text.
image(src, opts?)(src: MediaSource, opts?: ImageOptions): thisReplace with image.
video(src, opts?)(src: MediaSource, opts?: VideoOptions): thisReplace with video.

Builder mutations & helpers

ExportKindDescription
deleteMessage(...)functionDelete a message. Options: DeleteOptions.
reactToMessage(...)functionReact to a message.
forwardMessage(...)functionForward a message.
isJid(value)function(value: string): boolean — JID-format check.
resolveUsername(...)functionResolve a username to a JID. Socket: UsernameResolveSocketLike.
BuilderSocketLike / TextOptionstypeBuilder socket shape + text options.

Builder types

BuilderState, BuilderContext, MediaSource, ImageOptions, VideoOptions, AudioOptions, DocumentOptions, StickerOptions, AlbumItem, ListOptions, ListSection, PollOptions, LocationOptions, TemplateOptions, ButtonDef, InteractiveButton (ReplyButton, UrlButton, CopyButton, CallButton, ReminderButton, CancelReminderButton, LocationRequestButton, AddressButton), BottomSheetOptions, LimitedTimeOfferOptions.

Events

Inbound event payloads and helpers. See Events.

client.on('message', (msg) => console.log(msg.text(), msg.chatId())) client.on('call', (call) => console.log(call))
ExportKindDescription
buildMessageContext(...)functionBuild the rich MessageContext from a raw message.
dropSpoofedSelfOnly(upsert)functionGuard that drops spoofed self-only protocol messages.
SELF_ONLY_PROTOCOL_TYPESconstFrozen list of self-only protocol types.
MessageContexttypeThe rich, lazy message object passed to handlers.
ChatType / SenderInfo / SenderDevicetypeSender/chat metadata.
Payload typestypeButtonClickPayload, CallPayload/CallBase, DeletePayload, EditPayload, GroupJoinPayload, GroupLeavePayload, GroupUpdatePayload, GroupParticipantInfo, HistorySyncPayload, LimitedPayload, ListSelectPayload, MemberTagPayload, NewsletterPayload, PollVotePayload, PresencePayload, ReactionPayload, QuotedRef.
Media contexttypeContextMedia, MediaDescriptor, MediaDownloadResult, MediaKind.
MentionstypeMentionContext, MentionAllContext.
Event mapstypeInboundEventMap, InboundEventName.
CitationstypeCitationConfig, CitationPredicates.
MisctypeBuildContextInput, UpsertPayload, SelfOnlyProtocolType.

Commands

Prefix-based command routing. See Commands.

client.command('ping', async (ctx) => ctx.reply('pong')) client.use(async (ctx, next) => { console.log(ctx.command); await next() })
ExportKindDescription
parseCommand(text, prefixes)functionParse text into ParsedArgs.
CommandRegistryclassHolds command definitions: register, resolve, list.
runMiddleware(...)functionRun a middleware chain.
attachCommandDispatcher(...)functionWire the dispatcher to a client.
CommandContextinterfaceExtends MessageContext with command, args, flags, json, reply, react, edit.
CommandHandler / MiddlewaretypeHandler and middleware function shapes.
CommandDefinition / ParsedArgs / CommandPrefixtypeDefinition, parsed args, and prefix types.
DispatcherDeps / DispatcherHandle / ResolvedCommandtypeDispatcher internals.

Automation

Rate limiting, queues, broadcast, scheduling, presence. See Broadcast & Schedule.

ExportKindDescription
RateLimiterclassToken-bucket limiter. Method: acquire(jid?). Options: RateLimiterOptions, RateLimiterClock.
TaskQueueclassConcurrency-limited queue. Methods: add(task), onIdle(). Options: TaskQueueOptions, TaskQueueClock.
runBroadcast(...)functionFan-out send. Options: BroadcastOptions, BroadcastResult, BroadcastDeps.
SchedulerclassPersistent scheduler. Methods: scheduleAt(...), loadPending(), dispose(). Deps/types: SchedulerDeps, SchedulerTimer, ScheduleHandle, ScheduledContentSnapshot.
PresenceModuleclassMethods: online(), offline(), typing(jid, ms?), recording(jid, ms?). Types: AutomationSocketLike, WAPresence. Full guide: Presence.
RetryPolicy / ScheduledJob / ScheduledJobRecordtypeRetry config and scheduled-job shapes.

Domain Modules

Accessed via client.group, client.privacy, client.newsletter, client.community. Full guides: Groups · Communities · Newsletters · Privacy & Blocking. See also Client & Lifecycle.

const meta = await client.group.metadata('xxx@g.us') await client.group.addMember('xxx@g.us', ['628xxx@s.whatsapp.net'])

GroupModule

create, addMember, removeMember, promote, demote, updateSubject, updateDescription, leave, metadata, tagMember, inviteCode, revokeInvite, acceptInvite, toggleEphemeral, setting.

PrivacyModule

set, get, block, unblock, blocklist, disappearingMode.

NewsletterModule

create, follow, unfollow, metadata, updateName, updateDescription, updatePicture, mute, unmute, delete.

CommunityModule

create, createGroup, linkGroup, unlinkGroup, subGroups, leave, updateSubject, updateDescription, inviteCode, revokeInvite, acceptInvite.

Domain types: ParticipantUpdateResult, PrivacyConfig, PrivacySettings, LinkedGroup, DomainSocketLike.

Media

FFmpeg/sharp-backed media processing. See Media.

import { Media } from 'zaileys' const m = new Media('./input.mp3') const opus = await m.audio.toOpus() const thumb = await m.video.thumbnail()
ExportKindDescription
MediaclassFacade with getters: audio (toOpus/toMp3/convert/waveform), video (toMp4/thumbnail), image (toJpeg/thumbnail/resize), sticker.create, document.create, thumbnail.get.
AudioProcessor / VideoProcessor / ImageProcessor / StickerProcessor / DocumentProcessorclassLow-level processors.
FFmpegProcessor / FileManager / BufferConverter / MimeValidatorclassFFmpeg/IO helpers.
initializeFFmpeg(disable?) / detectFileType(buffer) / generateId() / ffmpegTransform(...)functionSetup and transform helpers.
FFMPEG_CONSTANTSconstShared MIME/extension constants.
MediaInput / FileExtension / AudioType / StickerShapeTypetypeInput and format types.
FFmpegConfig / StickerMetadataTypeinterfaceConfig and sticker metadata.

Connection

Lower-level connection primitives (advanced). See Client & Lifecycle.

ExportKindDescription
createPairingFlow(opts)functionBuild a pairing-code flow. Types: PairingFlow, PairingFlowOptions, PairingFlowResult.
createReconnectStrategy(...)functionReconnect backoff strategy. Types: ReconnectStrategy, ReconnectDecision, ReconnectStrategyDeps.
createConnectionStateMachine(initial?)functionState machine. Types: ConnectionStateMachine, StateTransitionListener.
signalKeyStoreFromAuthStore(store, logger?)functionAdapt an AuthStore into a Baileys signal key store.
renderQrInTerminal(qrString)functionRender a QR string in the terminal.
mapDisconnectReason(code) / isFatalDisconnect(r) / shouldClearAuth(r) / shouldReconnect(r)functionDisconnect-reason classifiers. Type: DisconnectReasonDomain.
normalizePhoneNumber(raw) / validateE164(raw)functionPhone-number helpers.

Utilities

ExportKindDescription
createLogger(options?)functionBuild a Pino-based logger. Options: CreateLoggerOptions.
adoptLogger(maybe, fallback?)functionNormalize a partial logger into a full Logger.
chunk(...)functionSplit an array into fixed-size chunks.
ZaileysLogger / LoggerLeveltypeLogger instance and level types.

Errors

Typed error classes per subsystem. Each carries a discriminated code. See Error Handling for handling patterns.

import { ZaileysBuilderError } from 'zaileys' try { await client.send(jid).text('hi') } catch (e) { if (e instanceof ZaileysBuilderError) console.error(e.code, e.message) }
ExportKindDescription
ZaileysBuilderErrorclassBuilder/send failures. Code: BuilderErrorCode.
ZaileysDomainErrorclassGroup/privacy/newsletter/community failures. Code: DomainErrorCode.
ZaileysCommandErrorclassCommand parsing/dispatch failures. Code: CommandErrorCode.
ZaileysAutomationErrorclassBroadcast/schedule/queue failures. Code: AutomationErrorCode.
ZaileysStoreErrorclassStore failures. Code: StoreErrorCode.

Misc Types

ExportKindDescription
LIDMappinginterfaceLinked-device ID mapping.
LIDMappingUpdatePayloadtypePayload for LID mapping updates.
⚠️

Optional native dependencies (SQLite, Postgres pg, Redis, Convex, FFmpeg, sharp) are loaded lazily. Install only the adapter you use — see Storage Adapters and Media.

Last updated on