### Full Command Bot Example Source: https://github.com/arcaelas/whatsapp/blob/main/docs/examples/command-bot.md This is a complete example of a command bot. It sets up message handlers for commands like /help, /ping, /info, and /echo. Ensure you have the necessary imports and engine setup. ```typescript import { join } from 'node:path'; import { WhatsApp, FileSystemEngine, type Message, type Chat } from '@arcaelas/whatsapp'; const PREFIX = '/'; type CommandHandler = (args: string, msg: Message, chat: Chat) => Promise; const wa = new WhatsApp({ engine: new FileSystemEngine(join(__dirname, 'session')), phone: 584144709840, }); const commands = new Map(); commands.set('help', async (_args, msg) => { await msg.text( [ 'Available commands:', ' /help — show this message', ' /ping — health check', ' /info — chat metadata', ' /echo — repeat ', ].join('\n'), ); }); commands.set('ping', async (_args, msg) => { await msg.text('pong'); }); commands.set('info', async (_args, msg, chat) => { const total = await wa.Message.count(chat.id); await msg.text( [ `chat: ${chat.name}`, `id: ${chat.id}`, `type: ${chat.type}`, `stored: ${total} messages`, ].join('\n'), ); }); commands.set('echo', async (args, msg) => { if (!args) { await msg.text('usage: /echo '); return; } await msg.text(args); }); wa.on('message:created', async (msg, chat) => { if (msg.me) { return; } const text = msg.caption.trim(); if (!text.startsWith(PREFIX)) { return; } const space = text.indexOf(' '); const name = (space === -1 ? text.slice(PREFIX.length) : text.slice(PREFIX.length, space)).toLowerCase(); const args = space === -1 ? '' : text.slice(space + 1).trim(); const handler = commands.get(name); if (!handler) { await msg.text(`unknown command: /${name} — try /help`); return; } try { await handler(args, msg, chat); } catch (err) { console.error(`[cmd:${name}] failed`, err); await msg.text('internal error'); } }); process.on('SIGINT', async () => { await wa.disconnect(); process.exit(0); }); wa.connect((auth) => { if (typeof auth === 'string') { console.log(`[wa] pairing code: ${auth}`); } else { console.log('[wa] scan the QR (PNG buffer received)'); } }).catch((err) => { console.error('[wa] connect failed:', err); process.exit(1); }); ``` -------------------------------- ### Integrating LoggingEngine with FileSystemEngine Source: https://github.com/arcaelas/whatsapp/blob/main/docs/examples/custom-engine.md This example shows how to instantiate the `LoggingEngine` and wrap a `FileSystemEngine`. The `WhatsApp` client is then configured to use this logging engine. This setup ensures that all interactions with the file system engine are logged. ```typescript import { join } from 'node:path'; import { WhatsApp, FileSystemEngine } from '@arcaelas/whatsapp'; import { LoggingEngine } from './logging-engine'; const wa = new WhatsApp({ engine: new LoggingEngine( new FileSystemEngine(join(__dirname, 'session')), 'fs', ), phone: 584144709840, }); ``` -------------------------------- ### Install with npm Source: https://github.com/arcaelas/whatsapp/wiki/Installation Use this command to install the library using npm. ```bash npm install @arcaelas/whatsapp ``` -------------------------------- ### Install with pnpm Source: https://github.com/arcaelas/whatsapp/wiki/Installation Use this command to install the library using pnpm. ```bash pnpm add @arcaelas/whatsapp ``` -------------------------------- ### Install with yarn Source: https://github.com/arcaelas/whatsapp/wiki/Installation Use this command to install the library using yarn. ```bash yarn add @arcaelas/whatsapp ``` -------------------------------- ### Create Project and Install Dependencies Source: https://github.com/arcaelas/whatsapp/wiki/Getting-Started Sets up a new project directory, initializes npm, and installs the necessary Arcaelas WhatsApp library and TypeScript tools. ```bash mkdir my-whatsapp-bot cd my-whatsapp-bot npm init -y npm install @arcaelas/whatsapp typescript tsx ``` -------------------------------- ### Command Bot Usage Examples Source: https://github.com/arcaelas/whatsapp/wiki/Command-Bot-Example Examples of common commands and their expected outputs. ```text !ping → pong! !help → Command list !time → 2:30:45 PM - Monday, January 1, 2025 !say Hello → Hello !dice 20 → 20-sided dice: 15 !group → Group information ``` -------------------------------- ### Chat Management Examples Source: https://github.com/arcaelas/whatsapp/wiki/API-Reference Examples demonstrating how to get, list, pin, archive, mute, and mark chats as read using the Chat class. ```typescript // Get chat const chat = await wa.Chat.get("5491112345678@s.whatsapp.net"); ``` ```typescript // List chats const chats = await wa.Chat.paginate(0, 50); ``` ```typescript // Pin chat await wa.Chat.pin("5491112345678@s.whatsapp.net", true); ``` ```typescript // Archive chat await wa.Chat.archive("5491112345678@s.whatsapp.net", true); ``` ```typescript // Mute for 8 hours await wa.Chat.mute("5491112345678@s.whatsapp.net", 8 * 60 * 60 * 1000); ``` ```typescript // Mark as read await wa.Chat.seen("5491112345678@s.whatsapp.net"); ``` -------------------------------- ### Verify Installation with TypeScript Source: https://github.com/arcaelas/whatsapp/wiki/Installation Create and run this test file to confirm the library is installed and configured correctly. ```typescript import { WhatsApp, FileEngine } from "@arcaelas/whatsapp"; const wa = new WhatsApp({ engine: new FileEngine(".baileys/test"), }); console.log("Installation successful!"); console.log("Available classes:", { Chat: wa.Chat, Contact: wa.Contact, Message: wa.Message, }); ``` -------------------------------- ### WhatsApp Server Example Source: https://github.com/arcaelas/whatsapp/blob/main/docs/references/whatsapp.md A full server-side example demonstrating how to connect to WhatsApp, handle incoming messages, and manage connection states. Requires IORedis for the RedisEngine. ```typescript import IORedis from 'ioredis'; import { WhatsApp, RedisEngine } from '@arcaelas/whatsapp'; const wa = new WhatsApp({ engine: new RedisEngine(new IORedis(), 'wa:default'), phone: 5491112345678, reconnect: { max: 5, interval: 30 }, autoclean: true, }); wa.on('connected', () => console.log('online')); wa.on('disconnected', () => console.log('offline')); wa.on('message:created', async (msg, chat) => { if (msg.caption === '/ping') { await chat.text('pong'); } }); await wa.connect((pin) => console.log('PIN:', pin)); ``` -------------------------------- ### Install Dependencies Source: https://github.com/arcaelas/whatsapp/blob/main/docs/examples/decorator-bot.md Install the necessary packages for the bot. Redis is used for state persistence, but other engines are supported. ```bash yarn add @arcaelas/whatsapp ioredis ``` -------------------------------- ### Running the Basic Bot Source: https://github.com/arcaelas/whatsapp/blob/main/docs/examples/basic-bot.md This command executes the TypeScript bot example using tsx. Ensure you have tsx installed globally or as a dev dependency. ```bash npx tsx index.ts ``` -------------------------------- ### Bootstrap Project and Install Dependencies Source: https://github.com/arcaelas/whatsapp/blob/main/docs/getting-started.md Initializes a new project directory, sets up a package.json, and installs the @arcaelas/whatsapp package along with development dependencies for TypeScript. ```bash mkdir whatsapp-bot && cd whatsapp-bot yarn init -y yarn add @arcaelas/whatsapp yarn add -D tsx typescript @types/node ``` -------------------------------- ### Install libffi-dev on Debian/Ubuntu Source: https://github.com/arcaelas/whatsapp/wiki/Installation For Linux users experiencing 'libffi.so.7 not found', install the necessary system dependencies. ```bash sudo apt-get install libffi-dev ``` -------------------------------- ### FileSystemEngine Write Operation Example Source: https://github.com/arcaelas/whatsapp/blob/main/docs/schema.md Illustrates the filesystem operations performed when writing a document. Shows directory creation and file writing for a given path. ```text /chat/120363@g.us/message/ABC/index.json ``` -------------------------------- ### Install libffi-devel on CentOS/RHEL Source: https://github.com/arcaelas/whatsapp/wiki/Installation For CentOS/RHEL users experiencing 'libffi.so.7 not found', install the necessary system dependencies. ```bash sudo yum install libffi-devel ``` -------------------------------- ### Install Periodic Timer with @every Source: https://github.com/arcaelas/whatsapp/blob/main/docs/references/decorators.md Use the @every decorator to install a periodic timer. The interval starts when the client is connected and is cleared on disconnection. Timer callbacks receive no arguments. ```typescript import { every } from "@decorator" @every(30_000) async heartbeat() { console.log("tick", Date.now()); } ``` -------------------------------- ### Basic Bot Usage Examples Source: https://github.com/arcaelas/whatsapp/wiki/Basic-Bot-Example These are example messages you can send to the bot and their expected responses. They illustrate the bot's command handling capabilities. ```text hello → Hello! How can I help you? ping → pong! time → Current time: 1/1/2025, 2:30:00 PM help → Available commands list ``` -------------------------------- ### Example Log Output Source: https://github.com/arcaelas/whatsapp/blob/main/docs/examples/custom-engine.md This is an example of the console output generated by the `LoggingEngine` when interacting with the `FileSystemEngine`. It shows the logged operations, paths, and results, aiding in debugging and understanding data flow. ```text [fs] get /session/creds HIT (1842b) [fs] set /chat/584144709840@s.whatsapp.net 73b [fs] list /chat offset=0 limit=50 -> 12 items [fs] count /chat/584144709840@s.whatsapp.net/message -> 47 ``` -------------------------------- ### Install Optional Peer Dependencies Source: https://github.com/arcaelas/whatsapp/blob/main/docs/installation.md Install ioredis if you plan to use the RedisEngine, and @aws-sdk/client-s3 if you plan to use the S3Engine. These are not required for FileSystemEngine or custom engines. ```bash yarn add ioredis # only if you use RedisEngine yarn add @aws-sdk/client-s3 # only if you use S3Engine ``` -------------------------------- ### FileSystemEngine Usage Source: https://github.com/arcaelas/whatsapp/blob/main/docs/references/engines.md Example of how to instantiate and use the FileSystemEngine with the WhatsApp client. Ensure the necessary imports are included. ```typescript import { WhatsApp, FileSystemEngine } from '@arcaelas/whatsapp'; import { join } from 'node:path'; const engine = new FileSystemEngine(join(process.cwd(), 'data', 'wa')); const wa = new WhatsApp({ engine }); await wa.connect((qr) => console.log('QR ready', qr.length, 'bytes')); ``` -------------------------------- ### End-to-end Example Source: https://github.com/arcaelas/whatsapp/blob/main/docs/references/message.md Demonstrates a comprehensive example of using message sending and CRUD operations in a TypeScript application. ```APIDOC ## End-to-end Example ### Description Demonstrates a comprehensive example of using message sending and CRUD operations in a TypeScript application. ### Usage This example shows how to: - Initialize the WhatsApp client. - Send basic text messages, including replies. - Send media messages (image, audio). - Send location and poll messages. - Retrieve message history and perform CRUD operations like editing existing messages. ### Code Example ```typescript import { WhatsApp, FileSystemEngine } from "@arcaelas/whatsapp"; import { readFileSync } from "node:fs"; const wa = new WhatsApp({ engine: new FileSystemEngine({ path: "./.whatsapp" }), }); await wa.connect(); const cid = "5215555555555@s.whatsapp.net"; // Basic text const greeting = await wa.Message.text(cid, "Hello from v3!"); // Reply (mid pins the quoted message) if (greeting) { await wa.Message.text(cid, "And a follow-up.", { mid: greeting.id }); } // Media await wa.Message.image(cid, readFileSync("./banner.png"), { caption: "Banner" }); await wa.Message.audio(cid, readFileSync("./note.ogg"), { ptt: true }); // Location await wa.Message.location(cid, { lat: 19.4326, lng: -99.1332 }); // Poll await wa.Message.poll(cid, { content: "Pick a framework", options: [{ content: "Next" }, { content: "Remix" }, { content: "Astro" }], }); // CRUD on existing messages const history = await wa.Message.list(cid, 0, 20); for (const m of history) { if (m.me && !m.edited && m instanceof wa.Message.Text) { await wa.Message.edit(cid, m.id, `[edited] ${m.caption}`); } } ``` ``` -------------------------------- ### Auto-reply Bot Example Source: https://github.com/arcaelas/whatsapp/wiki/Events-API An example demonstrating how to create an auto-reply bot that responds to messages containing 'hello'. ```APIDOC ## Auto-reply Bot ### Description This example shows how to set up an auto-reply mechanism. When a text message containing 'hello' is received, the bot sends back a predefined response. ### Event Subscription `wa.event.on("message:created", async (msg) => { ... });` ### Logic - Checks if the message is not from the user (`!msg.me`) and is a text message. - Converts the message content to lowercase and checks if it includes 'hello'. - If the condition is met, sends a reply using `wa.Message.text()`. ### Example Code ```typescript wa.event.on("message:created", async (msg) => { if (msg.me || msg.type !== "text") return; const text = (await msg.content()).toString().toLowerCase(); if (text.includes("hello")) { await wa.Message.text(msg.cid, "Hi! How can I help you?"); } }); ``` ``` -------------------------------- ### Message Logger Example Source: https://github.com/arcaelas/whatsapp/wiki/Events-API An example demonstrating how to log all incoming and outgoing messages with their timestamp, author, and content. ```APIDOC ## Message Logger ### Description This example logs details of each message, including its timestamp, author (whether it's from the user or another contact), chat ID, and content type. For text messages, the content is printed; otherwise, the message type is indicated. ### Event Subscription `wa.event.on("message:created", async (msg) => { ... });` ### Logging Details - **Timestamp**: Formatted as ISO string. - **Author**: 'Me' if sent by the user, otherwise the author's identifier. - **Chat ID**: The ID of the chat the message belongs to. - **Content**: For text messages, the actual text content is logged. For other types, the message type (e.g., 'IMAGE', 'VIDEO') is logged. ### Example Code ```typescript wa.event.on("message:created", async (msg) => { const timestamp = new Date(msg.created_at).toISOString(); const author = msg.me ? "Me" : msg.author; console.log(`[${timestamp}] ${author} in ${msg.cid}: `); if (msg.type === "text") { const text = (await msg.content()).toString(); console.log(` Text: ${text}`); } else { console.log(` ${msg.type.toUpperCase()}`); } }); ``` ``` -------------------------------- ### RedisEngine Write Operations Example Source: https://github.com/arcaelas/whatsapp/blob/main/docs/schema.md Demonstrates the Redis commands executed for a write operation to a specific path. Shows the use of SET for document storage and ZADD for index updates. ```text SET wa:default:doc:chat/120363@g.us/message/ABC "" ZADD wa:default:idx:chat/120363@g.us/message "chat/120363@g.us/message/ABC" ``` -------------------------------- ### Using InMemoryEngine with WhatsApp Source: https://github.com/arcaelas/whatsapp/blob/main/docs/examples/custom-engine.md Example of initializing the WhatsApp client with the InMemoryEngine. This demonstrates how to integrate a custom engine into the WhatsApp library for testing or ephemeral use cases. ```typescript import { WhatsApp } from '@arcaelas/whatsapp'; import { InMemoryEngine } from './in-memory-engine'; const wa = new WhatsApp({ engine: new InMemoryEngine(), phone: 584144709840, }); wa.connect((auth) => { console.log(typeof auth === 'string' ? `pin: ${auth}` : 'scan the QR'); }); ``` -------------------------------- ### Install Arcaelas WhatsApp Package Source: https://github.com/arcaelas/whatsapp/blob/main/README.md Install the core package using yarn. Node.js 18+ is required. Works in ESM & TypeScript projects. ```bash # core package yarn add @arcaelas/whatsapp ``` -------------------------------- ### RedisEngine Usage with ioredis Source: https://github.com/arcaelas/whatsapp/blob/main/docs/references/engines.md Example demonstrating how to use RedisEngine with the ioredis client. Ensure the Redis server is accessible and the correct connection details are provided. ```typescript import IORedis from 'ioredis'; import { WhatsApp, RedisEngine } from '@arcaelas/whatsapp'; const wa = new WhatsApp({ engine: new RedisEngine( new IORedis({ host: '127.0.0.1', port: 6379 }), 'wa:5491112345678', ), phone: 5491112345678, }); await wa.connect((pin) => console.log('PIN:', pin)); ``` -------------------------------- ### Quick Start: Connect and Handle Messages Source: https://github.com/arcaelas/whatsapp/wiki/Home Connect to WhatsApp using QR code or pairing code, listen for events like 'open' and 'close', and handle incoming text messages with replies. ```typescript import { WhatsApp } from "@arcaelas/whatsapp"; // Create instance const wa = new WhatsApp({ phone: "5491112345678", // Optional: for pairing code }); // Listen to events wa.event.on("open", () => console.log("Connected!")); wa.event.on("close", () => console.log("Disconnected")); wa.event.on("error", (err) => console.error("Error:", err.message)); // Connect await wa.pair(async (data) => { if (Buffer.isBuffer(data)) { // QR code as PNG image require("fs").writeFileSync("qr.png", data); console.log("Scan the QR in qr.png"); } else { // Pairing code (8 digits) console.log("Code:", data); } }); // Listen to messages wa.event.on("message:created", async (msg) => { if (msg.me) return; // Ignore own messages // Check type if (msg.type === "text") { const text = (await msg.content()).toString(); console.log(`Message: ${text}`); // Reply if (text.toLowerCase() === "hello") { await wa.Message.text(msg.cid, "Hello! How are you?"); } } }); ``` -------------------------------- ### Quick Start: Send a WhatsApp Message Source: https://github.com/arcaelas/whatsapp/blob/main/README.md Initialize the WhatsApp client, authenticate using QR code, and send a message to a chat. Requires 'qrcode-terminal' for QR display. ```typescript import WhatsApp from '@arcaelas/whatsapp'; import qrcode from 'qrcode-terminal'; const socket = new WhatsApp({ phone: '+01000000000', loginType: 'qr', qr: (buffer) => qrcode.generate(buffer.toString('base64'), { small: true }), }); await socket.ready(); // blocks until authenticated const [chat] = await socket.chats(); await chat.send('Hello from Arcaelas 🤖'); ``` -------------------------------- ### Custom Storage with Serialization Source: https://github.com/arcaelas/whatsapp/blob/main/docs/references/engines.md Demonstrates how to use the serialize and deserialize helpers to store and retrieve custom configuration objects using the engine's set and get methods. ```typescript import { serialize, deserialize } from '@arcaelas/whatsapp'; interface BotConfig { greeting: string; quietHours: [number, number]; } await wa.engine.set('/app/config', serialize({ greeting: 'Hello!', quietHours: [22, 8], })); const config = deserialize(await wa.engine.get('/app/config')); ``` -------------------------------- ### get() Method Source: https://github.com/arcaelas/whatsapp/wiki/Engine-API Retrieves a value from storage using its key. Returns the value as a string or null if the key is not found. ```APIDOC ### get() Retrieve a value by key. ```typescript get(key: string): Promise ``` **Parameters:** - `key` - Storage key **Returns:** Value as string or `null` if not found ``` -------------------------------- ### Full Basic Bot Example (index.ts) Source: https://github.com/arcaelas/whatsapp/blob/main/docs/examples/basic-bot.md This snippet shows a complete, single-file WhatsApp bot. It connects to WhatsApp, logs incoming messages, and replies 'pong' to 'ping'. Ensure you have the necessary imports and configure the engine and phone number. ```typescript import { join } from 'node:path'; import { WhatsApp, FileSystemEngine } from '@arcaelas/whatsapp'; const wa = new WhatsApp({ engine: new FileSystemEngine(join(__dirname, 'session')), phone: 584144709840, }); wa.on('connected', () => { console.log('[wa] connected'); }); wa.on('disconnected', () => { console.log('[wa] disconnected'); }); wa.on('message:created', async (msg, chat, wa) => { if (msg.me) { return; } console.log(`[${chat.name}] ${msg.caption}`); if (msg.caption.trim().toLowerCase() === 'ping') { await msg.text('pong'); } }); process.on('SIGINT', async () => { console.log('\n[wa] shutting down...'); await wa.disconnect(); process.exit(0); }); wa.connect((auth) => { if (typeof auth === 'string') { console.log(`[wa] pairing code: ${auth}`); } else { console.log('[wa] scan the QR (PNG buffer received)'); } }).catch((err) => { console.error('[wa] connect failed:', err); process.exit(1); }); ``` -------------------------------- ### Minimal In-Memory Store Implementation Source: https://github.com/arcaelas/whatsapp/blob/main/README.md Example of a minimal in-memory store implementation adhering to the Store contract. Useful for demos and testing. ```typescript /** Minimal in‑memory store for demos */ const MemoryStore: Store = { map: new Map(), has(key) { return this.map.has(key); }, get(key) { return JSON.parse(this.map.get(key) ?? 'null'); }, set(key, value) { if (value == null) return this.delete(key); this.map.set(key, JSON.stringify(value)); return true; }, delete(key) { return this.map.delete(key); }, async *keys() { for (const k of this.map.keys()) yield k; }, async *values() { for (const v of this.map.values()) yield JSON.parse(v); }, async *entries() { for (const [k, v] of this.map.entries()) yield [k, JSON.parse(v)]; }, clear() { this.map.clear(); return true; }, }; ``` -------------------------------- ### Custom Redis Persistence Engine Source: https://github.com/arcaelas/whatsapp/wiki/Examples This example shows how to implement a custom persistence engine using Redis. It defines a RedisEngine class that adheres to the Engine interface and then initializes the WhatsApp instance with this custom engine. ```typescript import { WhatsApp } from "@arcaelas/whatsapp"; import type { Engine } from "@arcaelas/whatsapp"; import Redis from "ioredis"; class RedisEngine implements Engine { private redis: Redis; constructor(url: string) { this.redis = new Redis(url); } async get(key: string): Promise { return await this.redis.get(key); } async set(key: string, value: string | null): Promise { if (value === null) { await this.redis.del(key); } else { await this.redis.set(key, value); } } async list(prefix: string, offset = 0, limit = 50): Promise { const pattern = `${prefix}*`; const keys = await this.redis.keys(pattern); return keys.slice(offset, offset + limit); } } // Use Redis engine const engine = new RedisEngine("redis://localhost:6379"); const wa = new WhatsApp({ engine }); wa.event.on("open", () => console.log("Connected with Redis engine")); wa.pair(async (data) => { if (Buffer.isBuffer(data)) { require("fs").writeFileSync("qr.png", data); } }); ``` -------------------------------- ### Connect with PIN using RedisEngine Source: https://github.com/arcaelas/whatsapp/blob/main/docs/references/whatsapp.md Connect to WhatsApp using a phone number and receive a PIN for pairing. This example uses `RedisEngine` for storing session data and logs the PIN to the console. Requires `RedisEngine` and an `IORedis` instance. ```typescript import IORedis from 'ioredis'; import { WhatsApp, RedisEngine } from '@arcaelas/whatsapp'; const wa = new WhatsApp({ engine: new RedisEngine(new IORedis(), 'wa:5491112345678'), phone: 5491112345678, }); await wa.connect((auth) => { console.log('Pair this code on your phone:', auth); }); ``` -------------------------------- ### Handle Incoming Messages Source: https://github.com/arcaelas/whatsapp/wiki/Message-API An example of how to process incoming messages using the 'message:created' event. It demonstrates retrieving message content and handling different message types like text and images. ```typescript wa.event.on("message:created", async (msg) => { const buffer = await msg.content(); if (msg.type === "text") { console.log("Text:", buffer.toString()); } if (msg.type === "image") { require("fs").writeFileSync("image.jpg", buffer); } }); ``` -------------------------------- ### S3Engine Usage with Cache Configuration Source: https://github.com/arcaelas/whatsapp/blob/main/docs/references/engines.md Example of initializing S3Engine with an in-memory cache. The `ttl` specifies the cache duration, and `when` is a function to determine which keys should be cached based on their prefix. ```typescript import { S3Client } from '@aws-sdk/client-s3'; import { WhatsApp, S3Engine } from '@arcaelas/whatsapp'; const wa = new WhatsApp({ engine: new S3Engine({ s3: new S3Client({ region: 'us-east-1' }), bucket: 'my-wa-bucket', basedir: 'wa/5491112345678', cache: { ttl: 180_000, // 3 minutes when: (key) => key.startsWith('/chat/') || key.startsWith('/contact/') || key.startsWith('/lid/'), }, }), phone: 5491112345678, }); await wa.connect((pin) => console.log('PIN:', pin)); ``` -------------------------------- ### Using Delegates for WhatsApp API Interaction Source: https://github.com/arcaelas/whatsapp/blob/main/docs/references/whatsapp.md Demonstrates how to use the Contact, Chat, and Message delegates to perform common actions like listing chats, getting contact information, and sending text messages. ```typescript const chats = await wa.Chat.list({ limit: 20 }); const contact = await wa.Contact.get('5491112345678'); await wa.Message.text('5491112345678', 'Hello from v3'); ``` -------------------------------- ### Initialize WhatsApp Client Source: https://github.com/arcaelas/whatsapp/blob/main/docs/examples/polls.md Sets up the WhatsApp client with a file system engine and connects to the service. This is the initial step for any interaction with the library. ```typescript import { WhatsApp } from '@arcaelas/whatsapp'; import { FileSystemEngine } from '@arcaelas/whatsapp/engines'; export const wa = new WhatsApp({ engine: new FileSystemEngine(__dirname), phone: 14155551234, }); await wa.connect((auth) => { if (typeof auth === 'string') { console.log('Pair code:', auth); } }); ``` -------------------------------- ### Initialize FileSystemEngine Source: https://github.com/arcaelas/whatsapp/blob/main/docs/engine.md Sets up the FileSystemEngine for WhatsApp data persistence using the local file system. Data is stored in a specified base directory. ```typescript import { FileSystemEngine, WhatsApp } from '@arcaelas/whatsapp'; import { join } from 'node:path'; const engine = new FileSystemEngine(join(process.cwd(), '.baileys')); const wa = new WhatsApp({ engine, phone: 584144709840 }); ``` -------------------------------- ### Initialize FileSystemEngine Source: https://github.com/arcaelas/whatsapp/blob/main/docs/getting-started.md Sets up the FileSystemEngine for local development, storing session data as files in the specified directory. ```typescript import { FileSystemEngine } from "@arcaelas/whatsapp"; const engine = new FileSystemEngine(__dirname + "/.session"); ``` -------------------------------- ### Install Baileys Dependency Source: https://github.com/arcaelas/whatsapp/wiki/Installation If you encounter a 'Cannot find module \'baileys\'' error, ensure baileys is installed as a dependency. ```bash npm install baileys ``` -------------------------------- ### Hello World WhatsApp Bot Source: https://github.com/arcaelas/whatsapp/blob/main/docs/index.md This snippet demonstrates how to initialize and connect a WhatsApp instance using the FileSystemEngine. It logs a message when the session is ready and prints the chat ID and message caption for new messages. The connection process requires handling QR codes or PINs for authentication. ```typescript import { WhatsApp, FileSystemEngine } from "@arcaelas/whatsapp"; import { writeFileSync } from "node:fs"; const wa = new WhatsApp({ engine: new FileSystemEngine(__dirname + "/.session"), phone: 584144709840, }); wa.on("connected", () => console.log("session ready")); wa.on("message:created", (msg, chat) => console.log(chat.id, msg.caption)); await wa.connect((code) => { if (typeof code === "string") console.log("PIN:", code); else writeFileSync("qr.png", code); }); ``` -------------------------------- ### Unread Counter Example Source: https://github.com/arcaelas/whatsapp/wiki/Events-API An example demonstrating how to display the number of unread messages for each chat when the chat information is updated. ```APIDOC ## Unread Counter ### Description This example monitors chat updates and logs a message indicating the number of unread messages for any chat that has unread messages. ### Event Subscription `wa.event.on("chat:updated", (chat) => { ... });` ### Logic - Listens for the `chat:updated` event. - Checks the `unread` property of the updated chat object. - If `chat.unread` is greater than 0, it logs the chat name and the count of unread messages. ### Example Code ```typescript wa.event.on("chat:updated", (chat) => { if (chat.unread > 0) { console.log(`${chat.name} has ${chat.unread} unread messages`); } }); ``` ``` -------------------------------- ### Initialize WhatsApp with FileEngine Source: https://github.com/arcaelas/whatsapp/wiki/API-Reference Instantiate `FileEngine` to use the default filesystem-based persistence. Provide a directory path for storing data. Then, initialize `WhatsApp` with the created engine. ```typescript import { FileEngine } from "@arcaelas/whatsapp"; const engine = new FileEngine(".baileys/my-bot"); const wa = new WhatsApp({ engine }); ``` -------------------------------- ### Example IChatRaw Payload Source: https://github.com/arcaelas/whatsapp/blob/main/docs/schema.md An example JSON payload conforming to the IChatRaw interface, illustrating typical values for chat details. ```json { "id": "120363123456789@g.us", "name": "Dev Team", "archived": false, "pinned": 1767371367857, "mute_end_time": null, "unread_count": 5, "read_only": false } ``` -------------------------------- ### Initialize RedisEngine Source: https://github.com/arcaelas/whatsapp/blob/main/docs/engine.md Sets up the RedisEngine for WhatsApp data persistence using ioredis. Ensure the REDIS_URL environment variable is set. ```typescript import IORedis from 'ioredis'; import { RedisEngine, WhatsApp } from '@arcaelas/whatsapp'; const redis = new IORedis(process.env.REDIS_URL!); const engine = new RedisEngine(redis, 'wa:584144709840'); const wa = new WhatsApp({ engine, phone: 584144709840 }); ``` -------------------------------- ### Example IContactRaw Payload Source: https://github.com/arcaelas/whatsapp/blob/main/docs/schema.md An example JSON payload conforming to the IContactRaw interface, illustrating typical values for contact details. ```json { "id": "584144709840@s.whatsapp.net", "lid": "140913951141911@lid", "name": "Juan Perez", "notify": "Juanito", "verified_name": null, "img_url": "https://pps.whatsapp.net/v/t61.24694-24/", "status": "Available 24/7" } ``` -------------------------------- ### Auto-reply Bot Example Source: https://github.com/arcaelas/whatsapp/wiki/Events-API An example of an auto-reply bot that responds to messages containing 'hello'. It only replies to text messages not sent by the user. ```typescript wa.event.on("message:created", async (msg) => { if (msg.me || msg.type !== "text") return; const text = (await msg.content()).toString().toLowerCase(); if (text.includes("hello")) { await wa.Message.text(msg.cid, "Hi! How can I help you?"); } }); ``` -------------------------------- ### Import WhatsApp and FileSystemEngine Source: https://github.com/arcaelas/whatsapp/blob/main/docs/references/events.md Import necessary classes from the '@arcaelas/whatsapp' library and initialize a new WhatsApp instance with a FileSystemEngine. ```typescript import { WhatsApp, FileSystemEngine } from '@arcaelas/whatsapp'; const wa = new WhatsApp({ engine: new FileSystemEngine('./data/wa') }); ``` -------------------------------- ### Message.content() Source: https://github.com/arcaelas/whatsapp/wiki/Message-API Gets the message content as a Buffer. ```APIDOC ## Message.content() ### Description Gets the message content as Buffer. ### Method `GET` (conceptual, actual implementation is SDK method) ### Endpoint N/A (SDK Method) ### Parameters N/A ### Request Example ```typescript const buffer = await msg.content(): Promise ``` ### Response #### Success Response - **Buffer** - Message content as a Buffer. #### Response Example ```javascript // Example for text message Buffer.from("Hello, world!") // Example for image message (binary data) // Buffer containing image file bytes ``` ``` -------------------------------- ### Initialize WhatsApp with Default Engine Source: https://github.com/arcaelas/whatsapp/wiki/WhatsApp-API Instantiate the WhatsApp class using the default FileEngine. ```typescript const wa = new WhatsApp(); ``` -------------------------------- ### Instantiate WhatsApp Client Source: https://github.com/arcaelas/whatsapp/blob/main/docs/getting-started.md Initializes the WhatsApp client with a file system engine and a phone number for PIN pairing. Omit the phone number to use QR code pairing. ```typescript import { WhatsApp, FileSystemEngine } from "@arcaelas/whatsapp"; const engine = new FileSystemEngine(__dirname + "/.session"); const wa = new WhatsApp({ engine, phone: 584144709840, // omit to fall back to QR pairing }); ``` -------------------------------- ### Get Chat and Type Source: https://github.com/arcaelas/whatsapp/blob/main/docs/references/message.md Retrieve the chat associated with a message and interact with it, such as indicating typing status. ```typescript const chat = await msg.chat(); await chat.typing(true); ``` -------------------------------- ### Initialize WhatsApp with Custom Engine Source: https://github.com/arcaelas/whatsapp/wiki/WhatsApp-API Instantiate the WhatsApp class with a custom file persistence engine path. ```typescript import { FileEngine } from "@arcaelas/whatsapp"; const wa = new WhatsApp({ engine: new FileEngine(".baileys/my-bot"), }); ``` -------------------------------- ### get() Source: https://github.com/arcaelas/whatsapp/wiki/Chat-API Retrieves a specific chat by its ID. Returns the Chat instance if found, otherwise null. ```APIDOC ## get() ### Description Get a specific chat. ### Method `GET` (conceptual, as it's an SDK method) ### Endpoint N/A (SDK Method) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```typescript const chat = await wa.Chat.get("5491112345678@s.whatsapp.net"); if (chat) { console.log(`Chat: ${chat.name}`); console.log(`Unread: ${chat.unread}`); } ``` ### Response #### Success Response (200) - **chat** (Chat | null) - Chat instance or null #### Response Example ```json { "id": "string", "name": "string", "unread": "number", "archived": "boolean", "pinned": "boolean", "muted": "boolean", "last_message_at": "number | null" } ``` ``` -------------------------------- ### Help Command Implementation Source: https://github.com/arcaelas/whatsapp/wiki/Command-Bot-Example Displays a list of all available commands and their descriptions. It iterates through the registered commands to generate the help message. ```typescript import { commands, register_command } from "./index"; register_command({ name: "help", description: "Show command list", aliases: ["h", "?"], async execute({ wa, cid }) { const unique_commands = new Map(); commands.forEach((cmd) => { if (!unique_commands.has(cmd.name)) { unique_commands.set(cmd.name, cmd.description); } }); let message = "*Available commands:*\n\n"; unique_commands.forEach((desc, name) => { message += `!${name} - ${desc}\n`; }); await wa.Message.text(cid, message); }, }); ``` -------------------------------- ### Engine Interface Definition Source: https://github.com/arcaelas/whatsapp/wiki/Engine-API Defines the methods for interacting with the persistence engine: get, set, and list. ```typescript interface Engine { get(key: string): Promise; set(key: string, value: string | null): Promise; list(prefix: string, offset?: number, limit?: number): Promise; } ``` -------------------------------- ### Run TypeScript Bot Source: https://github.com/arcaelas/whatsapp/wiki/Basic-Bot-Example Execute the bot using tsx. This command assumes you have Node.js and tsx installed. ```bash npx tsx bot.ts ``` -------------------------------- ### RedisEngine Initialization with Prefixes Source: https://github.com/arcaelas/whatsapp/blob/main/docs/schema.md Shows how to initialize RedisEngine instances with distinct prefixes for different accounts sharing a Redis instance. Ensures data isolation between sessions. ```typescript import IORedis from 'ioredis'; import { RedisEngine } from '@arcaelas/whatsapp'; const redis = new IORedis(process.env.REDIS_URL); const engine_a = new RedisEngine(redis, 'wa:584144709840'); const engine_b = new RedisEngine(redis, 'wa:584121234567'); ``` -------------------------------- ### Engine Interface Source: https://github.com/arcaelas/whatsapp/wiki/Engine-API The core Engine interface defines the methods for interacting with the persistence layer: get, set, and list. ```APIDOC ## Interface ```typescript interface Engine { get(key: string): Promise; set(key: string, value: string | null): Promise; list(prefix: string, offset?: number, limit?: number): Promise; } ``` ``` -------------------------------- ### Connect with QR Code using FileSystemEngine Source: https://github.com/arcaelas/whatsapp/blob/main/docs/references/whatsapp.md Use this snippet to connect to WhatsApp and receive a QR code for pairing, saving the QR code as a PNG file. Requires `FileSystemEngine`. ```typescript import { WhatsApp, FileSystemEngine } from '@arcaelas/whatsapp'; import { writeFileSync } from 'node:fs'; const wa = new WhatsApp({ engine: new FileSystemEngine('./data/wa') }); await wa.connect((auth) => { writeFileSync('./qr.png', auth as Buffer); }); ``` -------------------------------- ### Unread Message Counter Example Source: https://github.com/arcaelas/whatsapp/wiki/Events-API Logs the name of a chat and the number of unread messages when the chat is updated and has unread messages. ```typescript wa.event.on("chat:updated", (chat) => { if (chat.unread > 0) { console.log(`${chat.name} has ${chat.unread} unread messages`); } }); ``` -------------------------------- ### Get Chat Messages Source: https://github.com/arcaelas/whatsapp/blob/main/docs/references/chat.md Shortcut for `wa.Message.list(this.id, offset, limit)`. Returns messages ordered by engine mtime DESC. ```typescript const latest = await chat.messages(0, 20); for (const msg of latest) { console.log(msg.type, msg.caption); } ``` -------------------------------- ### Get Message Content Source: https://github.com/arcaelas/whatsapp/wiki/API-Reference Retrieves the content of a message as a Buffer. This is often used within event handlers for incoming messages. ```typescript // Get message content wa.event.on("message:created", async (msg) => { const buffer = await msg.content(); console.log(buffer.toString()); }); ``` -------------------------------- ### Bootstrap Chat Instance Source: https://github.com/arcaelas/whatsapp/blob/main/docs/references/chat.md Instantiate the WhatsApp client with a chosen engine and connect to the service. Then, retrieve a chat instance by its CID. The chat's name and type are logged if the chat is found. ```typescript import { WhatsApp, RedisEngine } from "@arcaelas/whatsapp"; const wa = new WhatsApp({ engine: new RedisEngine({ url: "redis://127.0.0.1:6379" }), }); await wa.connect(); const chat = await wa.Chat.get("5215555555555@s.whatsapp.net"); if (chat) { console.log(chat.name, chat.type); } ``` -------------------------------- ### Get Group Members Source: https://github.com/arcaelas/whatsapp/wiki/Chat-API Retrieves members of a group chat. Requires the chat ID to end with '@g.us'. Supports pagination. ```typescript if (cid.endsWith("@g.us")) { const members = await wa.Chat.members(cid); console.log(`Group has ${members.length} members`); } ``` -------------------------------- ### Configure WhatsApp with FileEngine Source: https://github.com/arcaelas/whatsapp/wiki/Home Instantiate WhatsApp with the default FileEngine, specifying a custom directory for storing data. ```typescript import { WhatsApp, FileEngine } from "@arcaelas/whatsapp"; const wa = new WhatsApp({ engine: new FileEngine(".baileys/my-bot"), }); ``` -------------------------------- ### Register Group-Only Command Source: https://github.com/arcaelas/whatsapp/wiki/Command-Bot-Example Register a command that is restricted to only function within group chats. This example retrieves and displays group information. ```typescript import { register_command } from "./index"; register_command({ name: "group", description: "Group information", aliases: ["g"], async execute({ wa, cid }) { // Only in groups if (!cid.endsWith("@g.us")) { await wa.Message.text(cid, "This command only works in groups"); return; } const chat = await wa.Chat.get(cid); if (!chat) return; const members = await wa.Chat.members(cid, 0, 1000); await wa.Message.text( cid, `*${chat.name}* ` + `Members: ${members.length}` ); }, }); ``` -------------------------------- ### Register Command with Input Validation Source: https://github.com/arcaelas/whatsapp/wiki/Command-Bot-Example Register a command that requires validation on its arguments. This example shows how to validate a number for dice sides. ```typescript import { register_command } from "./index"; register_command({ name: "dice", description: "Roll a dice", aliases: ["roll"], async execute({ wa, cid, args }) { const sides = parseInt(args[0]) || 6; if (sides < 2 || sides > 100) { await wa.Message.text(cid, "Dice must have between 2 and 100 sides"); return; } const result = Math.floor(Math.random() * sides) + 1; await wa.Message.text(cid, `${sides}-sided dice: ${result}`); }, }); ``` -------------------------------- ### Instantiate WhatsApp and Access Contact Class Source: https://github.com/arcaelas/whatsapp/wiki/Contact-API Demonstrates how to create a WhatsApp instance and access the Contact class after instantiation. This is the initial step before performing any contact operations. ```typescript const wa = new WhatsApp(); // wa.Contact is available after instantiation ``` -------------------------------- ### Basic WhatsApp Bot Structure Source: https://github.com/arcaelas/whatsapp/wiki/Getting-Started Initializes the WhatsApp client, sets up event listeners for connection status, and handles QR code generation for pairing. ```typescript import { WhatsApp } from "@arcaelas/whatsapp"; async function main() { // Create WhatsApp instance const wa = new WhatsApp(); // Listen to events before connecting wa.event.on("open", () => console.log("Connected!")); wa.event.on("close", () => console.log("Disconnected")); wa.event.on("error", (err) => console.error("Error:", err.message)); // Connect showing QR in console console.log("Waiting for QR..."); await wa.pair(async (data) => { if (Buffer.isBuffer(data)) { // Save QR as image const fs = await import("fs"); fs.writeFileSync("qr.png", data); console.log("QR saved to qr.png - Scan with your phone"); } else { // 8 digit code (if using phone) console.log("Pairing code:", data); } }); console.log("Bot started!"); } main().catch(console.error); ``` -------------------------------- ### Get Author Contact Source: https://github.com/arcaelas/whatsapp/blob/main/docs/references/message.md Resolve the sender of a message as a Contact object. Falls back to a minimal instance if the contact is not yet known. ```typescript const sender = await msg.author(); console.log(sender.name, sender.phone); ``` -------------------------------- ### Get Specific Chat Source: https://github.com/arcaelas/whatsapp/wiki/Chat-API Retrieve a specific chat using its Chat ID (CID). Returns the Chat instance or null if not found. ```typescript const chat = await wa.Chat.get("5491112345678@s.whatsapp.net"); if (chat) { console.log(`Chat: ${chat.name}`); console.log(`Unread: ${chat.unread}`); } ``` -------------------------------- ### WhatsApp Constructor Source: https://github.com/arcaelas/whatsapp/wiki/WhatsApp-API Initializes a new WhatsApp instance. You can provide options to configure the persistence engine or specify a phone number for pairing. ```APIDOC ## Constructor WhatsApp ### Description Initializes a new WhatsApp instance. You can provide options to configure the persistence engine or specify a phone number for pairing. ### Parameters #### Options - **engine** (Engine) - Optional - Persistence engine. Defaults to `FileEngine(".baileys/default")`. - **phone** (string) - Optional - Phone number for pairing code. ### Examples ```typescript // Default (FileEngine) const wa = new WhatsApp(); // Custom path import { FileEngine } from "@arcaelas/whatsapp"; const wa = new WhatsApp({ engine: new FileEngine(".baileys/my-bot"), }); // With phone for pairing code const wa = new WhatsApp({ phone: "5491112345678", }); ``` ``` -------------------------------- ### Forward a Message Source: https://github.com/arcaelas/whatsapp/blob/main/docs/examples/media.md Forward any received message to another chat. This example specifically forwards received image messages to a personal archive chat. ```typescript import { wa } from './client'; const ARCHIVE_CID = '14155550000@s.whatsapp.net'; wa.on('message:created', async (msg) => { // Archive every photo I receive into a personal chat with myself. if (msg instanceof wa.Message.Image && !msg.me) { const ok = await msg.forward(ARCHIVE_CID); console.log(ok ? 'Forwarded' : 'Forward failed'); } }); ``` -------------------------------- ### Initialize WhatsApp and Retrieve Contacts Source: https://github.com/arcaelas/whatsapp/blob/main/docs/references/contact.md Initialize the WhatsApp client with an engine and connect. Demonstrates retrieving contacts using phone number, JID, and LID, showcasing the smart dispatch functionality. ```typescript import { WhatsApp, RedisEngine } from "@arcaelas/whatsapp"; const wa = new WhatsApp({ engine: new RedisEngine({ url: "redis://127.0.0.1:6379" }), }); await wa.connect(); // Phone number (digits only) const byPhone = await wa.Contact.get("5215555555555"); // JID const byJid = await wa.Contact.get("5215555555555@s.whatsapp.net"); // LID (hidden identifier assigned by WhatsApp) const byLid = await wa.Contact.get("192837465@lid"); console.log(byPhone?.name, byJid?.phone, byLid?.id); ``` -------------------------------- ### Get Message Content as Buffer Source: https://github.com/arcaelas/whatsapp/wiki/Message-API Retrieves the raw content of a message as a Buffer. This is useful for processing media files or decoding text content. ```typescript const buffer = await msg.content(): Promise ``` -------------------------------- ### Import WhatsApp and Engine Source: https://github.com/arcaelas/whatsapp/blob/main/docs/references/contact.md Import necessary classes from the WhatsApp library. Choose between RedisEngine or FileSystemEngine based on your storage needs. ```typescript import { WhatsApp, RedisEngine } from "@arcaelas/whatsapp"; // or import { WhatsApp, FileSystemEngine } from "@arcaelas/whatsapp"; ```