### Install Chat SDK Packages (bun) Source: https://zeative.github.io/chat-adapter-zaileys/getting-started Install the core chat-adapter-zaileys, zaileys, and chat packages using bun. ```bash bun add chat-adapter-zaileys zaileys chat ``` -------------------------------- ### Install SQLite Store Backend (bun) Source: https://zeative.github.io/chat-adapter-zaileys/getting-started Install the better-sqlite3 package for durable message history using bun. ```bash bun add better-sqlite3 ``` -------------------------------- ### Install Chat SDK Packages (npm) Source: https://zeative.github.io/chat-adapter-zaileys/getting-started Install the core chat-adapter-zaileys, zaileys, and chat packages using npm. ```bash npm i chat-adapter-zaileys zaileys chat ``` -------------------------------- ### Install Chat SDK Packages (yarn) Source: https://zeative.github.io/chat-adapter-zaileys/getting-started Install the core chat-adapter-zaileys, zaileys, and chat packages using yarn. ```bash yarn add chat-adapter-zaileys zaileys chat ``` -------------------------------- ### Install SQLite Store Backend (yarn) Source: https://zeative.github.io/chat-adapter-zaileys/getting-started Install the better-sqlite3 package for durable message history using yarn. ```bash yarn add better-sqlite3 ``` -------------------------------- ### Install SQLite Store Backend (npm) Source: https://zeative.github.io/chat-adapter-zaileys/getting-started Install the better-sqlite3 package for durable message history using npm. ```bash npm i better-sqlite3 ``` -------------------------------- ### Install Chat SDK Packages (pnpm) Source: https://zeative.github.io/chat-adapter-zaileys/getting-started Install the core chat-adapter-zaileys, zaileys, and chat packages using pnpm. ```bash pnpm add chat-adapter-zaileys zaileys chat ``` -------------------------------- ### Initialize Chat SDK with Zaileys Adapter Source: https://zeative.github.io/chat-adapter-zaileys Sets up the Chat SDK with the Zaileys WhatsApp adapter. Ensure you have the necessary dependencies installed. ```javascript import { Chat, memoryState } from 'chat' import { createZaileysAdapter } from 'chat-adapter-zaileys' const whatsapp = createZaileysAdapter({ session: { sessionId: 'main' } }) const bot = new Chat({ userName: 'mybot', adapters: { whatsapp }, state: memoryState() }) bot.onNewMention(async (thread, message) => { await thread.subscribe() await thread.post(`Hello, ${message.author.fullName}!`) }) await bot.initialize() await whatsapp.connect() ``` -------------------------------- ### Install SQLite Store Backend (pnpm) Source: https://zeative.github.io/chat-adapter-zaileys/getting-started Install the better-sqlite3 package for durable message history using pnpm. ```bash pnpm add better-sqlite3 ``` -------------------------------- ### Configure Adapter for Slash Commands Source: https://zeative.github.io/chat-adapter-zaileys/events Initialize the adapter with `slashCommands: true` and specify command prefixes to enable routing of messages starting with these prefixes to `onSlashCommand`. ```javascript const whatsapp = createZaileysAdapter({ session: { sessionId: 'main', commandPrefix: ['/', '!'] }, slashCommands: true, }) ``` -------------------------------- ### Create a Basic Chat Bot Source: https://zeative.github.io/chat-adapter-zaileys/getting-started Initialize a Chat SDK bot with a WhatsApp adapter and memory-based state. Register handlers before connecting the adapter. ```typescript import { Chat, memoryState } from 'chat' import { createZaileysAdapter } from 'chat-adapter-zaileys' const whatsapp = createZaileysAdapter({ session: { sessionId: 'main' }, }) const bot = new Chat({ userName: 'mybot', adapters: { whatsapp }, state: memoryState(), }) bot.onNewMention(async (thread, message) => { await thread.subscribe() await thread.post(`Hello, ${message.author.fullName}!`) }) bot.onSubscribedMessage(async (thread, message) => { await thread.post(`You said: ${message.text}`) }) await bot.initialize() await whatsapp.connect() ``` -------------------------------- ### Welcome New Members with Chat SDK Source: https://zeative.github.io/chat-adapter-zaileys/events Use `onMemberJoinedChannel` to post a welcome message when a new member joins. This handler receives an event with channel and user information. ```javascript bot.onMemberJoinedChannel(async (event) => { const thread = await bot.getThread(event.channelId) await thread.post(`Welcome <@${event.userId}>!`) }) ``` -------------------------------- ### native() - The Everything Hatch Source: https://zeative.github.io/chat-adapter-zaileys/extensions Access the entire Zaileys message builder pre-targeted at a thread. ```APIDOC ## `native(threadId)` β€” The Everything Hatch This method exposes the entire Zaileys message builder, pre-targeted at a specific thread. It allows sending various content types and applying modifiers. ### Method Invoked as `adapter.native(threadId)`. ### Parameters - **threadId** (string) - Required - The ID of the thread to send the message to. ### Usage Examples ```javascript // Sending an image with viewOnce enabled await wa.native(thread.id).image(buffer, { viewOnce: true }) // Sending an album of images await wa.native(thread.id).album([ { type: 'image', src: './a.jpg' }, { type: 'image', src: './b.jpg' } ]) // Sending a list message await wa.native(thread.id).list({ title: 'Menu', buttonText: 'Open', sections }) // Sending an event message await wa.native(thread.id).event({ name: 'Standup', startTime }) // Sending a text message and mentioning everyone await wa.native(thread.id).text('hey everyone').mentionAll() // Sending a disappearing text message await wa.native(thread.id).text('secret').disappearing(86_400) ``` ### Available Content Types and Modifiers - **Content Types**: Text, image, video, video note, audio, document, sticker, buttons, carousel, list, poll, location, contact, template, event, group invite, product, album. - **Modifiers**: `.reply()`, `.mentions()`, `.mentionAll()`, `.disappearing()`. ### Return Value Awaiting the builder returns the sent `WAMessageKey`. ### Note Messages sent through `native()` are not tracked for `author.isMe` echo detection. ``` -------------------------------- ### Create Zaileys Adapter Instance Source: https://zeative.github.io/chat-adapter-zaileys/configuration Instantiate a Zaileys adapter with essential configuration like session details, adapter name, and user name. Customize behavior with options such as forwarding poll votes, auto-marking messages as read, rich message rendering, and slash command handling. ```javascript import { createZaileysAdapter } from 'chat-adapter-zaileys' const whatsapp = createZaileysAdapter({ session: { sessionId: 'main' }, // or: client: myZaileysClient adapterName: 'zaileys', userName: 'zaileys-bot', forwardPollVotes: true, autoMarkRead: false, richMessages: false, slashCommands: false, }) ``` -------------------------------- ### Configure Multi-Account Chatbot Source: https://zeative.github.io/chat-adapter-zaileys/configuration Set up a Chat instance to manage multiple WhatsApp accounts by creating separate Zaileys adapters, each with a unique `adapterName`. This allows for distinct thread IDs and management of different accounts within the same bot. ```javascript const main = createZaileysAdapter({ session: { sessionId: 'main' }, adapterName: 'wa-main', }) const sales = createZaileysAdapter({ session: { sessionId: 'sales' }, adapterName: 'wa-sales', }) const bot = new Chat({ userName: 'mybot', adapters: { main, sales }, state: memoryState(), }) await bot.initialize() await Promise.all([main.connect(), sales.connect()]) ``` -------------------------------- ### Send Broadcasts and Register Commands with adapter.client Source: https://zeative.github.io/chat-adapter-zaileys/extensions Utilize `adapter.client` for sending broadcast messages with optional rate limiting and for registering custom commands within the chat adapter framework. ```typescript whatsapp.client.broadcast(jids, (b) => b.text('Announcement'), { rateLimitPerSec: 5 }) whatsapp.client.command('ping', (ctx) => ctx.reply('pong πŸ“')) ``` -------------------------------- ### Extension Reference Source: https://zeative.github.io/chat-adapter-zaileys/extensions A table listing available extension methods for interacting with WhatsApp features. ```APIDOC ## Extension Reference This section lists various extension methods that can be used to access native WhatsApp functionalities. ### `reply(message, content)` - **Description**: Sends a quoted reply to a message, supporting any postable content including media. - **Method**: Not specified (invoked as an extension method). - **Parameters**: - `message`: The message to reply to. - `content`: The content of the reply (postable, media). ### `markRead(threadId)` - **Description**: Sends read receipts (blue ticks) for a given chat. - **Method**: Not specified (invoked as an extension method). - **Parameters**: - `threadId` (string): The ID of the thread to mark as read. ### `setPresence(status)` - **Description**: Sets the global online/offline status. - **Method**: Not specified (invoked as an extension method). - **Parameters**: - `status` ('available' | 'unavailable'): The presence status to set. ### `startTyping(threadId)` - **Description**: Shows the "typing..." indicator in a chat. - **Method**: Not specified (invoked as an extension method). - **Parameters**: - `threadId` (string): The ID of the thread to show typing indicator for. ### `startRecording(threadId)` - **Description**: Shows the "recording audio..." indicator in a chat. - **Method**: Not specified (invoked as an extension method). - **Parameters**: - `threadId` (string): The ID of the thread to show recording indicator for. ### `setDisappearing(threadId, seconds)` - **Description**: Toggles disappearing messages for a chat. Setting `seconds` to `0` disables this feature. - **Method**: Not specified (invoked as an extension method). - **Parameters**: - `threadId` (string): The ID of the thread. - `seconds` (number): The duration in seconds for messages to disappear. ### `sendLocation({ threadId, latitude, longitude, name?, address? })` - **Description**: Sends a native map-pin message. - **Method**: Not specified (invoked as an extension method). - **Parameters**: - `threadId` (string): The ID of the thread. - `latitude` (number): The latitude of the location. - `longitude` (number): The longitude of the location. - `name` (string, optional): The name of the location. - `address` (string, optional): The address of the location. ### `sendPoll({ threadId, question, options, selectableCount? })` - **Description**: Sends a native poll message. - **Method**: Not specified (invoked as an extension method). - **Parameters**: - `threadId` (string): The ID of the thread. - `question` (string): The question for the poll. - `options` (array): An array of poll options. - `selectableCount` (number, optional): The number of options a user can select. ### `sendSticker(threadId, src)` - **Description**: Sends a sticker from a webp, png, or jpeg source. Zaileys handles conversion, including animated Lottie. - **Method**: Not specified (invoked as an extension method). - **Parameters**: - `threadId` (string): The ID of the thread. - `src` (string | Buffer): The source of the sticker. ### `sendVoiceNote(threadId, src)` - **Description**: Sends a push-to-talk audio bubble. - **Method**: Not specified (invoked as an extension method). - **Parameters**: - `threadId` (string): The ID of the thread. - `src` (string | Buffer): The source of the voice note. ### `sendContact(threadId, vcard)` - **Description**: Sends a contact card. - **Method**: Not specified (invoked as an extension method). - **Parameters**: - `threadId` (string): The ID of the thread. - `vcard` (string): The vCard data for the contact. ### `forwardMessage(threadId, messageId, toThreadId)` - **Description**: Forwards a message to another chat. - **Method**: Not specified (invoked as an extension method). - **Parameters**: - `threadId` (string): The ID of the thread where the original message is. - `messageId` (string): The ID of the message to forward. - `toThreadId` (string): The ID of the thread to forward the message to. ### `pinMessage(threadId, messageId)` / `unpinMessage(threadId, messageId)` - **Description**: Pins or unpins a message in a chat. - **Method**: Not specified (invoked as an extension method). - **Parameters**: - `threadId` (string): The ID of the thread. - `messageId` (string): The ID of the message to pin or unpin. ### `fetchGroupParticipants(threadId)` - **Description**: Fetches participants of a group, including `isAdmin` and `isSuperAdmin` flags. Throws an error if the thread is not a group. - **Method**: Not specified (invoked as an extension method). - **Parameters**: - `threadId` (string): The ID of the group thread. - **Returns**: An array of participant objects. ### `getUser(userId)` - **Description**: Retrieves user information, including profile picture, from the contact store. - **Method**: Not specified (invoked as an extension method). - **Parameters**: - `userId` (string): The ID of the user. - **Returns**: `UserInfo` object. ### `openDM(userId)` - **Description**: Opens a direct message thread with a user. Accepts user ID as digits or a JID. - **Method**: Not specified (invoked as an extension method). - **Parameters**: - `userId` (string): The ID or JID of the user. - **Returns**: The thread ID of the direct message. ### `onPollVote(handler)` - **Description**: Registers a handler for decrypted poll votes. - **Method**: Not specified (invoked as an extension method). - **Parameters**: - `handler` (function): The callback function to handle poll vote events. ``` -------------------------------- ### Handle Slash Commands Source: https://zeative.github.io/chat-adapter-zaileys/events Implement `onSlashCommand` to process commands prefixed with configured prefixes. The command name is normalized to `/name`. ```javascript bot.onSlashCommand('/deploy', async (event) => { await event.channel.post(`Deploying ${event.text}…`) // "/deploy prod" β†’ text = "prod" }) ``` -------------------------------- ### Handling Lazy Media Attachments Source: https://zeative.github.io/chat-adapter-zaileys/payload This snippet shows how to access metadata for attachments immediately and download their content on demand using `fetchData`. It covers both the standard message attachments and accessing media through the Zaileys context. ```javascript const [attachment] = message.attachments if (attachment) { attachment.mimeType // 'image/jpeg' attachment.size // bytes, when known const buffer = await attachment.fetchData() // downloads now } // or through the zaileys context: const ctx = zaileysContext(message) if (ctx?.media && 'buffer' in ctx.media) { const buffer = await ctx.media.buffer() } ``` -------------------------------- ### Post Files and Attachments Source: https://zeative.github.io/chat-adapter-zaileys/messages Send files or attachments with messages by providing a `files` array. The adapter routes based on MIME type and handles URLs by downloading them. ```javascript await thread.post({ markdown: 'Here is the report', files: [{ data: pdfBuffer, filename: 'report.pdf', mimeType: 'application/pdf' }], }) ``` -------------------------------- ### Create Zaileys Client with Custom Stores Source: https://zeative.github.io/chat-adapter-zaileys/getting-started Construct a Zaileys Client manually for advanced control, specifying custom authentication and message stores. ```typescript import { Client, SqliteAuthStore, SqliteMessageStore } from 'zaileys' import { createZaileysAdapter } from 'chat-adapter-zaileys' const client = new Client({ sessionId: 'main', auth: new SqliteAuthStore({ database: './auth.db' }), store: new SqliteMessageStore({ database: './wa.db' }), // durable history for fetchMessages }) const whatsapp = createZaileysAdapter({ client }) ``` -------------------------------- ### Use Zaileys Extension Methods Source: https://zeative.github.io/chat-adapter-zaileys/extensions Demonstrates common Zaileys extension methods for interacting with WhatsApp threads, such as marking messages as read, sending location, voice notes, and fetching group participants. ```typescript const wa = requireZaileysAdapter(thread) await wa.markRead(thread.id) await wa.sendLocation({ threadId: thread.id, latitude: -6.2, longitude: 106.8, name: 'Jakarta' }) await wa.sendVoiceNote(thread.id, oggBuffer) const admins = (await wa.fetchGroupParticipants(thread.id)).filter((p) => p.isAdmin) ``` -------------------------------- ### Post Message with Echo Detection Source: https://zeative.github.io/chat-adapter-zaileys/troubleshooting Use `thread.post` instead of `native()` when echo detection is important, as the builder bypasses the adapter's send path. ```javascript thread.post ``` -------------------------------- ### Send Media Edit with Native Client Source: https://zeative.github.io/chat-adapter-zaileys/troubleshooting For media edits, use `wa.native()` combined with `client.edit(key)` instead of the text-only `sent.edit()` method. ```javascript wa.native() + client.edit(key) ``` -------------------------------- ### Send Various Media with native() Source: https://zeative.github.io/chat-adapter-zaileys/extensions Utilize the `native()` method to send diverse content types like single view-once images, albums of images, and structured lists. This provides access to the full Zaileys message builder. ```typescript await wa.native(thread.id).image(buffer, { viewOnce: true }) await wa.native(thread.id).album([ { type: 'image', src: './a.jpg' }, { type: 'image', src: './b.jpg' }, ]) await wa.native(thread.id).list({ title: 'Menu', buttonText: 'Open', sections }) ``` -------------------------------- ### adapter.client - The Whole Zaileys Client Source: https://zeative.github.io/chat-adapter-zaileys/extensions Access to the complete Zaileys client for managing groups, communities, privacy, contacts, and more. ```APIDOC ## `adapter.client` β€” The Whole Zaileys Client This property provides access to the complete Zaileys client, offering functionalities beyond direct message sending, including group management, community features, privacy settings, contact management, business catalogs, broadcasting, and the command framework. ### Access Available via `whatsapp.client`. ### Example Usage ```javascript // Promoting a user in a group whatsapp.client.group.promote(groupJid, [userJid]) // Creating a newsletter whatsapp.client.newsletter.create('My Channel', 'Updates') // Updating privacy settings for last seen whatsapp.client.privacy.updateLastSeen('contacts') // Sending a broadcast message whatsapp.client.broadcast(jids, (b) => b.text('Announcement'), { rateLimitPerSec: 5 }) // Registering a command whatsapp.client.command('ping', (ctx) => ctx.reply('pong πŸ“')) ``` ### Further Documentation For a complete list of available methods and features, refer to the full documentation at [zeative.github.io/zaileys](https://zeative.github.io/zaileys). ``` -------------------------------- ### Configure Durable Message Store Source: https://zeative.github.io/chat-adapter-zaileys/scheduling To ensure scheduled jobs persist across process restarts, configure the `Client` with a durable message store like `SqliteMessageStore`. ```javascript const client = new Client({ sessionId: 'main', store: new SqliteMessageStore({ database: './wa.db' }), }) ``` -------------------------------- ### Stream Text Content Source: https://zeative.github.io/chat-adapter-zaileys/messages The adapter implements `editMessage`, allowing the SDK's fallback streaming (post + edit) to work seamlessly for streaming text content. ```javascript bot.onSubscribedMessage(async (thread) => { const stream = await ai.streamText({ /* … */ }) await thread.post(stream.textStream) }) ``` -------------------------------- ### Schedule Media or Interactive Content Directly Source: https://zeative.github.io/chat-adapter-zaileys/scheduling For scheduling media or interactive content, use the Zaileys scheduler directly with the builder pattern, providing the date and a callback to construct the message. ```javascript await whatsapp.client.scheduleAt(date, (b) => b.to(jid).image('./promo.jpg', { caption: 'Launching today!' }), ) ``` -------------------------------- ### Manage Groups, Newsletters, and Privacy with adapter.client Source: https://zeative.github.io/chat-adapter-zaileys/extensions Perform administrative tasks like promoting group members, creating newsletters, and updating privacy settings using the `adapter.client` property. This offers access to a wide range of Zaileys client functionalities. ```typescript whatsapp.client.group.promote(groupJid, [userJid]) whatsapp.client.newsletter.create('My Channel', 'Updates') whatsapp.client.privacy.updateLastSeen('contacts') ``` -------------------------------- ### Handle Incoming Calls Source: https://zeative.github.io/chat-adapter-zaileys/events Listen for 'call-incoming' events on the client to log details about incoming calls, including the caller's identifier. ```javascript whatsapp.client.on('call-incoming', (call) => console.log('incoming call from', call.from)) ``` -------------------------------- ### Post Plain Text and Formatted Markdown Source: https://zeative.github.io/chat-adapter-zaileys/messages Use `thread.post()` to send plain text or markdown-formatted messages. Markdown is converted to WhatsApp's native markup. ```javascript await thread.post('plain text') ``` ```javascript await thread.post({ markdown: '**bold** _italic_ ~~strike~~ `code` [docs](https://example.com)' }) ``` -------------------------------- ### Post a Card with Buttons Source: https://zeative.github.io/chat-adapter-zaileys/cards-buttons Post a card with title and actions, including buttons with IDs and values. This is used to present interactive options to the user. ```javascript import { Card, Actions, Button } from 'chat' bot.onNewMention(async (thread) => { await thread.post( ) }) ``` -------------------------------- ### Enable Rich Messages with AIRich Source: https://zeative.github.io/chat-adapter-zaileys/messages Set `richMessages: true` in the adapter configuration to render markdown posts with syntax-highlighted code blocks, tables, and directives using Zaileys AIRich. ```javascript const whatsapp = createZaileysAdapter({ session: { sessionId: 'main' }, richMessages: true }) await thread.post({ markdown: ['## Daily brief', '', '```ts', 'const x = 1', '```'].join('\n'), }) ``` -------------------------------- ### Configure Durable Message Store Source: https://zeative.github.io/chat-adapter-zaileys/history Initializes the Zaileys client with a durable SQLite message store for persistent history. This ensures messages are not lost on client restart. ```javascript import { Client, SqliteMessageStore } from 'zaileys' const client = new Client({ sessionId: 'main', store: new SqliteMessageStore({ database: './wa.db' }), }) const whatsapp = createZaileysAdapter({ client }) ``` -------------------------------- ### Send URL Button in Card Source: https://zeative.github.io/chat-adapter-zaileys/troubleshooting When WhatsApp buttons are reply-buttons, use the card body for URLs or `native().buttons([{ type: 'url', … }])`. ```javascript native().buttons([{ type: 'url', … }]) ``` -------------------------------- ### Handle Reactions with Chat SDK Source: https://zeative.github.io/chat-adapter-zaileys/events Use `onReaction` to handle reaction events. The `added` property indicates if a reaction was added or removed, and emojis are normalized. ```javascript bot.onReaction('πŸ”₯', async (event) => { await event.thread.post(`${event.user.userName} reacted with fire!`) }) ``` -------------------------------- ### WhatsApp Authentication via Pairing Code Source: https://zeative.github.io/chat-adapter-zaileys/getting-started Configure the Zaileys adapter to use pairing code authentication for WhatsApp, providing the phone number. ```typescript const whatsapp = createZaileysAdapter({ session: { sessionId: 'main', authType: 'pairing', phoneNumber: '6281234567890' }, }) ``` -------------------------------- ### Enable Media Rehydration Source: https://zeative.github.io/chat-adapter-zaileys/history Configures the chat adapter to rehydrate attachments by storing message keys and re-downloading media from the store when messages are dequeued. This is useful when using queue or debounce concurrency. ```javascript const bot = new Chat({ adapters: { whatsapp }, state: myState, concurrency: 'queue', // attachments still download after dequeue /* … */ }) ``` -------------------------------- ### Handle Presence Updates Source: https://zeative.github.io/chat-adapter-zaileys/events The 'presence' event provides updates on user presence status. Log the event payload to inspect presence details. ```javascript whatsapp.client.on('presence', (p) => console.log(p)) ``` -------------------------------- ### Access Underlying Zaileys Client Source: https://zeative.github.io/chat-adapter-zaileys/configuration Interact directly with the Zaileys client instance through the adapter's `.client` property. This provides access to all Zaileys client methods for advanced operations like managing group metadata, updating privacy settings, sending broadcasts, and handling incoming calls. ```javascript whatsapp.client.group.metadata(jid) whatsapp.client.privacy.updateLastSeen('contacts') whatsapp.client.broadcast(jids, (b) => b.text('Announcement')) whatsapp.client.on('call-incoming', (call) => { /* … */ }) ``` -------------------------------- ### Add Reaction with Participant JID Source: https://zeative.github.io/chat-adapter-zaileys/troubleshooting When reacting to another member's message in a group, the participant's JID must be passed as the 4th argument. ```javascript adapter.addReaction(threadId, messageId, emoji, participantJid) ``` -------------------------------- ### Send Native Interactive Buttons Source: https://zeative.github.io/chat-adapter-zaileys/cards-buttons Utilize the native() method to send various interactive message types, including URL, copy, and call buttons. This provides a richer user experience beyond basic cards. ```javascript const wa = requireZaileysAdapter(thread) await wa.native(thread.id).buttons( [ { id: 'yes', text: 'Yes' }, { type: 'url', text: 'Open docs', url: 'https://zeative.github.io/zaileys/' }, { type: 'copy', text: 'Copy code', code: 'ZAILEYS-2026' }, ], { title: 'Pick one', text: 'Tap a button below' }, ) whatsapp.client.on('button-click', (ctx) => console.log('tapped:', ctx.buttonId)) ``` -------------------------------- ### Receive All Poll Votes with Zaileys Source: https://zeative.github.io/chat-adapter-zaileys/polls Listen for all poll votes sent by the current account using `wa.onPollVote`. This handler receives `ZaileysPollVote` objects. ```javascript // every poll this account sent wa.onPollVote((vote) => { console.log(vote.voter.userName, 'β†’', vote.selectedOptions) }) ``` -------------------------------- ### Send a WhatsApp Poll with Zaileys Source: https://zeative.github.io/chat-adapter-zaileys/polls Use `wa.sendPoll` to send a poll. Specify the `threadId`, `question`, `options`, and `selectableCount`. A `selectableCount` of 1 allows single selection, while other values permit multiple selections. ```javascript import { requireZaileysAdapter } from 'chat-adapter-zaileys' const wa = requireZaileysAdapter(thread) const poll = await wa.sendPoll({ threadId: thread.id, question: 'What time works for the call?', options: ['10:00', '14:00', '17:00'], selectableCount: 1, // any other value allows multiple selections }) ``` -------------------------------- ### Handle Group Updates Source: https://zeative.github.io/chat-adapter-zaileys/events Use the 'group-update' event to log changes in group information. The event payload contains details about the update. ```javascript whatsapp.client.on('group-update', (u) => console.log('group changed:', u.update)) ``` -------------------------------- ### Accessing and Using Zaileys Message Context Source: https://zeative.github.io/chat-adapter-zaileys/payload This snippet demonstrates how to access the decoded Zaileys MessageContext from an incoming message and use its properties and methods. It's useful for processing live messages, checking message flags, retrieving quoted messages, and reacting to messages. ```javascript import { zaileysContext } from 'chat-adapter-zaileys' bot.onSubscribedMessage(async (thread, message) => { const ctx = zaileysContext(message) if (!ctx) return // history fetches / sent echoes have no live context ctx.senderDevice // 'android' | 'ios' | 'web' | 'desktop' ctx.isForwarded / ctx.isViewOnce // 20+ decoded flags const quoted = await ctx.replied() // the full decoded quoted message await ctx.react('πŸ”₯') // zaileys shortcuts still work }) ``` -------------------------------- ### Manipulate Zaileys Thread IDs Source: https://zeative.github.io/chat-adapter-zaileys/configuration Utilities for encoding and decoding thread IDs, which are formatted as ':'. Includes functions to check if a thread ID represents a direct message and to open a new direct message thread. ```javascript adapter.encodeThreadId({ jid: '628123456789@s.whatsapp.net' }) // "zaileys:NjI4MTIzNDU2Nzg5QHMud2hhdHNhcHAubmV0" adapter.decodeThreadId(threadId) // { jid: "628123456789@s.whatsapp.net" } adapter.isDM(threadId) // true for DMs, false for groups/newsletters adapter.openDM('6281234567890') // β†’ DM thread ID (accepts digits or a jid) ``` -------------------------------- ### Edit, Delete, React, and Indicate Typing Source: https://zeative.github.io/chat-adapter-zaileys/messages Manage sent messages by editing content, adding/removing reactions, deleting messages, or showing a typing indicator. Use `native()` for editing media or exotic content. ```javascript const sent = await thread.post('Original') await sent.edit('Fixed') // β†’ WhatsApp native edit await sent.addReaction('πŸ‘') // β†’ native reaction await sent.removeReaction('πŸ‘') await sent.delete() // β†’ delete for everyone await thread.startTyping() // "typing…" indicator ``` -------------------------------- ### Require Zaileys Adapter Source: https://zeative.github.io/chat-adapter-zaileys/extensions Safely access Zaileys-specific adapter methods by ensuring the thread is from Zaileys. Throws an error if the adapter is not of the Zaileys type. ```typescript import { isZaileysAdapter, requireZaileysAdapter } from 'chat-adapter-zaileys' bot.onSubscribedMessage(async (thread, message) => { const wa = requireZaileysAdapter(thread) // throws if not a zaileys thread // … }) ``` -------------------------------- ### Handle Message Deletions Source: https://zeative.github.io/chat-adapter-zaileys/events Listen for 'delete' events to log the ID of deleted messages. This is useful for tracking message lifecycle. ```javascript whatsapp.client.on('delete', (d) => console.log('message deleted:', d.key.id)) ``` -------------------------------- ### Send Rich Messages and Apply Modifiers with native() Source: https://zeative.github.io/chat-adapter-zaileys/extensions Send rich messages such as events or text with mentions and disappearing options using the `native()` method. Note that messages sent via `native()` are not tracked for `author.isMe` echo detection. ```typescript await wa.native(thread.id).event({ name: 'Standup', startTime }) await wa.native(thread.id).text('hey everyone').mentionAll() await wa.native(thread.id).text('secret').disappearing(86_400) ``` -------------------------------- ### Send Quoted Replies Source: https://zeative.github.io/chat-adapter-zaileys/messages Utilize the `reply` method from the Zaileys adapter to send quoted replies, which quotes the original message. This feature supports media as well. ```javascript import { requireZaileysAdapter } from 'chat-adapter-zaileys' bot.onSubscribedMessage(async (thread, message) => { const wa = requireZaileysAdapter(thread) await wa.reply(message, 'Got it!') // quotes the original, media supported }) ``` -------------------------------- ### Fetch Recent Messages Source: https://zeative.github.io/chat-adapter-zaileys/history Fetches the most recent messages up to a specified limit. Use the `nextCursor` from the result to fetch older messages. ```javascript const recent = await thread.fetchMessages({ limit: 50 }) // recent.messages β€” chronological (oldest β†’ newest), full Message objects const older = await thread.fetchMessages({ limit: 50, cursor: recent.nextCursor }) ``` -------------------------------- ### Fallback to DM for Ephemeral Messages Source: https://zeative.github.io/chat-adapter-zaileys/troubleshooting WhatsApp's `thread.postEphemeral` falls back to Direct Message when `fallbackToDM: true` is set, as WhatsApp has no direct equivalent for ephemeral messages. ```javascript thread.postEphemeral ``` -------------------------------- ### Handle Button Clicks Source: https://zeative.github.io/chat-adapter-zaileys/cards-buttons Handle actions triggered by button clicks. The event object contains actionId, value, user, and messageId. This is crucial for processing user interactions. ```javascript bot.onAction('deploy', async (event) => { await event.thread?.post(`Deploying ${event.value}…`) // value = "prod" }) ``` -------------------------------- ### Schedule a Text Message Source: https://zeative.github.io/chat-adapter-zaileys/scheduling Use `thread.schedule` to send a text message at a specific future time. The returned object contains the Zaileys job ID and the scheduled post time, and can be used to cancel the message. ```javascript const scheduled = await thread.schedule('Reminder: standup in 10 minutes!', { postAt: new Date(Date.now() + 3600_000), }) scheduled.scheduledMessageId // zaileys job id scheduled.postAt // Date await scheduled.cancel() // change of plans ``` -------------------------------- ### Receive Specific Poll Votes with Zaileys Source: https://zeative.github.io/chat-adapter-zaileys/polls Register a handler for votes on a specific poll or a list of polls using `wa.onPollVote` with poll IDs. The handler processes `ZaileysPollVote` objects. ```javascript // scoped to one (or several) polls wa.onPollVote(poll.id, async (vote) => { await thread.post(`${vote.voter.userName} picked ${vote.selectedOptions[0]}`) }) wa.onPollVote([pollA.id, pollB.id], handler) ``` -------------------------------- ### Receiving votes Source: https://zeative.github.io/chat-adapter-zaileys/polls This function allows you to subscribe to vote events for polls. You can listen for all votes sent by the account or filter by specific poll IDs. ```APIDOC ## Receiving votes ### Description Subscribes to real-time vote updates for polls. Can listen to all votes or specific polls. ### Method `wa.onPollVote(pollIdOrArray, handler)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters for `onPollVote` - **pollIdOrArray** (string | string[] | undefined) - Optional - The ID of a single poll, an array of poll IDs, or undefined to listen to all polls. - **handler** (function) - Required - A callback function that receives the `vote` object. - The `vote` object has the following structure: - **threadId** (string) - Where the poll lives. - **pollMessageId** (string) - ID of the original poll message. - **question** (string | null) - Recovered from the message store when available. - **options** (string[]) - Same β€” empty if the poll left the store. - **selectedOptions** (string[]) - Current selection; **empty = vote cleared**. - **voter** (Author) - Chat SDK author shape. - **raw** (PollVotePayload) - The Zaileys payload. ### Request Example ```javascript // Listen to all votes wa.onPollVote((vote) => { console.log(vote.voter.userName, 'β†’', vote.selectedOptions); }); // Listen to votes for a specific poll wa.onPollVote(poll.id, async (vote) => { await thread.post(`${vote.voter.userName} picked ${vote.selectedOptions[0]}`); }); // Listen to votes for multiple polls wa.onPollVote([pollA.id, pollB.id], handler); ``` ### Response #### Success Response (200) None (This is an event listener) #### Response Example None ``` -------------------------------- ### Forward Poll Votes as Messages Source: https://zeative.github.io/chat-adapter-zaileys/polls When `forwardPollVotes` is true (default), non-empty poll votes are forwarded to the regular message pipeline. Bots can then process these votes as plain text messages via `onSubscribedMessage`. ```javascript bot.onSubscribedMessage(async (thread, message) => { // a vote for "14:00" arrives as message.text === "14:00" }) ``` -------------------------------- ### Sending a poll Source: https://zeative.github.io/chat-adapter-zaileys/polls This function allows you to send a new poll within a thread. You can specify the question, multiple-choice options, and whether single or multiple selections are allowed. ```APIDOC ## Sending a poll ### Description Allows sending a poll to a specified thread with a question and options. Supports single or multiple selections. ### Method `wa.sendPoll(params)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **threadId** (string) - Required - The ID of the thread to send the poll to. - **question** (string) - Required - The question for the poll. - **options** (string[]) - Required - An array of strings representing the poll options. - **selectableCount** (number) - Optional - The maximum number of options a user can select. Defaults to 1 (single selection). ### Request Example ```javascript const poll = await wa.sendPoll({ threadId: thread.id, question: 'What time works for the call?', options: ['10:00', '14:00', '17:00'], selectableCount: 1, }); ``` ### Response #### Success Response (200) Returns a poll object with an ID that can be used to reference the poll. #### Response Example (Response structure not explicitly defined in source, but implies a poll object with an ID) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.