### Project Setup Source: https://github.com/zeative/zaileys/blob/main/CONTRIBUTING.md Clone the repository, navigate to the project directory, and install dependencies using pnpm. ```bash git clone https://github.com/zeative/zaileys.git cd zaileys pnpm install ``` -------------------------------- ### Minimal Zaileys Client Setup Source: https://github.com/zeative/zaileys/blob/main/_autodocs/configuration.md Basic setup for a Zaileys client using all default configurations. This example demonstrates a simple echo bot. ```typescript import { Client } from 'zaileys' const client = new Client() client.on('text', async (msg) => { await msg.reply('Echo: ' + msg.text) }) ``` -------------------------------- ### Install Postgres Driver (bun) Source: https://github.com/zeative/zaileys/blob/main/docs/content/storage.mdx Install the pg package using bun. ```bash bun add pg ``` -------------------------------- ### Install Redis Driver (bun) Source: https://github.com/zeative/zaileys/blob/main/docs/content/storage.mdx Install the redis package using bun. ```bash bun add redis ``` -------------------------------- ### Install Convex with bun Source: https://github.com/zeative/zaileys/blob/main/docs/content/storage.mdx Install the Convex package using bun. ```bash bun add convex ``` -------------------------------- ### Hello World Bot Source: https://github.com/zeative/zaileys/blob/main/docs/content/index.mdx A complete, working bot that connects, prints a QR code for scanning, and echoes incoming text messages back to the sender. This example demonstrates basic client setup and event handling for 'qr', 'connect', and 'text' events. ```typescript import { Client } from 'zaileys' const client = new Client() client.on('qr', ({ qrString }) => console.log('Scan this QR:', qrString)) client.on('connect', ({ me }) => console.log('Connected as', me.id)) client.on('text', async (msg) => { const quoted = await msg.replied() if (quoted) console.log('In reply to:', quoted.senderId, '|', quoted.text) await msg.reply(`Hello ${msg.senderName ?? ''}! You said: ${msg.text}`) }) ``` -------------------------------- ### Install Optional Storage Adapters Source: https://github.com/zeative/zaileys/blob/main/README.md Install optional peer dependencies for different storage backends if not using the default file store. ```bash npm i better-sqlite3 # sqlite adapters ``` ```bash npm i redis # redis adapters ``` ```bash npm i pg # postgres adapters ``` ```bash npm i convex # convex adapters ``` -------------------------------- ### Minimal Client Configuration Source: https://github.com/zeative/zaileys/blob/main/_autodocs/README.md Initialize a Zaileys client with minimal configuration. This is the most basic setup required to start using the client. ```typescript const client = new Client() ``` -------------------------------- ### Full Client Configuration Example Source: https://github.com/zeative/zaileys/blob/main/docs/content/configuration.mdx A comprehensive example demonstrating the full range of ClientOptions, including session ID, authentication, phone number, message storage, command prefix, citation settings, reconnection strategy, and custom logger. ```typescript import { Client, SqliteAuthStore, SqliteMessageStore } from 'zaileys' const client = new Client({ sessionId: 'production-bot', authType: 'pairing', phoneNumber: '628xxxxxxxxxx', auth: new SqliteAuthStore({ database: './zaileys.db' }), store: new SqliteMessageStore({ database: './zaileys.db' }), commandPrefix: ['/', '!'], ignoreMe: true, citation: { authors: ['628xxx@s.whatsapp.net'], banned: (jid) => jid.startsWith('62800'), }, reconnect: { maxAttempts: 20, initialDelayMs: 2000, maxDelayMs: 30000, jitterFactor: 0.25, }, autoConnect: true, qrTerminal: false, statusLog: true, cacheSignal: true, logger: { info: (...a) => console.log('[info]', ...a), warn: (...a) => console.warn('[warn]', ...a), error: (...a) => console.error('[error]', ...a), }, baileys: { browser: ['zaileys', 'Chrome', '1.0.0'], }, }) client.on('pairing-code', ({ code }) => console.log('Pairing code:', code)) client.on('connect', ({ me }) => console.log('Connected as', me.id)) client.command('ping', async (ctx) => { await ctx.reply('pong') }) ``` -------------------------------- ### Complete Bot Example with Middleware and Commands Source: https://github.com/zeative/zaileys/blob/main/docs/content/commands.mdx A full bot example including client initialization, event listeners, logging middleware, and multiple command handlers for 'ping', 'help', and 'weather'. ```typescript import { Client, type Middleware } from 'zaileys' const client = new Client({ commandPrefix: ['/', '!'] }) client.on('qr', ({ qrString }) => console.log('Scan QR:', qrString)) const loggingMiddleware: Middleware = async (ctx, next) => { console.log(`[command] ${ctx.command} from ${ctx.senderId} args=${ctx.args.join(',')}`) await next() } client.use(loggingMiddleware) client.command('ping', async (ctx) => { await ctx.reply('pong') }) client.command('help|h|?', async (ctx) => { await ctx.reply('Commands: /ping, /weather , /help') }) client.command('weather', async (ctx) => { const city = ctx.args[0] if (!city) { await ctx.reply('Usage: /weather ') return } await ctx.reply(`Weather in ${city}: sunny, 28 degrees`) }) client.on('connect', ({ me }) => { console.log('Command bot ready as', me.id) }) ``` -------------------------------- ### Install Postgres Driver (npm) Source: https://github.com/zeative/zaileys/blob/main/docs/content/storage.mdx Install the pg package using npm. ```bash npm i pg ``` -------------------------------- ### Install Postgres Driver (yarn) Source: https://github.com/zeative/zaileys/blob/main/docs/content/storage.mdx Install the pg package using yarn. ```bash yarn add pg ``` -------------------------------- ### Initialize Client with Bun Source: https://github.com/zeative/zaileys/blob/main/docs/content/runtimes.mdx Example of initializing the Zaileys client for use with Bun. ```typescript import { Client } from 'zaileys' const client = new Client({ authType: 'qr' }) await client.connect() ``` -------------------------------- ### Install Convex with npm Source: https://github.com/zeative/zaileys/blob/main/docs/content/storage.mdx Install the Convex package using npm. ```bash npm i convex ``` -------------------------------- ### Install Postgres Driver (pnpm) Source: https://github.com/zeative/zaileys/blob/main/docs/content/storage.mdx Install the pg package using pnpm. ```bash pnpm add pg ``` -------------------------------- ### Install Missing Peer Dependencies for Adapters Source: https://github.com/zeative/zaileys/blob/main/docs/content/troubleshooting.mdx Install the specific database driver required by your chosen auth or store adapter. Missing drivers result in a `STORE_NOT_AVAILABLE` error. ```bash pnpm add better-sqlite3 # or: pg | redis | convex ``` -------------------------------- ### Install SQLite, PostgreSQL, Redis, and Convex Adapters with bun Source: https://github.com/zeative/zaileys/blob/main/docs/content/installation.mdx Install optional peer dependencies for various storage adapters using bun. These are only needed if you intend to use the corresponding adapter. ```bash bun add better-sqlite3 # SQLite adapters bun add pg # PostgreSQL adapters bun add redis # Redis adapters bun add convex # Convex adapters ``` -------------------------------- ### Install Sharp Image Processor Source: https://github.com/zeative/zaileys/blob/main/docs/content/media.mdx Install the sharp package for accelerated image processing. If sharp is not installed, Zaileys will fall back to jimp. ```bash npm i sharp ``` ```bash pnpm add sharp ``` ```bash yarn add sharp ``` ```bash bun add sharp ``` -------------------------------- ### Install SQLite, PostgreSQL, Redis, and Convex Adapters with npm Source: https://github.com/zeative/zaileys/blob/main/docs/content/installation.mdx Install optional peer dependencies for various storage adapters using npm. These are only needed if you intend to use the corresponding adapter. ```bash npm i better-sqlite3 # SQLite adapters npm i pg # PostgreSQL adapters npm i redis # Redis adapters npm i convex # Convex adapters ``` -------------------------------- ### v3 Client Instantiation Source: https://github.com/zeative/zaileys/blob/main/MIGRATION.md Example of how to instantiate the v3 Zaileys client with various options. ```typescript import { Client } from 'zaileys' const wa = new Client({ session: 'zaileys', authType: 'qr', prefix: '/', showLogs: true, fancyLogs: false, }) ``` -------------------------------- ### Install Storage Adapter Drivers (npm) Source: https://github.com/zeative/zaileys/blob/main/docs/content/runtimes.mdx Install the necessary npm packages for specific Zaileys storage adapters. Choose the driver corresponding to your chosen backend (SQLite, Postgres, Redis). ```bash npm i better-sqlite3 # SQLite npm i pg # Postgres npm i redis # Redis ``` -------------------------------- ### Install Convex with yarn Source: https://github.com/zeative/zaileys/blob/main/docs/content/storage.mdx Install the Convex package using yarn. ```bash yarn add convex ``` -------------------------------- ### Install Redis Driver (yarn) Source: https://github.com/zeative/zaileys/blob/main/docs/content/storage.mdx Install the redis package using yarn. ```bash yarn add redis ``` -------------------------------- ### Install Redis Driver (pnpm) Source: https://github.com/zeative/zaileys/blob/main/docs/content/storage.mdx Install the redis package using pnpm. ```bash pnpm add redis ``` -------------------------------- ### Install Redis Driver (npm) Source: https://github.com/zeative/zaileys/blob/main/docs/content/storage.mdx Install the redis package using npm. ```bash npm i redis ``` -------------------------------- ### Install Node.js and Build Tools in Termux Source: https://github.com/zeative/zaileys/blob/main/docs/content/runtimes.mdx Set up Termux by updating packages and installing Node.js LTS, Python, Make, Clang, and FFmpeg. These are necessary for running Zaileys and compiling optional native modules. ```bash pkg update && pkg upgrade pkg install nodejs-lts python make clang ffmpeg ``` -------------------------------- ### Install sharp image acceleration with bun Source: https://github.com/zeative/zaileys/blob/main/docs/content/installation.mdx Install the optional `sharp` package for native image acceleration using bun. Zaileys falls back to a pure-JS implementation if `sharp` is not found. ```bash bun add sharp ``` -------------------------------- ### Initialize Client with CommonJS Source: https://github.com/zeative/zaileys/blob/main/docs/content/runtimes.mdx Example of initializing the Zaileys client using CommonJS syntax and handling connection events. ```javascript const { Client } = require('zaileys') const client = new Client({ authType: 'pairing', phoneNumber: 628000000000, }) client.on('connection', ({ status }) => console.log(status)) client.connect() ``` -------------------------------- ### Install Storage Adapter Drivers (bun) Source: https://github.com/zeative/zaileys/blob/main/docs/content/runtimes.mdx Install the necessary bun packages for specific Zaileys storage adapters. Choose the driver corresponding to your chosen backend (SQLite, Postgres, Redis). ```bash bun add better-sqlite3 bun add pg bun add redis ``` -------------------------------- ### Initialize Client with PostgresAuthStore Source: https://github.com/zeative/zaileys/blob/main/_autodocs/api-reference/storage.md Example of creating a Zaileys client using PostgresAuthStore for authentication, specifying database credentials. ```typescript import { Client, PostgresAuthStore } from 'zaileys' const client = new Client({ auth: new PostgresAuthStore({ database: 'zaileys', user: 'postgres', password: 'secret', }), }) ``` -------------------------------- ### Install better-sqlite3 Source: https://github.com/zeative/zaileys/blob/main/docs/content/storage.mdx Install the 'better-sqlite3' peer dependency for SQLite adapter functionality. ```bash npm i better-sqlite3 ``` ```bash pnpm add better-sqlite3 ``` ```bash yarn add better-sqlite3 ``` ```bash bun add better-sqlite3 ``` -------------------------------- ### Install sharp image acceleration with npm Source: https://github.com/zeative/zaileys/blob/main/docs/content/installation.mdx Install the optional `sharp` package for native image acceleration using npm. Zaileys falls back to a pure-JS implementation if `sharp` is not found. ```bash npm i sharp ``` -------------------------------- ### Install sharp image acceleration with pnpm Source: https://github.com/zeative/zaileys/blob/main/docs/content/installation.mdx Install the optional `sharp` package for native image acceleration using pnpm. Zaileys falls back to a pure-JS implementation if `sharp` is not found. ```bash pnpm add sharp ``` -------------------------------- ### Initialize Client with ESM/TypeScript Source: https://github.com/zeative/zaileys/blob/main/docs/content/runtimes.mdx Example of initializing the Zaileys client using ESM syntax and handling connection events. ```typescript import { Client } from 'zaileys' const client = new Client({ authType: 'pairing', phoneNumber: 628000000000, }) client.on('connection', ({ status }) => console.log(status)) await client.connect() ``` -------------------------------- ### Install Zaileys with npm Source: https://github.com/zeative/zaileys/blob/main/docs/content/installation.mdx Use npm to install the zaileys package. This is the standard method for Node.js projects. ```bash npm i zaileys ``` -------------------------------- ### Initialize Client with RedisAuthStore Source: https://github.com/zeative/zaileys/blob/main/_autodocs/api-reference/storage.md Example of creating a Zaileys client using RedisAuthStore for authentication, providing the Redis connection URL. ```typescript import { Client, RedisAuthStore } from 'zaileys' const client = new Client({ auth: new RedisAuthStore({ url: 'redis://localhost:6379' }), }) ``` -------------------------------- ### QR Authentication Example Source: https://github.com/zeative/zaileys/blob/main/_autodocs/configuration.md Instantiates a client using QR code scanning for authentication. ```typescript const client = new Client({ authType: 'qr' }) ``` -------------------------------- ### v3 Plugin Example Source: https://github.com/zeative/zaileys/blob/main/MIGRATION.md Example of a v3 plugin using `definePlugins` to send a message. ```typescript import { definePlugins } from 'zaileys' export default definePlugins( async (wa, ctx) => { await wa.send(ctx.messages.roomId, 'Hello from plugin!') }, { matcher: ['/hello'], metadata: { description: 'hello plugin' } }, ) ``` -------------------------------- ### Install Deno dependencies Source: https://github.com/zeative/zaileys/blob/main/docs/content/runtimes.mdx Install npm dependencies for Deno to use with the `--node-modules-dir` flag. ```bash deno cache --node-modules-dir npm:zaileys ``` -------------------------------- ### Install Storage Adapter Drivers (yarn) Source: https://github.com/zeative/zaileys/blob/main/docs/content/runtimes.mdx Install the necessary yarn packages for specific Zaileys storage adapters. Choose the driver corresponding to your chosen backend (SQLite, Postgres, Redis). ```bash yarn add better-sqlite3 yarn add pg yarn add redis ``` -------------------------------- ### Install sharp image acceleration with yarn Source: https://github.com/zeative/zaileys/blob/main/docs/content/installation.mdx Install the optional `sharp` package for native image acceleration using yarn. Zaileys falls back to a pure-JS implementation if `sharp` is not found. ```bash yarn add sharp ``` -------------------------------- ### Install SQLite, PostgreSQL, Redis, and Convex Adapters with pnpm Source: https://github.com/zeative/zaileys/blob/main/docs/content/installation.mdx Install optional peer dependencies for various storage adapters using pnpm. These are only needed if you intend to use the corresponding adapter. ```bash pnpm add better-sqlite3 # SQLite adapters pnpm add pg # PostgreSQL adapters pnpm add redis # Redis adapters pnpm add convex # Convex adapters ``` -------------------------------- ### Install Storage Adapter Drivers (pnpm) Source: https://github.com/zeative/zaileys/blob/main/docs/content/runtimes.mdx Install the necessary pnpm packages for specific Zaileys storage adapters. Choose the driver corresponding to your chosen backend (SQLite, Postgres, Redis). ```bash pnpm add better-sqlite3 pnpm add pg pnpm add redis ``` -------------------------------- ### Install Zaileys Package Source: https://github.com/zeative/zaileys/blob/main/README.md Install the Zaileys package using your preferred package manager. Node.js v20+ is required. ```bash npm i zaileys # or: pnpm add zaileys β€’ yarn add zaileys β€’ bun add zaileys ``` -------------------------------- ### v4 Client Instantiation Source: https://github.com/zeative/zaileys/blob/main/MIGRATION.md Example of how to instantiate the v4 Zaileys client, which auto-connects on construction. ```typescript import { Client } from 'zaileys' const client = new Client({ sessionId: 'zaileys', authType: 'qr', commandPrefix: '/', }) ``` -------------------------------- ### Run Bot with bun Source: https://github.com/zeative/zaileys/blob/main/docs/content/getting-started.mdx Execute the bot file using bun. This is one of the methods to run your bot after setup. ```bash bun run bot.ts ``` -------------------------------- ### Install SQLite, PostgreSQL, Redis, and Convex Adapters with yarn Source: https://github.com/zeative/zaileys/blob/main/docs/content/installation.mdx Install optional peer dependencies for various storage adapters using yarn. These are only needed if you intend to use the corresponding adapter. ```bash yarn add better-sqlite3 # SQLite adapters yarn add pg # PostgreSQL adapters yarn add redis # Redis adapters yarn add convex # Convex adapters ``` -------------------------------- ### Initialize Client with FileAuthStore Source: https://github.com/zeative/zaileys/blob/main/_autodocs/api-reference/storage.md Example of creating a Zaileys client using FileAuthStore for authentication, specifying a custom base path. ```typescript import { Client, FileAuthStore } from 'zaileys' const client = new Client({ auth: new FileAuthStore({ basePath: './auth' }), }) ``` -------------------------------- ### Full Rich Response Example Source: https://github.com/zeative/zaileys/blob/main/docs/content/rich-responses.mdx A comprehensive example showcasing various markdown elements including text, links, code blocks, tables, and metadata like title, footer, and sources. ```typescript await client.send('628xxx@s.whatsapp.net').text( [ '*Daily brief* β˜•', '', 'Repo: [GitHub](https://github.com/zeative/zaileys)', 'A citation: [](https://github.com/zeative/zaileys)', '', '```ts', "const client = new Client()", '```', '', '| Feature | Status |', '|---|---| | Buttons | Ready |', '| AIRich | Experimental |', ].join('\n'), { rich: true, title: 'πŸ“° zaileys Daily', footer: 'πŸ’‘ Dibuat dengan zaileys β€” github.com/zeative/zaileys', sources: [ ['https://avatars.githubusercontent.com/u/9919?s=64', 'https://github.com/zeative/zaileys', 'zaileys on GitHub'], ], }, ) ``` -------------------------------- ### Initialize Client with SqliteAuthStore Source: https://github.com/zeative/zaileys/blob/main/_autodocs/api-reference/storage.md Example of creating a Zaileys client using SqliteAuthStore for authentication, specifying the database file path. ```typescript import { Client, SqliteAuthStore } from 'zaileys' const client = new Client({ auth: new SqliteAuthStore({ database: './auth.db' }), }) ``` -------------------------------- ### Initialize Client with MemoryAuthStore Source: https://github.com/zeative/zaileys/blob/main/_autodocs/api-reference/storage.md Example of creating a Zaileys client using MemoryAuthStore for authentication. ```typescript import { Client, MemoryAuthStore } from 'zaileys' const client = new Client({ auth: new MemoryAuthStore(), }) ``` -------------------------------- ### Basic RateLimiter Usage Source: https://github.com/zeative/zaileys/blob/main/_autodocs/api-reference/automation.md Example demonstrating how to initialize a RateLimiter and process items with a global rate limit. ```typescript const limiter = new RateLimiter({ perSec: 5 }) // Process 100 items with rate limit for (let i = 0; i < 100; i++) { await limiter.acquire() console.log(`Processing ${i}`) } ``` -------------------------------- ### Install Zaileys with bun Source: https://github.com/zeative/zaileys/blob/main/docs/content/installation.mdx Use bun to add the zaileys package. bun is a fast all-in-one JavaScript runtime. ```bash bun add zaileys ``` -------------------------------- ### Production Setup with Persistence Source: https://github.com/zeative/zaileys/blob/main/_autodocs/configuration.md Configure Zaileys for production with session ID, SQL authentication, and message storage. Includes custom reconnect settings and logger. ```typescript import { Client, SqliteAuthStore, SqliteMessageStore } from 'zaileys' const client = new Client({ sessionId: 'production-bot', auth: new SqliteAuthStore({ database: './auth.db' }), store: new SqliteMessageStore({ database: './messages.db' }), commandPrefix: '/', reconnect: { enabled: true, maxAttempts: 10, initialDelayMs: 2000, }, statusLog: true, logger: { debug: () => {}, // Suppress debug logs info: (msg) => console.log('[INFO]', msg), warn: (msg) => console.warn('[WARN]', msg), error: (err) => console.error('[ERROR]', err), fatal: (err) => console.error('[FATAL]', err), }, }) ``` -------------------------------- ### Initialize Client with MemoryMessageStore Source: https://github.com/zeative/zaileys/blob/main/_autodocs/api-reference/storage.md Example of creating a Zaileys client using the default MemoryMessageStore for message storage. ```typescript import { Client, MemoryMessageStore } from 'zaileys' const client = new Client({ store: new MemoryMessageStore(), }) ``` -------------------------------- ### RateLimiter with Per-JID Limiting Source: https://github.com/zeative/zaileys/blob/main/_autodocs/api-reference/automation.md Example showing how to configure and use a RateLimiter for per-token (JID) limiting. ```typescript const limiter = new RateLimiter({ perSec: 10, // 10 total/sec perJidPerSec: 2, // 2 per JID/sec }) // Acquire for specific JID await limiter.acquire('user1@s.whatsapp.net') ``` -------------------------------- ### Get Group Metadata Source: https://github.com/zeative/zaileys/blob/main/docs/content/api-reference.mdx Retrieve metadata for a specific group using its JID. This is an example of interacting with the group domain module. ```typescript const meta = await client.group.metadata('xxx@g.us') ``` -------------------------------- ### Redis-Backed Zaileys Setup Source: https://github.com/zeative/zaileys/blob/main/_autodocs/configuration.md Configure Zaileys to use Redis for authentication and message storage. Requires a running Redis instance. ```typescript import { Client, RedisAuthStore, RedisMessageStore } from 'zaileys' const client = new Client({ auth: new RedisAuthStore({ url: 'redis://localhost:6379' }), store: new RedisMessageStore({ url: 'redis://localhost:6379' }), reconnect: { maxAttempts: 10 }, }) ``` -------------------------------- ### Flag Parsing Example Source: https://github.com/zeative/zaileys/blob/main/_autodocs/api-reference/command-handling.md Demonstrates how flags starting with '--' are parsed into a key-value object. Boolean flags are represented as true. ```plaintext /search query --limit 10 --sort date ↓ args: ['query'] flags: { limit: '10', sort: 'date' } ``` ```plaintext /toggle --enabled ↓ flags: { enabled: true } ``` -------------------------------- ### Run Bot with ts-node Source: https://github.com/zeative/zaileys/blob/main/docs/content/getting-started.mdx Execute the bot file using ts-node. This is one of the methods to run your bot after setup. ```bash npx ts-node bot.ts ``` -------------------------------- ### TaskQueue Usage with Retry Policy Source: https://github.com/zeative/zaileys/blob/main/_autodocs/api-reference/automation.md Example demonstrating how to initialize a TaskQueue with concurrency and a retry policy, then add tasks. ```typescript const queue = new TaskQueue({ concurrency: 3, retry: { maxRetries: 3, backoffMs: (attempt) => Math.pow(2, attempt) * 1000, // exponential backoff }, }) for (const url of urls) { queue.add(() => fetch(url)) } ``` -------------------------------- ### Run Bot with tsx Source: https://github.com/zeative/zaileys/blob/main/docs/content/getting-started.mdx Execute the bot file using tsx. This is one of the methods to run your bot after setup. ```bash npx tsx bot.ts ``` -------------------------------- ### Pairing Code Authentication Example Source: https://github.com/zeative/zaileys/blob/main/_autodocs/configuration.md Instantiates a client using phone number and pairing code for authentication. Requires phoneNumber. ```typescript const client = new Client({ authType: 'pairing', phoneNumber: '6281234567890', // With country code, no + }) ``` -------------------------------- ### Multi-Session Zaileys Setup Source: https://github.com/zeative/zaileys/blob/main/_autodocs/configuration.md Set up multiple independent Zaileys clients, each with its own session ID. Each bot manages its own authentication, storage, and lifecycle. ```typescript const botA = new Client({ sessionId: 'bot-a' }) const botB = new Client({ sessionId: 'bot-b' }) botA.on('text', (msg) => msg.reply('Bot A')) botB.on('text', (msg) => msg.reply('Bot B')) // Each has separate auth, storage, and lifecycle ``` -------------------------------- ### Install Convex Peer Dependency Source: https://github.com/zeative/zaileys/blob/main/examples/convex/README.md Install the 'convex' package as a peer dependency for your project. ```bash pnpm add convex ``` -------------------------------- ### Media Processing with Zaileys Source: https://github.com/zeative/zaileys/blob/main/docs/content/api-reference.mdx Demonstrates how to initialize the Media class and perform audio and video processing tasks like converting to Opus and generating thumbnails. ```typescript import { Media } from 'zaileys' const m = new Media('./input.mp3') const opus = await m.audio.toOpus() const thumb = await m.video.thumbnail() ``` -------------------------------- ### Conventional Commit Example Source: https://github.com/zeative/zaileys/blob/main/CONTRIBUTING.md An example of a commit message following the Conventional Commits format. ```bash feat(builder): add album() chaining for media groups ``` -------------------------------- ### Initialize Zaileys Client in Deno Source: https://github.com/zeative/zaileys/blob/main/docs/content/runtimes.mdx Import and connect to Zaileys using the `npm:` specifier in Deno. Ensure you have granted the necessary permissions for file access, network, and running child processes. ```typescript import { Client } from 'npm:zaileys' const client = new Client({ authType: 'qr' }) await client.connect() ``` -------------------------------- ### Custom Session ID Example Source: https://github.com/zeative/zaileys/blob/main/docs/content/troubleshooting.mdx Example of how to specify a custom session ID when initializing the Zaileys client. The auth data will be stored in a subfolder corresponding to this ID. ```typescript import { Client } from 'zaileys' const client = new Client({ sessionId: 'mybot' }) // auth lives at ./.zaileys/auth/mybot ``` -------------------------------- ### Command Registration and Handling Source: https://github.com/zeative/zaileys/blob/main/_autodocs/README.md Illustrates how to register custom commands with a specified prefix, define command handlers, and implement middleware for pre-processing command execution. ```APIDOC ## Command Registration and Handling ### Description This section details how to set up command handling within Zaileys. You can define a prefix for commands and register individual commands with their respective handler functions. Middleware can also be applied to execute logic before or after command execution. ### Method `client.command(name, handler)` `client.use(middleware)` ### Endpoint N/A ### Parameters - `client.command`: - `name` (string): The name of the command. - `handler` (function): The function to execute when the command is invoked. - `client.use`: - `middleware` (function): A middleware function that takes context and a `next` callback. ### Request Example ```typescript const client = new Client({ commandPrefix: '/' }) client.command('ping', async (ctx) => { await ctx.reply('pong πŸ“') }) client.command('echo message', async (ctx) => { await ctx.reply(ctx.args.join(' ')) }) client.use(async (ctx, next) => { console.log(`Command: /${ctx.command}`) await next() }) ``` ### Response N/A (Command execution results in message replies or console logs) ``` -------------------------------- ### Complete Zaileys Client Lifecycle Source: https://github.com/zeative/zaileys/blob/main/docs/content/client.mdx This snippet demonstrates initializing a Zaileys client, setting up event listeners for various states (QR, reconnecting, error, connect, text), sending messages, reacting to them, and handling graceful shutdown with SIGINT. ```typescript import { Client } from 'zaileys' const client = new Client({ sessionId: 'demo', autoConnect: false }) client.on('qr', ({ qrString }) => console.log('Scan QR:', qrString)) client.on('reconnecting', ({ attempt, delayMs }) => console.log(`reconnecting #${attempt} in ${delayMs}ms`), ) client.on('error', ({ error }) => console.error('client error:', error.message)) client.on('connect', async ({ me }) => { console.log('connected as', me.id) await client.presence.online() }) client.on('text', async (ctx) => { if (ctx.text?.toLowerCase() === 'ping') { const key = await client.send(ctx.roomId).text('pong') await client.react(key, 'πŸ“') } }) await client.connect() // later, on shutdown: process.on('SIGINT', async () => { await client.disconnect() process.exit(0) }) ``` -------------------------------- ### Help Command Display Source: https://github.com/zeative/zaileys/blob/main/_autodocs/api-reference/command-handling.md Create a command to display available commands and their usage instructions. Usage: /help or /h ```typescript client.command('help h', async (ctx) => { const help = [ '*Available Commands:*', '', '*/ping* - Check if bot is alive', '*/greet [name] [age]* - Greet someone', '*/list [--limit N] [--sort field]* - List items', '*/help* - Show this help', ].join('\n') await ctx.reply(help) }) // Usage: /help or /h ``` -------------------------------- ### Command Router with Middleware Source: https://github.com/zeative/zaileys/blob/main/docs/content/index.mdx Sets up a client with command prefixes and registers middleware for logging. Includes examples for a simple 'ping' command and a 'weather' command with arguments. ```typescript import { Client, type Middleware } from 'zaileys' const client = new Client({ commandPrefix: ['/', '!'] }) const logging: Middleware = async (ctx, next) => { console.log(`[command] ${ctx.command} from ${ctx.senderId}`) await next() } client.use(logging) client.command('ping', async (ctx) => ctx.reply('pong')) client.command('weather', async (ctx) => { const city = ctx.args[0] await ctx.reply(city ? `Weather in ${city}: sunny, 28Β°` : 'Usage: /weather ') }) ``` -------------------------------- ### client.community.inviteCode Source: https://github.com/zeative/zaileys/blob/main/docs/content/client.mdx Get the invite code. ```APIDOC ## client.community.inviteCode ### Description Get the invite code. ### Method GET ### Endpoint /community/inviteCode ### Parameters #### Query Parameters - **communityId** (string) - Required - The ID of the community. ### Response #### Success Response (200) - **string | undefined** - The invite code, or undefined if none exists. ``` -------------------------------- ### Get Room Name Source: https://github.com/zeative/zaileys/blob/main/docs/content/events.mdx Retrieve the subject of the group chat. ```APIDOC ## roomName() ### Description The group subject when in a group, else `null`. Cached per room. ### Method `roomName(): Promise` ### Returns - `Promise` - A promise that resolves to the group subject string, or `null` if not in a group. ### Request Example ```typescript client.on('text', async (msg) => { const groupName = await msg.roomName() if (groupName) { console.log(`This message is from group: ${groupName}`) } }) ``` ``` -------------------------------- ### Get Receiver Name Source: https://github.com/zeative/zaileys/blob/main/docs/content/events.mdx Retrieve your own account's display name. ```APIDOC ## receiverName() ### Description Your own account's display name. ### Method `receiverName(): Promise` ### Returns - `Promise` - A promise that resolves to your account's display name, or `null` if not available. ### Request Example ```typescript client.on('text', async (msg) => { const myName = await msg.receiverName() console.log(`My display name is: ${myName}`) }) ``` ``` -------------------------------- ### SqliteAuthStore and SqliteMessageStore Example Source: https://github.com/zeative/zaileys/blob/main/docs/content/storage.mdx Configure SqliteAuthStore and SqliteMessageStore using a SQLite database file. Both stores auto-create their tables on first use and store buffers serialized with BufferJSON. ```typescript import { Client, SqliteAuthStore, SqliteMessageStore } from 'zaileys' const client = new Client({ auth: new SqliteAuthStore({ database: './auth.db' }), store: new SqliteMessageStore({ database: './history.db' }), }) ``` -------------------------------- ### Get Replied Message Source: https://github.com/zeative/zaileys/blob/main/docs/content/events.mdx Retrieve the context of the message that this message is a reply to. ```APIDOC ## replied() ### Description Resolve the quoted message (the one this message replied to) as a full context, or `null` if none. ### Method `replied(): Promise` ### Returns - `Promise` - A promise that resolves to the `MessageContext` of the quoted message, or `null` if there is no quoted message. ### Request Example ```typescript client.on('text', async (msg) => { const quoted = await msg.replied() if (quoted) { console.log('In reply to:', quoted.senderId, '|', quoted.text) await msg.reply(`You quoted: "${quoted.text}"`) } }) ``` ``` -------------------------------- ### get() Source: https://github.com/zeative/zaileys/blob/main/_autodocs/api-reference/privacy-module.md Fetches current privacy settings. Requires the client to be connected. ```APIDOC ## get() ### Description Fetches current privacy settings. Requires the client to be connected. ### Method `get(): Promise` ### Response #### Success Response (200) - **PrivacySettings** (object) - Dictionary of privacy setting values. ### Request Example ```typescript const settings = await client.privacy.get() console.log('Current settings:', settings) ``` ``` -------------------------------- ### Media Processing - Resize Source: https://github.com/zeative/zaileys/blob/main/docs/public/llms.txt Resize images using the 'sharp' library (if installed) or 'jimp'. ```typescript import { Media } from 'zaileys'; await Media.resize('input.jpg', 'output.jpg', { width: 500, height: 500 }); ``` -------------------------------- ### Connect the Client Source: https://github.com/zeative/zaileys/blob/main/docs/content/interactive.mdx Initialize the Zaileys client and set up a listener for the 'qr' event to display the QR code for authentication. ```typescript import { Client } from 'zaileys' const client = new Client() client.on('qr', ({ qrString }) => console.log('Scan QR:', qrString)) ``` -------------------------------- ### Client Initialization and Message Handling Source: https://github.com/zeative/zaileys/blob/main/_autodocs/README.md Demonstrates how to create a new Zaileys client instance, listen for connection events like QR code generation and successful connection, and handle incoming text messages by replying with an echo. ```APIDOC ## Client Initialization and Message Handling ### Description This example shows the basic setup for a Zaileys client. It includes listening for essential events such as `qr` for scanning and `connect` for confirming the connection. It also demonstrates a common pattern for replying to incoming text messages. ### Method N/A (Client Initialization and Event Listeners) ### Endpoint N/A ### Parameters N/A ### Request Example ```typescript import { Client } from 'zaileys' const client = new Client() client.on('qr', ({ qrString }) => console.log('Scan:', qrString)) client.on('connect', ({ me }) => console.log('Connected as:', me.id)) client.on('text', async (msg) => { await msg.reply(`Echo: ${msg.text}`) }) ``` ### Response N/A (Event-driven responses) ``` -------------------------------- ### Get Raw Message Object Source: https://github.com/zeative/zaileys/blob/main/docs/content/events.mdx Access the raw underlying Baileys message object. ```APIDOC ## message() ### Description The raw underlying Baileys message object (escape hatch). ### Method `message(): WAMessage` ### Returns - `WAMessage` - The raw Baileys message object. ### Request Example ```typescript client.on('text', async (msg) => { const rawMessage = msg.message() console.log('Raw message object:', rawMessage) }) ``` ``` -------------------------------- ### RedisAuthStore Constructor Source: https://github.com/zeative/zaileys/blob/main/_autodocs/api-reference/storage.md Initializes a Redis-based authentication store. Requires the 'redis' peer dependency. ```typescript class RedisAuthStore implements AuthStoreBundle { constructor(options: RedisAuthStoreOptions) } ``` -------------------------------- ### Install Zaileys with pnpm Source: https://github.com/zeative/zaileys/blob/main/docs/content/installation.mdx Use pnpm to add the zaileys package. pnpm is a fast, disk-space-efficient package manager. ```bash pnpm add zaileys ``` -------------------------------- ### Presence Automation Example Source: https://github.com/zeative/zaileys/blob/main/docs/content/automation.mdx Demonstrates how to manage account presence and send typing indicators. This requires an active connection to the Zaileys service. The `typing` method can optionally auto-clear after a specified duration. ```typescript import { Client } from 'zaileys' const client = new Client() const jid = '6281111111111@s.whatsapp.net' client.on('connect', async () => { await client.presence.online() // mark account as online await client.presence.typing(jid) // show "typing…" in that chat await client.send(jid).text('Hi! Thanks for waiting.') }) ``` ```typescript // Simulate a natural typing delay before replying. await client.presence.typing(jid, 2000) // auto-clears after 2s setTimeout(() => client.send(jid).text('Done thinking!'), 2000) ``` -------------------------------- ### Create Zaileys Client and Listen for Messages Source: https://github.com/zeative/zaileys/blob/main/_autodocs/README.md Initialize the Client and set up event listeners for QR code generation, connection status, and incoming text messages. Use this to start your Zaileys application and handle basic message echoing. ```typescript import { Client } from 'zaileys' const client = new Client() client.on('qr', ({ qrString }) => console.log('Scan:', qrString)) client.on('connect', ({ me }) => console.log('Connected as:', me.id)) client.on('text', async (msg) => { await msg.reply(`Echo: ${msg.text}`) }) ``` -------------------------------- ### Handle ZaileysAutomationError on Schedule Source: https://github.com/zeative/zaileys/blob/main/docs/content/error-handling.mdx Catch and inspect ZaileysAutomationError when scheduling tasks. This example specifically checks for the 'SCHEDULE_INVALID' code. ```typescript import { Client, ZaileysAutomationError } from 'zaileys' const client = new Client() client.on('connect', async () => { try { await client.scheduleAt( new Date(Date.now() + 60_000), (b) => b.text('Reminder: standup in 1 minute.'), ) } catch (err) { if (err instanceof ZaileysAutomationError && err.code === 'SCHEDULE_INVALID') { console.error('Bad schedule:', err.message) } } }) ``` -------------------------------- ### Creating a Changeset Source: https://github.com/zeative/zaileys/blob/main/CONTRIBUTING.md Generate a changeset to document changes for versioning and changelog generation. Use '--empty' for docs-only or chore PRs. ```bash pnpm changeset # choose bump (patch / minor / major) + describe the change ``` ```bash pnpm changeset --empty ``` -------------------------------- ### Initialize Zaileys Client and Listen for Connection Source: https://github.com/zeative/zaileys/blob/main/docs/content/client.mdx Instantiate the Zaileys Client with a session ID and log a message when the client successfully connects. ```typescript import { Client } from 'zaileys' const client = new Client({ sessionId: 'default' }) client.on('connect', ({ me }) => console.log('ready as', me.id)) ``` -------------------------------- ### JSON Parsing Example Source: https://github.com/zeative/zaileys/blob/main/_autodocs/api-reference/command-handling.md Shows how the last argument, if it's valid JSON, is automatically parsed into a JavaScript object. ```plaintext /process {"key":"value"} ↓ args: [] json: { key: 'value' } ``` ```plaintext /api data --format json '{"id":123}' ↓ args: ['data'] flags: { format: 'json' } json: { id: 123 } ``` -------------------------------- ### Initialize Zaileys Client with Pre-built Convex Client Source: https://github.com/zeative/zaileys/blob/main/examples/convex/README.md Initialize the Zaileys client using an existing ConvexHttpClient instance. This is useful if you already have a Convex client set up. ```typescript import { ConvexHttpClient } from 'convex/browser' import { ConvexAuthStore } from 'zaileys' const convex = new ConvexHttpClient(process.env.CONVEX_URL!) new ConvexAuthStore({ client: convex, namespace: 'wa-auth' }) ``` -------------------------------- ### Handle Client Events Source: https://github.com/zeative/zaileys/blob/main/_autodocs/api-reference/client.md Listen for various client events such as connection status, QR code generation, and inbound messages. This example shows how to handle 'connect', 'text', and 'error' events. ```typescript client.on('connect', ({ me }) => { console.log(`Connected as ${me.name} (${me.id})`) }) client.on('text', async (msg) => { if (msg.text.startsWith('!')) return await msg.reply(`Echoing: ${msg.text}`) }) client.on('error', ({ error }) => { console.error('Unexpected error:', error) }) ``` -------------------------------- ### Handle Connection Event Source: https://github.com/zeative/zaileys/blob/main/docs/content/events.mdx Fires when the socket is authenticated and ready. Use this to start operations requiring an active connection. ```typescript client.on('connect', async ({ sessionId, me }) => { console.log(`[${sessionId}] connected as ${me.id}${me.name ? ` (${me.name})` : ''}`) }) ```