### Local Example File for Baileys-Joss Source: https://github.com/firdausmntp/baileys-joss/blob/main/README.md This is a local example file demonstrating the usage of the Baileys-Joss library. It serves as a comprehensive guide for various functionalities. ```javascript // This is a placeholder for the actual content of the wa-baileys-joss-complete.js file. // The file contains comprehensive examples of how to use the Baileys-Joss library. // For the full code, please refer to the local example file in the repository. ``` -------------------------------- ### Install Baileys-Joss using npm Source: https://github.com/firdausmntp/baileys-joss/blob/main/README.md Use npm to install the Baileys-Joss library. This command adds the library to your project's dependencies. ```bash npm install baileys-joss ``` -------------------------------- ### Install and Connect Baileys-Joss Bot Source: https://context7.com/firdausmntp/baileys-joss/llms.txt Install the library and establish a basic WhatsApp Web connection using QR code or pairing code. Handles authentication state and connection updates. ```typescript // Instalasi // npm install baileys-joss // atau sebagai override di package.json: // "@whiskeysockets/baileys": "npm:baileys-joss" import makeWASocket, { useMultiFileAuthState, DisconnectReason, fetchLatestBaileysVersion, getCurrentSenderInfo } from 'baileys-joss' import { Boom } from '@hapi/boom' async function startBot() { // Load atau buat auth state const { state, saveCreds } = await useMultiFileAuthState('auth_session') // Fetch versi WA Web terbaru const { version, isLatest } = await fetchLatestBaileysVersion() console.log(`Using WA version: ${version.join('.')}, isLatest: ${isLatest}`) // Buat socket connection const sock = makeWASocket({ version, auth: state, printQRInTerminal: true, // Tampilkan QR di terminal generateHighQualityLinkPreview: true }) // Save credentials saat update sock.ev.on('creds.update', saveCreds) // Handle connection updates sock.ev.on('connection.update', async (update) => { const { connection, lastDisconnect, qr } = update if (connection === 'close') { const shouldReconnect = (lastDisconnect?.error as Boom)?.output?.statusCode !== DisconnectReason.loggedOut console.log('Connection closed, reconnecting:', shouldReconnect) if (shouldReconnect) startBot() } if (connection === 'open') { console.log('Connected!') // Get sender info (Baileys-Joss feature) const senderInfo = getCurrentSenderInfo(sock.authState) console.log('Phone:', senderInfo?.phoneNumber) console.log('LID:', senderInfo?.lid) } }) return sock } // Pairing Code (alternative to QR) const sock = makeWASocket({ auth: state, printQRInTerminal: false }) sock.ev.on('connection.update', async ({ qr }) => { if (qr && !sock.authState.creds.registered) { const code = await sock.requestPairingCode('6281234567890') console.log('Pairing Code:', code) // Custom pairing code const customCode = await sock.requestPairingCode('6281234567890', 'MYCODE12') console.log('Custom Code:', customCode) } }) startBot() ``` -------------------------------- ### Start and Answer Quiz Game Source: https://context7.com/firdausmntp/baileys-joss/llms.txt Starts a quiz game with predefined questions and allows users to answer. Provides feedback on correctness, score, and explanations. ```typescript // === QUIZ === const quizSession = games.startQuiz(jid, sampleQuizQuestions) const currentQ = games.getCurrentQuestion(quizSession.id) if (currentQ) { await sock.sendMessage(jid, { text: formatQuizQuestion(currentQ.question, currentQ.index, currentQ.total) }) } // Answer quiz (0 = A, 1 = B, 2 = C, 3 = D) const quizResult = games.answerQuiz(quizSession.id, 1) // user answered B console.log(quizResult.correct) console.log(quizResult.score) console.log(quizResult.explanation) await sock.sendMessage(jid, { text: quizResult.message }) ``` -------------------------------- ### Install Baileys-Joss with npm, yarn, or pnpm Source: https://github.com/firdausmntp/baileys-joss/blob/main/README.md Use these commands to install the baileys-joss package using your preferred package manager. ```bash # Menggunakan npm npm install baileys-joss ``` ```bash # Menggunakan yarn yarn add baileys-joss ``` ```bash # Menggunakan pnpm pnpm add baileys-joss ``` -------------------------------- ### Implement Mini Games with Baileys-Joss Source: https://github.com/firdausmntp/baileys-joss/blob/main/README.md Provides examples for integrating mini-games like Guess Number, Quiz, and TicTacToe into your chat application. Includes functions for starting games, handling moves, and rendering game states. ```typescript import { MiniGamesManager, createTicTacToeGame, createQuiz } from 'baileys-joss' // Create games manager const games = new MiniGamesManager() // šŸŽÆ Guess Number Game const guessSession = games.startGuessNumber('6281234567890@s.whatsapp.net', { minNumber: 1, maxNumber: 100, maxAttempts: 7 }) // Handle guess const result = games.handleGuess(guessSession.id, 50) if (result.correct) { await sock.sendMessage(jid, { text: `šŸŽ‰ Correct! The number was ${result.answer}` }) } else { await sock.sendMessage(jid, { text: `${result.hint} (${result.remaining} attempts left)` }) } ``` ```typescript // 🧠 Quiz Game const quizSession = games.startQuiz(jid, { questions: [ { question: 'Apa ibukota Indonesia?', options: ['Jakarta', 'Bandung', 'Surabaya', 'Medan'], correctIndex: 0, explanation: 'Jakarta adalah ibukota Indonesia sejak 1945' } ], category: 'geography' }) await sock.sendMessage(jid, { text: `šŸ“ Quiz:\n${quizSession.data.currentQuestion}\n\n${quizSession.data.options.map((o, i) => `${i+1}. ${o}`).join('\n')}` }) ``` ```typescript // āŒā­• TicTacToe Game const tttSession = games.startTicTacToe(jid, player1Jid, player2Jid) const moveResult = games.handleMove(tttSession.id, player1Jid, 4) // Center position await sock.sendMessage(jid, { text: `${games.renderBoard(tttSession)}\n\n${moveResult.message}` }) ``` ```typescript // šŸŽ² Quick Games const dice = games.rollDice() // { value: 1-6, emoji: 'šŸŽ²' } const coin = games.flipCoin() // { result: 'heads'|'tails', emoji: 'šŸŖ™' } const rps = games.playRockPaperScissors('rock', 'scissors') // { winner: 'player1', ... } ``` ```typescript // šŸ† Leaderboard const leaderboard = games.getLeaderboard(10) ``` -------------------------------- ### Start Typing Indicator Source: https://github.com/firdausmntp/baileys-joss/blob/main/README.md Simulate typing activity in a chat. Uses `createTypingIndicator` and `sock.sendPresenceUpdate`. Automatically pauses after a specified duration. ```typescript const typing = createTypingIndicator( (jid, presence) => sock.sendPresenceUpdate(presence, jid) ) await typing.startTyping(jid, { duration: 5000, // Auto pause after 5 seconds }) ``` -------------------------------- ### QR Event Handler for WhatsApp Connection Source: https://context7.com/firdausmntp/baileys-joss/llms.txt Set up a QR code event handler for the WhatsApp connection process. This example shows how to configure the handler to display the QR code in the terminal during connection attempts. ```typescript import { createQRHandler, makeWASocket } from 'baileys-joss' // Use sebagai QR event handler const sock = makeWASocket({ printQRInTerminal: false }) sock.ev.on('connection.update', async ({ qr }) => { if (qr) { const qrHandler = createQRHandler({ maxAttempts: 5, onQR: (rendered, raw, attempt) => { console.log(`\nScan QR (${attempt}/5):\n`) console.log(rendered) } }) await qrHandler(qr) } }) ``` -------------------------------- ### Baileys-Joss Bot Quick Start Source: https://github.com/firdausmntp/baileys-joss/blob/main/README.md Sets up a basic WhatsApp bot using Baileys-Joss, handling authentication, connection events, and message processing for commands like /menu, /poll, and /ai. Requires 'baileys-joss' and related imports. ```typescript import makeWASocket, { useMultiFileAuthState, DisconnectReason, // Interactive Message features generateQuickReplyButtons, generateInteractiveListMessage, generateCombinedButtons, // JID Plotting features getCurrentSenderInfo, parseJid, isSelf } from 'baileys-joss' async function startBot() { const { state, saveCreds } = await useMultiFileAuthState('auth_session') const sock = makeWASocket({ auth: state, printQRInTerminal: true }) sock.ev.on('creds.update', saveCreds) sock.ev.on('connection.update', (update) => { const { connection, lastDisconnect } = update if (connection === 'close') { const shouldReconnect = lastDisconnect?.error?.output?.statusCode !== DisconnectReason.loggedOut if (shouldReconnect) { startBot() } } else if (connection === 'open') { console.log('āœ… Connected!') // Get sender info const sender = getCurrentSenderInfo(sock.authState) console.log('šŸ“± Logged in as:', sender?.phoneNumber) } }) sock.ev.on('messages.upsert', async ({ messages }) => { const msg = messages[0] if (!msg.message || msg.key.fromMe) return const text = msg.message.conversation || msg.message.extendedTextMessage?.text || '' if (text === '/menu') { // Kirim interactive buttons const buttons = generateQuickReplyButtons( 'šŸ¤– Bot Menu\n\nPilih opsi:', [ { id: 'help', displayText: 'ā“ Bantuan' }, { id: 'info', displayText: 'ā„¹ļø Info' }, { id: 'order', displayText: 'šŸ›’ Order' } ], { footer: 'Baileys-Joss Bot' } ) await sock.sendMessage(msg.key.remoteJid!, buttons) } if (text === '/poll') { // Kirim poll await sock.sendMessage(msg.key.remoteJid!, { poll: { name: 'šŸ—³ļø Vote sekarang!', values: ['Option A', 'Option B', 'Option C'], selectableCount: 1 } }) } if (text === '/ai') { // Kirim pesan dengan AI style await sock.sendMessage(msg.key.remoteJid!, { text: 'Halo! Saya asisten AI Anda šŸ¤–', ai: true }) } }) } startBot() ``` -------------------------------- ### Start and Play Guess Number Game Source: https://context7.com/firdausmntp/baileys-joss/llms.txt Initiates a 'Guess Number' game with specified min/max values and processes user guesses. Provides feedback on correctness, hints, and game over status. ```typescript import { MiniGamesManager, sampleQuizQuestions, formatQuizQuestion } from 'baileys-joss' const games = new MiniGamesManager() // === TEBAK ANGKA === const guessSession = games.startGuessNumber(jid, 1, 100) // min, max await sock.sendMessage(jid, { text: 'šŸŽÆ Tebak angka 1-100!\nKetik angka tebakanmu.' }) // Process guess const result = games.guessNumber(guessSession.id, 50) // user's guess console.log(result.correct) // true/false console.log(result.hint) // 'higher', 'lower', 'correct' console.log(result.attempts) // jumlah percobaan console.log(result.gameOver) // true jika game selesai await sock.sendMessage(jid, { text: result.message }) ``` -------------------------------- ### Pomodoro Timer with Baileys-Joss Source: https://github.com/firdausmntp/baileys-joss/blob/main/README.md Implement a Pomodoro productivity timer using the PomodoroManager. This example shows how to set up event handlers for work and break sessions, start/pause/resume timers, and retrieve status and statistics. ```typescript import { PomodoroManager, DEFAULT_POMODORO_CONFIG } from 'baileys-joss' // Create pomodoro manager const pomodoro = new PomodoroManager() // Register event handler pomodoro.onEvent(async (event) => { const jid = event.session.jid switch (event.type) { case 'work_start': await sock.sendMessage(jid, { text: `šŸ… *WORK SESSION STARTED*\n\nā±ļø Duration: 25 minutes\nšŸŽÆ Session: ${event.session.currentSession}/${event.session.totalSessions}\n\nšŸ’Ŗ Stay focused!` }) break case 'work_end': await sock.sendMessage(jid, { text: `āœ… *WORK SESSION COMPLETE!*\n\nšŸŽ‰ Great job! Time for a break.\n\nType /break to start break timer.` }) break case 'break_start': await sock.sendMessage(jid, { text: `ā˜• *BREAK TIME*\n\nā±ļø Duration: 5 minutes\n\n🧘 Relax and recharge!` }) break case 'break_end': await sock.sendMessage(jid, { text: `ā° *BREAK OVER!*\n\nReady for next session?\nType /work to continue.` }) break } }) ``` ```typescript // Start work session const session = pomodoro.start('6281234567890@s.whatsapp.net', { workDuration: 25, // 25 minutes shortBreakDuration: 5, // 5 minutes longBreakDuration: 15, // 15 minutes sessionsBeforeLongBreak: 4, autoStartBreaks: true }) ``` ```typescript // Pause/Resume pomodoro.pause(jid) pomodoro.resume(jid) ``` ```typescript // Start break manually pomodoro.startBreak(jid) ``` ```typescript // Get current status const status = pomodoro.status(jid) console.log('Status:', status.status) // 'work' | 'short_break' | 'long_break' | 'paused' console.log('Time remaining:', status.remainingTime) console.log('Current session:', status.currentSession) ``` ```typescript // Stop and reset pomodoro.stop(jid) ``` ```typescript // Get statistics const stats = pomodoro.stats(jid) console.log('Total work sessions:', stats.totalWorkSessions) console.log('Total work minutes:', stats.totalWorkMinutes) console.log('Current streak:', stats.currentStreak) ``` -------------------------------- ### Create JID Plotter for Bidirectional Mapping Source: https://context7.com/firdausmntp/baileys-joss/llms.txt Instantiate a JID plotter that can map between phone numbers (PN) and Linked IDs (LID). Requires functions to get LID for PN and PN for LID from 'sock.lidMapping'. ```typescript import { createJidPlotter } from 'baileys-joss' // Advanced: Create plotter dengan LID mapping const plotter = createJidPlotter( sock.lidMapping.getLIDForPN.bind(sock.lidMapping), sock.lidMapping.getPNForLID.bind(sock.lidMapping) ) const plotted = await plotter.plotBidirectional('6281234567890@s.whatsapp.net') console.log('Phone:', plotted.pn) console.log('LID:', plotted.lid) ``` -------------------------------- ### Start and Make Move in Tic Tac Toe Source: https://context7.com/firdausmntp/baileys-joss/llms.txt Initiates a Tic Tac Toe game between two players and processes moves. Displays the game board and indicates the winner or if it's a draw. ```typescript // === TIC TAC TOE === const tttSession = games.startTictactoe(jid, player1Jid, player2Jid) await sock.sendMessage(jid, { text: `TicTacToe dimulai!\nPlayer X: ${player1Jid}\nPlayer O: ${player2Jid}\n\nKetik 1-9 untuk memilih posisi.` }) // Make move (position 0-8) const moveResult = games.tictactoeMove(tttSession.id, player1Jid, 4) // center console.log(moveResult.valid) console.log(moveResult.board) // Rendered board console.log(moveResult.winner) // Winner JID jika ada console.log(moveResult.draw) // true jika seri await sock.sendMessage(jid, { text: moveResult.message }) ``` -------------------------------- ### Create JID Plotter with LID Mapping Source: https://github.com/firdausmntp/baileys-joss/blob/main/README.md Create an advanced JID plotter that supports bidirectional mapping between Phone Numbers (PN) and Linked IDs (LID). Requires functions to get LID for PN and PN for LID. ```typescript const plotter = createJidPlotter( sock.lidMapping.getLIDForPN.bind(sock.lidMapping), sock.lidMapping.getPNForLID.bind(sock.lidMapping) ) const plotted = await plotter.plotBidirectional('6281234567890@s.whatsapp.net') console.log('Phone:', plotted.pn) console.log('LID:', plotted.lid) ``` -------------------------------- ### Get All Pending Scheduled Messages Source: https://context7.com/firdausmntp/baileys-joss/llms.txt Retrieve a list of all messages currently waiting to be sent by the scheduler. Use the 'getPending' method. ```typescript // Get all pending messages const pending = scheduler.getPending() console.log('Pending:', pending.length) ``` -------------------------------- ### Get Current Session Info Source: https://context7.com/firdausmntp/baileys-joss/llms.txt Retrieve information about the current WhatsApp session, including phone number, JID, LID, device ID, and push name. Requires the 'sock.authState'. ```typescript import { getCurrentSenderInfo } from 'baileys-joss' // Get current session info const senderInfo = getCurrentSenderInfo(sock.authState) console.log('Phone:', senderInfo?.phoneNumber) // 6281234567890 console.log('Phone JID:', senderInfo?.phoneJid) // 6281234567890@s.whatsapp.net console.log('LID:', senderInfo?.lid) // lid@s.whatsapp.net console.log('Device ID:', senderInfo?.deviceId) // 0, 1, 2... console.log('Push Name:', senderInfo?.pushName) // Nama WhatsApp ``` -------------------------------- ### Get Current Sender Information Source: https://github.com/firdausmntp/baileys-joss/blob/main/README.md Retrieve information about the current WhatsApp session, including phone number, JID, LID, device ID, and push name. ```typescript const senderInfo = getCurrentSenderInfo(sock.authState) console.log('Phone:', senderInfo.phoneNumber) console.log('Phone JID:', senderInfo.phoneJid) console.log('LID:', senderInfo.lid) console.log('Device ID:', senderInfo.deviceId) console.log('Name:', senderInfo.pushName) ``` -------------------------------- ### Create and Configure Anti-Spam System Source: https://context7.com/firdausmntp/baileys-joss/llms.txt Initializes an anti-spam system with various configuration options including rate limiting, duplicate message detection, and custom spam patterns. Includes a callback for handling detected spam. ```typescript import { createAntiSpam, COMMON_SPAM_PATTERNS } from 'baileys-joss' const antispam = createAntiSpam({ maxMessagesPerMinute: 15, maxDuplicates: 3, duplicateWindow: 60000, // 1 minute minMessageDelay: 500, maxMessageLength: 5000, spamPatterns: COMMON_SPAM_PATTERNS, whitelist: ['admin@s.whatsapp.net'], onSpamDetected: async (jid, message, result) => { console.log(`Spam detected from ${jid}`) console.log('Score:', result.score) console.log('Rules:', result.rules) console.log('Action:', result.action) if (result.action === 'warn') { await sock.sendMessage(jid, { text: 'āš ļø Warning: Spam detected!' }) } else if (result.action === 'mute') { antispam.muteUser(jid, 5 * 60 * 1000) // Mute 5 menit } } }) ``` -------------------------------- ### Get Remote JID from Message Source: https://github.com/firdausmntp/baileys-joss/blob/main/README.md Extract the chat JID and sender JID from a received message object. ```typescript sock.ev.on('messages.upsert', async ({ messages }) => { for (const msg of messages) { const { chatJid, senderJid } = getRemoteJidFromMessage(msg) console.log('Chat:', chatJid) console.log('Sender:', senderJid) } }) ``` -------------------------------- ### Create and Send vCard/Contact Card Source: https://context7.com/firdausmntp/baileys-joss/llms.txt Use `createContactCard` to send a single contact card or `createContactCards` for multiple. `quickContact` provides a simpler way to create basic contact objects. ```typescript import { createContactCard, createContactCards, quickContact, generateVCard } from 'baileys-joss' // Quick contact (simple) const simple = quickContact('John Doe', '+628123456789', { organization: 'PT Example', email: 'john@example.com' }) await sock.sendMessage(jid, createContactCard(simple)) ``` ```typescript // Full vCard dengan semua detail const fullContact = { fullName: 'Dr. John Doe', displayName: 'John D.', organization: 'Hospital ABC', title: 'Senior Doctor', phones: [ { number: '+628123456789', type: 'CELL' }, { number: '+622112345678', type: 'WORK' } ], emails: [ { email: 'john@hospital.com', type: 'WORK' }, { email: 'john.personal@gmail.com', type: 'HOME' } ], urls: [ { url: 'https://linkedin.com/in/johndoe', type: 'WORK' } ], addresses: [{ street: 'Jl. Sudirman No. 123', city: 'Jakarta', state: 'DKI Jakarta', postalCode: '12345', country: 'Indonesia', type: 'WORK' }], birthday: '1990-05-15', note: 'Met at conference 2024' } await sock.sendMessage(jid, createContactCard(fullContact)) ``` ```typescript // Send multiple contacts const contacts = [ quickContact('Alice', '+628111111111'), quickContact('Bob', '+628222222222'), quickContact('Charlie', '+628333333333') ] await sock.sendMessage(jid, createContactCards(contacts)) ``` ```typescript // Generate raw vCard string const vcardString = generateVCard(fullContact) console.log(vcardString) ``` -------------------------------- ### Create Interactive Quick Reply Buttons Source: https://context7.com/firdausmntp/baileys-joss/llms.txt Generate quick reply buttons for users to select options. Requires importing 'generateQuickReplyButtons'. Handles button responses via 'messages.upsert' event. ```typescript import { generateQuickReplyButtons } from 'baileys-joss' const quickButtons = generateQuickReplyButtons( 'Pilih opsi di bawah ini:', // Body text [ { id: 'btn-1', displayText: 'āœ… Setuju' }, { id: 'btn-2', displayText: 'āŒ Tolak' }, { id: 'btn-3', displayText: 'šŸ“ž Hubungi CS' } ], { footer: 'Powered by Baileys-Joss', title: 'Menu Pilihan' } ) await sock.sendMessage(jid, quickButtons) // Handle button response sock.ev.on('messages.upsert', async ({ messages }) => { for (const msg of messages) { const buttonResponse = msg.message?.buttonsResponseMessage if (buttonResponse) { console.log('Button clicked:', buttonResponse.selectedButtonId) console.log('Display text:', buttonResponse.selectedDisplayText) } } }) ``` -------------------------------- ### Get WhatsApp Channel Metadata Source: https://github.com/firdausmntp/baileys-joss/blob/main/README.md Retrieve metadata for a WhatsApp Channel, including the number of subscribers. Requires the channel's JID. ```typescript const metadata = await sock.newsletterMetadata('jid', channelJid) console.log('Subscribers:', metadata.subscribers) ``` -------------------------------- ### Get WhatsApp Channel Metadata Source: https://context7.com/firdausmntp/baileys-joss/llms.txt Retrieve metadata for a WhatsApp Channel, including its name and subscriber count. This provides an overview of the channel's status. ```typescript // Get channel metadata const metadata = await sock.newsletterMetadata('jid', channelJid) console.log('Name:', metadata.name) console.log('Subscribers:', metadata.subscribers) ``` -------------------------------- ### Import JID Utilities Source: https://github.com/firdausmntp/baileys-joss/blob/main/README.md Import various utility functions for parsing, normalizing, and manipulating WhatsApp JIDs (Jabber IDs) and phone numbers. ```typescript import { parseJid, getSenderPn, getCurrentSenderInfo, isSelf, plotJid, normalizePhoneToJid, extractPhoneNumber, formatJidDisplay, isSameUser, getJidVariants, getRemoteJidFromMessage, createJidPlotter } from 'baileys-joss' ``` -------------------------------- ### Get Remote JID from Message Source: https://context7.com/firdausmntp/baileys-joss/llms.txt Extract the chat JID and sender JID from a message object. Useful for identifying message origins. Use 'getRemoteJidFromMessage'. ```typescript import { getRemoteJidFromMessage } from 'baileys-joss' // Get sender dari message sock.ev.on('messages.upsert', async ({ messages }) => { for (const msg of messages) { const { chatJid, senderJid } = getRemoteJidFromMessage(msg) || {} console.log('Chat:', chatJid) console.log('Sender:', senderJid) } }) ``` -------------------------------- ### Format JID for Display Source: https://context7.com/firdausmntp/baileys-joss/llms.txt Create a human-readable representation of a JID, with options to show device and type information. Use 'formatJidDisplay'. ```typescript import { formatJidDisplay } from 'baileys-joss' // Format JID untuk display const display = formatJidDisplay('6281234567890:1@s.whatsapp.net', { showDevice: true, showType: true }) console.log(display) // 6281234567890:1 (PN) ``` -------------------------------- ### Generate PNG QR Code Buffer Source: https://context7.com/firdausmntp/baileys-joss/llms.txt Create a PNG image buffer of the QR code, which can be saved to a file or used directly. Requires the 'fs' module for file writing. ```typescript import { QRHelper } from 'baileys-joss' import fs from 'fs' // Generate PNG buffer const pngBuffer = await QRHelper.buffer(pairingCode) fs.writeFileSync('qr.png', pngBuffer) ``` -------------------------------- ### Get WhatsApp Group Metadata Source: https://context7.com/firdausmntp/baileys-joss/llms.txt Retrieve metadata for a WhatsApp group, including its subject, description, owner, and participant details. This is useful for understanding group properties. ```typescript const metadata = await sock.groupMetadata(groupJid) console.log('Group Name:', metadata.subject) console.log('Description:', metadata.desc) console.log('Owner:', metadata.owner) console.log('Members:', metadata.participants.length) console.log('Admins:', metadata.participants.filter(p => p.admin).length) ``` -------------------------------- ### Get Global Chat Statistics Source: https://context7.com/firdausmntp/baileys-joss/llms.txt Obtain overall statistics across all chats, including total counts of chats, messages, contacts, and groups. Identifies the most active chat. ```typescript // Global stats semua chat const globalStats = analytics.getGlobalStats() console.log('Total chats:', globalStats.totalChats) console.log('Total messages:', globalStats.totalMessages) console.log('Total contacts:', globalStats.totalContacts) console.log('Total groups:', globalStats.totalGroups) console.log('Most active chat:', globalStats.mostActiveChat?.jid) ``` -------------------------------- ### Generate Quick Reply Buttons Source: https://github.com/firdausmntp/baileys-joss/blob/main/README.md Use `generateQuickReplyButtons` to create messages with predefined reply options. Useful for simple user choices. ```typescript import { generateInteractiveButtonMessage, generateInteractiveListMessage, generateTemplateMessage, generateCombinedButtons, generateCopyCodeButton, generateUrlButtonMessage, generateQuickReplyButtons } from 'baileys-joss' // Quick Reply Buttons const quickButtons = generateQuickReplyButtons( 'Pilih opsi di bawah ini:', [ { id: 'btn-1', displayText: 'āœ… Setuju' }, { id: 'btn-2', displayText: 'āŒ Tolak' }, { id: 'btn-3', displayText: 'šŸ“ž Hubungi CS' } ], { footer: 'Powered by Baileys-Joss' } ) await sock.sendMessage(jid, quickButtons) ``` -------------------------------- ### Get Anti-Spam System Statistics Source: https://context7.com/firdausmntp/baileys-joss/llms.txt Retrieves statistics from the anti-spam system, including the total number of users, muted users, banned users, and total warnings issued. ```typescript // Get stats const stats = antispam.getStats() console.log('Total users:', stats.totalUsers) console.log('Muted:', stats.mutedUsers) console.log('Banned:', stats.bannedUsers) console.log('Total warnings:', stats.totalWarnings) ``` -------------------------------- ### Create WhatsApp Styled QR Code Source: https://context7.com/firdausmntp/baileys-joss/llms.txt Generate a QR code specifically styled to match WhatsApp's appearance, using a provided pairing code. ```typescript import { createWhatsAppQR } from 'baileys-joss' // WhatsApp-styled QR const waQR = await createWhatsAppQR(pairingCode) ``` -------------------------------- ### Get Top Participants in Group Source: https://context7.com/firdausmntp/baileys-joss/llms.txt Identify and rank the most active participants in a group chat based on message count. Specify the group JID and the number of top participants to retrieve. ```typescript // Top participants in group const topParticipants = analytics.getTopParticipants(groupJid, 5) for (const p of topParticipants) { console.log(`${p.participant}: ${p.count} messages`) } ``` -------------------------------- ### Get Chat Statistics Source: https://context7.com/firdausmntp/baileys-joss/llms.txt Retrieve detailed statistics for a specific chat. This includes message counts, media usage, and activity patterns. The optional time range can filter the data. ```typescript // Get stats untuk chat tertentu const chatStats = analytics.getChatStats('6281234567890@s.whatsapp.net') if (chatStats) { console.log('Total messages:', chatStats.totalMessages) console.log('From me:', chatStats.messagesFromMe) console.log('From others:', chatStats.messagesFromOthers) console.log('Media count:', chatStats.mediaCount) console.log('Link count:', chatStats.linkCount) console.log('Emoji count:', chatStats.emojiCount) console.log('Most active hour:', chatStats.mostActiveHour + ':00') console.log('Most active day:', chatStats.mostActiveDay) console.log('Avg messages/day:', chatStats.averageMessagesPerDay) console.log('Avg message length:', chatStats.averageMessageLength) console.log('First message:', chatStats.firstMessageTime) console.log('Last message:', chatStats.lastMessageTime) // Message breakdown by type console.log('Messages by type:', chatStats.messagesByType) // { text: 150, image: 45, video: 12, audio: 8, document: 5, ... } } ``` ```typescript // Stats dengan time range const stats = analytics.getChatStats(jid, { start: new Date('2024-01-01'), end: new Date('2024-12-31') }) ``` -------------------------------- ### Format JID for Display Source: https://github.com/firdausmntp/baileys-joss/blob/main/README.md Format a JID string for user-friendly display, with options to show device and type information. ```typescript const display = formatJidDisplay('6281234567890:1@s.whatsapp.net', { showDevice: true, showType: true }) // -> 6281234567890:1 (PN) ``` -------------------------------- ### Create WhatsApp Channel/Newsletter Source: https://context7.com/firdausmntp/baileys-joss/llms.txt Create a new WhatsApp Channel or Newsletter with a specified name and description. This is the first step in managing channel content. ```typescript // Create newsletter/channel await sock.newsletterCreate('My Channel', 'Channel description') ``` -------------------------------- ### Quick Template Rendering Source: https://github.com/firdausmntp/baileys-joss/blob/main/README.md Render a template string directly without a manager, useful for simple, one-off templating needs. ```typescript const quick = renderTemplate( 'Hi {{name}}, your order #{{orderId}} is {{status:processing}}', { name: 'Alice', orderId: '123' } ) ``` -------------------------------- ### Create and Send Bulk Messages Source: https://context7.com/firdausmntp/baileys-joss/llms.txt Use `createBulkSender` to configure and send messages to multiple recipients. Options include delays, retries, and progress/error callbacks. Supports sending the same message to many JIDs or different messages to different JIDs. A quick helper `sendBulkMessages` is also available. ```typescript import { createBulkSender, sendBulkMessages } from 'baileys-joss' const bulkSender = createBulkSender( (jid, content) => sock.sendMessage(jid, content), { delayBetweenMessages: 2000, // 2 detik delay randomDelay: 1000, // Random 0-1 detik tambahan maxRetries: 2, continueOnError: true, onProgress: (progress) => { console.log(`Progress: ${progress.sent}/${progress.total} (${progress.percentage}%)`) console.log(`Current: ${progress.currentJid}`) }, onMessageSent: (result) => { console.log(`Sent to ${result.jid}: ${result.success}`) }, onError: (jid, error) => { console.log(`Error ${jid}: ${error.message}`) }, onComplete: (results) => { const success = results.filter(r => r.success).length console.log(`Selesai: ${success}/${results.length} berhasil`) } } ) // Kirim pesan yang sama ke banyak JID const jids = [ '6281234567890@s.whatsapp.net', '6281234567891@s.whatsapp.net', '6281234567892@s.whatsapp.net' ] const results = await bulkSender.sendToMany(jids, { text: 'Hello everyone!' }) // Kirim pesan berbeda ke JID berbeda const messages = [ { jid: '6281234567890@s.whatsapp.net', content: { text: 'Hi John!' } }, { jid: '6281234567891@s.whatsapp.net', content: { text: 'Hi Jane!' } } ] await bulkSender.send(messages) // Stop bulk messaging jika sedang berjalan bulkSender.stop() // Quick helper tanpa membuat instance await sendBulkMessages( (jid, content) => sock.sendMessage(jid, content), jids, { text: 'Broadcast message' } ) ``` -------------------------------- ### Render Preset Message Template Source: https://github.com/firdausmntp/baileys-joss/blob/main/README.md Render a predefined message template like 'order_confirmation' with dynamic data. Requires `createTemplateManager`. ```typescript const orderConfirmation = templates.render('order_confirmation', { orderId: 'ORD-12345', customerName: 'John Doe', orderDate: '2024-01-15', items: '1x Product A\n2x Product B', total: '150,000' }) await sock.sendMessage(jid, { text: orderConfirmation }) ``` -------------------------------- ### Generate Terminal QR Code Source: https://context7.com/firdausmntp/baileys-joss/llms.txt Quickly generate a QR code string suitable for display in a terminal. Requires a pairing code. ```typescript import { QRHelper } from 'baileys-joss' // Quick QR generation const terminalQR = await QRHelper.terminal(pairingCode) console.log(terminalQR) ``` -------------------------------- ### Add Custom Spam Rule to Anti-Spam System Source: https://context7.com/firdausmntp/baileys-joss/llms.txt Demonstrates how to add a custom spam detection rule to the anti-spam system, specifying patterns and the action to take when the rule is triggered. ```typescript // Add custom spam rule antispam.addRule({ id: 'promo_spam', name: 'Promotional Spam', type: 'pattern', enabled: true, config: { patterns: [/FREE\s+\d+\s+TOKEN/i, /CLICK\s+HERE.*WIN/i] }, action: 'delete' }) ``` -------------------------------- ### Create and Manage Auto-Reply Rules Source: https://context7.com/firdausmntp/baileys-joss/llms.txt Implement an auto-reply system using `createAutoReply`. Rules can be defined by keywords, regex patterns, exact matches, or dynamic responses. Options include cooldowns, group/private chat restrictions, and allowed/blocked JIDs. Rules can be managed (enabled, disabled, removed) after creation. ```typescript import { createAutoReply } from 'baileys-joss' const autoReply = createAutoReply( (jid, content, options) => sock.sendMessage(jid, content, options), (jid, presence) => sock.sendPresenceUpdate(presence, jid), { simulateTyping: true, typingDuration: 1500, globalCooldown: 1000, onReply: (rule, message, response) => { console.log(`Auto-replied with rule: ${rule.id}`) } } ) // Rule berdasarkan keywords autoReply.addRule({ keywords: ['harga', 'price', 'biaya'], response: { text: 'Silakan cek katalog kami di example.com' }, cooldown: 60000, // 1 menit cooldown per user quoted: true // Reply dengan quote }) // Rule dengan regex pattern autoReply.addRule({ pattern: /^(hi|hello|halo|hay)/i, response: { text: 'Hai! Ada yang bisa dibantu?' }, privateOnly: true // Hanya di private chat }) // Rule dengan dynamic response autoReply.addRule({ keywords: ['order'], response: async (message, match) => { const orderId = Date.now() return { text: `Terima kasih! Order ID: ${orderId}` } } }) // Rule dengan exact match autoReply.addRule({ exactMatch: '/menu', response: { text: 'Menu:\n1. Help\n2. Info\n3. Contact' }, groupsOnly: true // Hanya di grup }) // Rule dengan filter JID autoReply.addRule({ keywords: ['admin'], response: { text: 'Pesan untuk admin' }, allowedJids: ['6281234567890@s.whatsapp.net'], blockedJids: ['6289999999999@s.whatsapp.net'] }) // Proses pesan masuk sock.ev.on('messages.upsert', async ({ messages }) => { for (const msg of messages) { if (!msg.key.fromMe) { const replied = await autoReply.processMessage(msg) if (replied) console.log('Auto-replied!') } } }) // Manage rules autoReply.setRuleActive('rule-id', false) // Disable rule autoReply.removeRule('rule-id') const rules = autoReply.getRules() ``` -------------------------------- ### Manage Broadcast Lists Source: https://github.com/firdausmntp/baileys-joss/blob/main/README.md Create, manage, and send messages to broadcast lists. Requires a function to send messages via `sock.sendMessage`. ```typescript const broadcast = createBroadcastManager( (jid, content) => sock.sendMessage(jid, content) ) const customerList = broadcast.create({ name: 'VIP Customers', description: 'Premium customers for promo', recipients: [ '6281234567890@s.whatsapp.net', '6281234567891@s.whatsapp.net' ] }) broadcast.addRecipients(customerList.id, [ '6281234567892@s.whatsapp.net' ]) const result = await broadcast.broadcast( customerList.id, { text: 'šŸŽ‰ Special promo for VIP customers!' }, { delay: 2000, onProgress: (sent, total, jid) => { console.log(`Sending ${sent}/${total}: ${jid}`) } } ) console.log(`Sent: ${result.sent}, Failed: ${result.failed}`) const stats = broadcast.getStats() console.log(`Total lists: ${stats.totalLists}, Recipients: ${stats.totalRecipients}`) const json = broadcast.export() broadcast.import(json) ``` -------------------------------- ### Custom QR Code Generator Source: https://context7.com/firdausmntp/baileys-joss/llms.txt Instantiate a custom QR code generator with specific options for size, error correction level, foreground color, and margin. Then use it to generate QR codes from data. ```typescript import { createQRGenerator } from 'baileys-joss' // Custom generator dengan options const generator = createQRGenerator({ size: 256, errorCorrectionLevel: 'H', foregroundColor: '#000000', margin: 4 }) const qr = await generator.generate(data) ``` -------------------------------- ### Post Video Status Source: https://context7.com/firdausmntp/baileys-joss/llms.txt Upload a video to your WhatsApp status using `StatusHelper.video`. Supports video files from a buffer. ```typescript // Video status const videoBuffer = fs.readFileSync('./my-video.mp4') await sock.sendMessage(statusJid, StatusHelper.video(videoBuffer, 'Video caption')) ``` -------------------------------- ### Create URL and Copy Code Buttons Source: https://context7.com/firdausmntp/baileys-joss/llms.txt Generate buttons to open URLs or copy code snippets. Use 'generateUrlButtonMessage' for links and 'generateCopyCodeButton' for codes. Supports multiple URL buttons. ```typescript import { generateUrlButtonMessage, generateCopyCodeButton } from 'baileys-joss' // URL Button - satu atau lebih link const urlButton = generateUrlButtonMessage( 'Kunjungi website kami untuk info lebih lanjut', [ { displayText: '🌐 Buka Website', url: 'https://example.com' }, { displayText: 'šŸ“± Download App', url: 'https://play.google.com' } ], { title: 'Info Produk', footer: 'Click untuk membuka' } ) await sock.sendMessage(jid, urlButton) // Copy Code Button - untuk OTP, kode promo, dll const copyButton = generateCopyCodeButton( 'šŸ” Kode OTP Anda adalah:', // Body text '123456', // Code to copy 'šŸ“‹ Copy Kode', // Button text { footer: 'Kode berlaku 5 menit' } ) await sock.sendMessage(jid, copyButton) ``` -------------------------------- ### Create and Render Custom Message Template Source: https://github.com/firdausmntp/baileys-joss/blob/main/README.md Define and use custom message templates with placeholders. Templates can be managed using `createTemplateManager`. ```typescript templates.create({ name: 'Welcome Message', content: `Halo {{name}}! šŸ‘‹\n\nSelamat datang di {{company}}!\n\nBerikut layanan kami:\n{{services}}\n\nContact: {{phone:021-12345678}}`, category: 'greeting' }) const welcome = templates.render('welcome_message', { name: 'Budi', company: 'PT Example', services: '- Layanan A\n- Layanan B\n- Layanan C' }) ``` -------------------------------- ### Post Image Status Source: https://context7.com/firdausmntp/baileys-joss/llms.txt Send an image as a WhatsApp status using `StatusHelper.image` with a buffer or `StatusHelper.imageUrl` with a URL. Captions are supported. ```typescript // Image status const imageBuffer = fs.readFileSync('./my-photo.jpg') await sock.sendMessage(statusJid, StatusHelper.image(imageBuffer, 'Caption')) ``` ```typescript // Image status dari URL await sock.sendMessage(statusJid, StatusHelper.imageUrl( 'https://example.com/photo.jpg', 'Photo caption' )) ``` -------------------------------- ### Create WhatsApp Group Source: https://context7.com/firdausmntp/baileys-joss/llms.txt Use this function to create a new WhatsApp group with specified participants. Requires the group name and a list of participant JIDs. ```typescript const group = await sock.groupCreate('My Group', [ '6281234567890@s.whatsapp.net', '6281234567891@s.whatsapp.net' ]) console.log('Group ID:', group.id) ``` -------------------------------- ### Mini Games API (Untested) Source: https://github.com/firdausmntp/baileys-joss/blob/main/README.md APIs for managing and playing mini-games. Note: These features are currently untested. ```APIDOC ## Mini Games API (UNTESTED āš ļø) ### Description Provides functionality for playing various mini-games. ### Classes & Functions - `MiniGamesManager`: The main class for managing all games. - `games.startGuessNumber()`: Starts a 'Guess the Number' game. - `games.startQuiz()`: Starts a quiz game. - `games.startTicTacToe()`: Starts a Tic Tac Toe game (playable against a bot or another player). - `games.playRockPaperScissors()`: Plays a Rock Paper Scissors game. - `games.rollDice()`: Rolls a dice, returning a number between 1 and 6. - `games.flipCoin()`: Flips a coin, returning heads or tails. - `games.handleGuess()`: Handles user input for guessing games. - `games.handleMove()`: Handles user moves in games like Tic Tac Toe. - `games.getLeaderboard()`: Retrieves the player leaderboard. ``` -------------------------------- ### Available Status Options Source: https://context7.com/firdausmntp/baileys-joss/llms.txt Lists available solid background colors and font options for status messages. These can be used to customize the appearance of text statuses. ```typescript // Available background colors console.log(STATUS_BACKGROUNDS.solid) // { green, blue, purple, red, orange, yellow, pink, teal, gray, black, white } ``` ```typescript // Available fonts (0-9) console.log(STATUS_FONTS) // { SANS_SERIF: 0, SERIF: 1, NORICAN: 2, BRYNDAN: 3, BEBASNEUE: 4, // OSWALD: 5, DAMION: 6, DANCING: 7, COMFORTAA: 8, EXOTWO: 9 } ```