### Basic @itsukichan/utils Bot Setup with Commands and Event Listeners Source: https://github.com/itsukichann/utils/blob/master/README.md This TypeScript example demonstrates a basic setup for a WhatsApp bot using the @itsukichan/utils library. It includes initializing the client, listening for the 'ClientReady' event, defining simple 'ping' and 'hi' commands, and setting up 'hears' handlers for text, sticker messages, arrays of keywords, and regular expressions. The bot is then launched. ```typescript const { Client, Events, MessageType } = require('@itsukichan/utils') const bot = new Client({ prefix: '!', printQRInTerminal: true, readIncommingMsg: true }) bot.ev.once(Events.ClientReady, (m) => { console.log(`ready at ${m.user.id}`) }) bot.command('ping', async(ctx) => ctx.reply({ text: 'pong!' })) bot.command('hi', async(ctx) => ctx.reply('hello! you can use string as a first parameter in reply function too!')) bot.hears('test', async(ctx) => ctx.reply('test 1 2 3 beep boop...')) bot.hears(MessageType.stickerMessage, async(ctx) => ctx.reply('wow, cool sticker')) bot.hears(['help', 'menu'], async(ctx) => ctx.reply('hears can be use with array too!')) bot.hears(/(using\s?)?regex/, async(ctx) => ctx.reply('or using regex!')) bot.launch() ``` -------------------------------- ### Custom MySQL Auth Adapter Setup Source: https://github.com/itsukichann/utils/blob/master/README.md This code example shows how to configure a custom authentication adapter using the `mysql-baileys` library. It demonstrates initializing a new client and assigning the `useMySQLAuthState` function to the `authAdapter` option for storing authentication sessions in a MySQL database. ```javascript // ... const { useMySQLAuthState } = require('mysql-baileys') // For more examples of using mysql-baileys, go to npmjs.com/mysql-baileys. const bot = new Client({ prefix: '!', readIncommingMsg: true, // directly assigned to authAdapter. authAdapter: useMySQLAuthState({ session: 'session', password: '', database: 'baileys', }) }) // ... ``` -------------------------------- ### Access Media Buffers and Streams Source: https://github.com/itsukichann/utils/blob/master/README.md Provides examples for accessing media content from messages. It shows how to get the media as a buffer or a stream for both the current message and a quoted message. ```typescript // Get current message media ctx.msg().media.toBuffer() ctx.msg().media.toStream() // Get quoted message media ctx.quoted().media.toBuffer() ctx.quoted().media.toStream() ``` -------------------------------- ### Install @itsukichan/utils using npm or yarn Source: https://github.com/itsukichann/utils/blob/master/README.md This code snippet shows how to install the @itsukichan/utils library using either npm or yarn package managers. ```bash npm install @itsukichan/utils # or yarn add @itsukichan/utils ``` -------------------------------- ### Event-Driven @itsukichan/utils Bot with Message Handling Source: https://github.com/itsukichann/utils/blob/master/README.md This TypeScript example shows how to build an event-driven WhatsApp bot using @itsukichan/utils. It configures the client with a prefix, enables QR printing and message reading, and then sets up event listeners for 'ClientReady' and 'MessagesUpsert'. The 'MessagesUpsert' handler specifically checks for incoming messages, ignores messages sent by the bot itself, and replies with 'Hi' if the message content is 'hello'. Finally, the bot is launched. ```typescript const { Client, Events } = require('@itsukichan/utils') const bot = new Client({ prefix: '!', // you can also use array or regex too, printQRInTerminal: true, readIncommingMsg: true }) bot.ev.once(Events.ClientReady, (m) => { console.log(`ready at ${m.user.id}`) }) bot.ev.on(Events.MessagesUpsert, (m, ctx) => { if(m.key.fromMe) return if(m.content === 'hello') { ctx.reply('Hi') } }) bot.launch() ``` -------------------------------- ### Create CTA URL Button Source: https://github.com/itsukichann/utils/blob/master/README.md Provides an example of creating a Call To Action (CTA) URL button using the `ButtonBuilder`. This button type allows users to navigate to a specified URL when clicked. It includes setting the button ID, display text, type, and the target URL. ```typescript const { ButtonBuilder } = require('@itsukichan/utils') let button = new ButtonBuilder() .setId('!ping') .setDisplayText('SPEED TEST') .setType('quick_reply') .build() let button2 = new ButtonBuilder() .setId('id2') .setDisplayText('copy here') .setType('cta_copy') .setCopyCode('hello world') .build() let button3 = new ButtonBuilder() .setId('id3') .setDisplayText('click here!') .setType('cta_url') .setURL('https://github.com/Itsukichann/Utils') .setMerchantURL('https://github.com/Itsukichann/Utils') .build() ctx.sendMessage(ctx.id, { text: 'This is text', footer: 'This is footer', title: 'This is title', interactiveButtons: [button, button2, button3] }, { quoted: ctx.msg }) ``` -------------------------------- ### Auto Mention Usage Example Source: https://github.com/itsukichann/utils/blob/master/README.md Illustrates the usage of the `autoMention` feature. When `autoMention` is enabled, a simple reply with '@' followed by a number is sufficient. When disabled, the `mentions` array must be explicitly provided with the user's JID. ```typescript // autoMention: true ctx.reply('Hello @62xxx') // autoMention: false, you must manually specify the mentions ctx.reply({ text: 'Hello @62xxx', mentions: ['62xxx@s.whatsapp.net'] }) ``` -------------------------------- ### Access Cooldown Properties Source: https://github.com/itsukichann/utils/blob/master/README.md Explains how to access properties of the `Cooldown` object, specifically `onCooldown` to check if a user is currently on cooldown, and `timeleft` to get the remaining cooldown time in milliseconds. ```typescript // Cooldown props /* check if sender is on cooldown */ cd.onCooldown // boolean /* check the cooldown time left (in ms) */ cd.timeleft // number ``` -------------------------------- ### Get Mentioned User JIDs Source: https://github.com/itsukichann/utils/blob/master/README.md Explains how to retrieve an array of JIDs for users mentioned in a message using ctx.getMentioned(). This is useful for identifying mentioned participants in group chats. ```typescript ctx.getMentioned() // Returns an array of JIDs ``` -------------------------------- ### Get Device Information and Chat Type with Itsukichan Utils Source: https://github.com/itsukichann/utils/blob/master/README.md Explains how to retrieve device-specific information and check if a chat is a group. ctx.getDevice() can fetch a user's device details or the bot's own device, and ctx.isGroup() returns a boolean indicating if the current chat is a group. ```typescript /* get device */ ctx.getDevice(id) ctx.getDevice() // get the user device /* check whether the chat is a group */ ctx.isGroup() ``` -------------------------------- ### Set Up Command Handler with File Paths Source: https://github.com/itsukichann/utils/blob/master/README.md Illustrates how to set up a command handler for organizing commands into separate files. This involves importing the CommandHandler class, specifying the path to the command directory, and then loading the commands. An option to hide console logs during loading is also shown. ```javascript const { CommandHandler } = require('@itsukichan/utils') const path = require('path') /* ... */ const cmd = new CommandHandler(bot, path.resolve() + '/CommandsPath') cmd.load() //cmd.load(false) // hide log console /* ...bot.launch() */ ``` -------------------------------- ### Command File Structure with Types Source: https://github.com/itsukichann/utils/blob/master/README.md Shows the structure for individual command files, including the 'name' and 'code' properties. It also demonstrates how to define different handler types, such as 'hears', by adding a 'type' property. The 'code' property contains the asynchronous function to execute. ```javascript // command example module.exports = { name: 'ping', code: async (ctx) => { ctx.reply('pong!') }, } // Hears type example module.exports = { name: 'example name', type: 'hears', code: async (ctx) => { ctx.reply('Hello world!') }, booelan: true } ``` -------------------------------- ### Client Configuration Options for @itsukichan/utils Source: https://github.com/itsukichann/utils/blob/master/README.md This JavaScript object defines the available configuration options for the Client in the @itsukichan/utils library. It details parameters such as message prefix, read receipt settings, authentication directory, QR code display, session timeouts, online status marking, phone number for pairing, and custom authentication adapters. ```javascript module.exports = { /* The bot prefix */ prefix: Array | string | RegExp /* Should bot mark as read the incomming messages? - Default: false */ readIncommingMsg?: boolean /* Path to the auth/creds directory - Default: ./state */ authDir?: string /* Print the qr in terminal? - Default: false */ printQRInTerminal?: boolean /* Time taken to generate new qr in ms - Default: 60000 ms (1 minute) */ qrTimeout?: number /* Should the client mark as online on connect? - Default: true */ markOnlineOnConnect?: boolean /* The bot phone number starts with country code (e.g 62xxx), Used for pairing code purposes. */ phoneNumber?: string /* Connect the bot using pairing code method instead of qr method. - Default: false */ usePairingCode?: boolean /* Should a bot reply when the bot number itself uses its bot command? - Default: false */ selfReply?: boolean /* Optional specify a custom Whatsapp Web Version */ WAVersion?: [number, number, number] /* You can mention someone without having to enter each Whatsapp Jid into the `mentions` array. - Default: false */ autoMention?: boolean /* You can use custom adapters to store your bot's session auth state. The default will be stored locally with baileys default multi auth state. */ authAdapter?: Promise /* Browser configuration for the WhatsApp Web client. Default to be Chrome in Ubuntu. You should only set a valid/logical browser config, otherwise the pair will fail. */ browser?: WABrowserDescription } ``` -------------------------------- ### Define Commands with Options or Strings Source: https://github.com/itsukichann/utils/blob/master/README.md Demonstrates two ways to define bot commands: using a string alias or a detailed options object. The options object allows for more configuration. Both methods accept an asynchronous function that handles the command logic. ```typescript bot.command(opts: CommandOptions | string, code?: (ctx: Ctx) => Promise) // you can use the new command function code too! bot.command('ping', async(ctx) => ctx.reply('pong!')) // alternatively you can use the old one! module.exports = { /* command name */ name: string /* command aliases */ aliases?: Array /* command code */ code: (ctx: Ctx) => Promise } // example bot.command({ name: 'ping', code: async(ctx) => ctx.reply('pong!') }) ``` -------------------------------- ### Build Album Message with AlbumBuilder Source: https://github.com/itsukichann/utils/blob/master/README.md Creates an album message containing multiple media items (images and videos) from various sources like URLs, local paths, or buffers. Uses AlbumBuilder and provides options for caption and delay. Sends the album using a context method. ```typescript const { AlbumBuilder } = require('@itsukichan/utils') const album = new AlbumBuilder() .addImageFromUrl('https://files.catbox.moe/i7mnhq.jpg') .addImageFromPath('./local/image2.jpg') .addImageFromBuffer(ctx.getBuffer(global.config.bot.thumbnail)) .addVideoFromUrl('https://example.com/ay.mp4') .addVideoFromPath('./local/video.mp4') .addVideoFromBuffer(ctx.getBuffer(https://example.com/ay.mp4')) .setOptions({ caption: 'Hi there!', delay: 2000 }) .build() await ctx.sendAlbumMessage(ctx.id, album.medias, album.options) ``` -------------------------------- ### Group Creation and Invite Code Operations Source: https://github.com/itsukichann/utils/blob/master/README.md This snippet outlines methods for group management, including creating a new group with a subject and members, retrieving information about an invite code, and accepting an invite using either the code or a v4 invite message. ```typescript ctx.groups.create(subject: string, members: string[]) ctx.groups.inviteCodeInfo(code: string) ctx.groups.acceptInvite(code: string) ctx.groups.acceptInviteV4(key: string | proto.IMessageKeinviteMessage: proto.Message.IGroupInviteMessage) ``` -------------------------------- ### Access Bot and Context Information with Itsukichan Utils Source: https://github.com/itsukichann/utils/blob/master/README.md Demonstrates how to access various pieces of information from the bot instance and the message context. This includes bot readiness time, sender details, message arguments, quoted messages, and the bot's own user information. ```typescript /* get the bot ready at timestamp */ bot.readyAt /* get the current jid */ ctx.id // string ctx.decodedId // string /* get the array of arguments used */ ctx.args // Array /* get sender details */ ctx.sender /* get quoted */ ctx.quoted() /* get bot user */ ctx.me() /* get the message type */ ctx.getMessageType() /* accessing @itsukichan/baileys objects */ bot.core ctx.core ``` -------------------------------- ### Import Events Constant Source: https://github.com/itsukichann/utils/blob/master/README.md Shows how to import the 'Events' constant from the '@itsukichan/utils' package, which is necessary for subscribing to various bot events. ```typescript const { Events } = require('@itsukichan/utils') ``` -------------------------------- ### Send Various Message Types Source: https://github.com/itsukichann/utils/blob/master/README.md Illustrates how to send different types of messages using the ctx object, including text, images, audio, stickers, and videos. It also shows how to use ctx.sendFile for sending files with various options. ```typescript /* sending a message */ ctx.sendMessage(ctx.id, { text: 'hello' }) /* quote the message */ ctx.reply('hello') ctx.reply({ text: 'hello' }) /* send an image */ ctx.sendMessage(ctx.id, { image: { url: 'https://example.com/image.jpeg' }, caption: 'image caption' }) ctx.reply({ image: { url: 'https://example.com/image.jpeg' }, caption: 'image caption' }) /* send an audio file */ ctx.reply({ audio: { url: './audio.mp3' }, mimetype: 'audio/mp4', ptt: false }) // if 'ptt' is true, the audio will be send as voicenote /* send an sticker */ ctx.reply({ sticker: { url: './tmp/generatedsticker.webp' }}) /* send an video */ const fs = require('node:fs') ctx.reply({ video: fs.readFileSync('./video.mp4'), caption: 'video caption', gifPlayback: false }) /* send an all type */ ctx.sendFile(ctx.id, 'https://files.catbox.moe/i7mnhq.jpg', 'anu.jpeg', 'Hi there!', m) // image ctx.sendFile(ctx.id, 'https://example.mp4', 'anu.mp4', 'Hi there!', m) // video ctx.sendFile(ctx.id, 'https://example.mp3', 'anu.mp3', null, m) // audio ctx.sendFile(ctx.id, 'https://example.mp3', 'anu.ogg', null, m, { ptt: true }) // vn ``` -------------------------------- ### Format Text with Utility Functions Source: https://github.com/itsukichann/utils/blob/master/README.md Demonstrates how to use utility functions imported from '@itsukichan/utils' to format text with bold, italic, strikethrough, and code styles. It also shows how to apply quotes and inline code. ```typescript const { bold, inlineCode, italic, monospace, quote, strikethrough } = require('@itsukichan/utils') const str = 'Hello World' const boldString = bold(str) const italicString = italic(str) const strikethroughString = strikethrough(str) const quoteString = quote(str) const inlineCodeString = inlineCode(str) const monospaceString = monospace(str) ``` -------------------------------- ### Create Template Buttons Message with TemplateButtonsBuilder Source: https://github.com/itsukichann/utils/blob/master/README.md Constructs a message with template buttons, including URL, call, copy, and quick reply options. Uses the TemplateButtonsBuilder. The output is a message object with interactive buttons. ```typescript const { TemplateButtonsBuilder } = require('@itsukichan/utils') const templateButtons = new TemplateButtonsBuilder() .addURL({ displayText: 'library at Github', url: 'https://github.com/Itsukichann' }) .addCall({ displayText: 'call me', phoneNumber: '628xxx' }) .addCopy({ displayText: 'copy', copy: 'https://github.com/Itsukichann' }) .addQuickReply({ displayText: 'just a normal button', id: 'btn1' }) .build() // required build function at end ctx.sendMessage(ctx.id, { text: 'template buttons', templateButtons }) ``` -------------------------------- ### Handle Message Content and Downloads with Itsukichan Utils Source: https://github.com/itsukichann/utils/blob/master/README.md Explains how to determine the content type of a message and download media content. The ctx.getContentType function helps identify the media type, and ctx.downloadContentFromMessage facilitates the actual download process. ```typescript /* get content type */ ctx.getContentType(content: WAProto.IMessage | undefined) /* download content from message */ ctx.downloadContentFromMessage(downloadable: DownloadableMessage, type: MediaType, opts?: MediaDownloadOptions) ``` -------------------------------- ### Send Interactive Messages with Itsukichan Utils Source: https://github.com/itsukichann/utils/blob/master/README.md Shows how to send interactive messages, which allow for richer user interactions. This includes sending general interactive messages and replying with interactive content. Requires specifying message content and optional generation options. ```typescript /* using interactive message */ ctx.sendInteractiveMessage(jid: string, content: IInteractiveMessageContent, options: MessageGenerationOptionsFromContent | {} = {}) ctx.replyInteractiveMessage(content: IInteractiveMessageContent, options: MessageGenerationOptionsFromContent | {} = {}) ``` -------------------------------- ### Group Information and Settings Management Source: https://github.com/itsukichann/utils/blob/master/README.md This extensive snippet details various methods for interacting with and managing group properties. It covers retrieving group metadata, owner, name, description, checking admin status, toggling ephemeral messages, updating group settings, and managing pending members. ```typescript ctx.group(jid?: string) // jid is optional ctx.group().members() ctx.group().inviteCode() ctx.group().revokeInviteCode() ctx.group().joinApproval(mode: 'on' | 'off') ctx.group().leave() ctx.group().membersCanAddMemberMode(mode: 'on' | 'off') ctx.group().metadata() ctx.group().getMetadata(key: keyof GroupMetadata) ctx.group().name() ctx.group().description() ctx.group().owner() ctx.group().isAdmin(jid: string) ctx.group().isSenderAdmin() ctx.group().isBotAdmin() ctx.group().toggleEphemeral(expiration: number) ctx.group().updateDescription(description: number) ctx.group().updateSubject(subject: number) ctx.group().membersUpdate(members: string[], action: ParticipantAction) ctx.group().kick(members: string[]) ctx.group().add(members: string[]) ctx.group().promote(members: string[]) ctx.group().demote(members: string[]) ctx.group().pendingMembers() ctx.group().pendingMembersUpdate(members: string[], action: 'reject' | 'approve') ctx.group().approvePendingMembers(members: string[]) ctx.group().rejectPendingMembers(members: string[]) ctx.group().updateSetting(setting: 'announcement' | 'not_announcement' | 'locked' | 'unlocked') ctx.group().open() ctx.group().close() ctx.group().lock() ctx.group().unlock() ``` -------------------------------- ### Manage Message Read Status and Typing Indicators with Itsukichan Utils Source: https://github.com/itsukichann/utils/blob/master/README.md Shows how to mark messages as read and simulate typing or recording states. ctx.read() marks the message as read, while ctx.simulateTyping() and ctx.simulateRecording() provide visual feedback to the user. ```typescript /* read the message */ ctx.read() /* simulate typing or recording state */ ctx.simulateTyping() ctx.simulateRecording() ``` -------------------------------- ### Build Sections Message with SectionsBuilder Source: https://github.com/itsukichann/utils/blob/master/README.md Constructs a message with multiple sections, each containing rows of information. Uses the SectionsBuilder utility. Input is a context object for sending messages. ```typescript const { SectionsBuilder } = require('@itsukichan/utils') let section1 = new SectionsBuilder() .setDisplayText('Touch Me!') .addSection({ title: 'Title 1', rows: [{ header: 'Row Header 1', title: 'Row Title 1', description: 'Row Description 1', id: 'Row Id 1' }, { header: 'Row Header 2', title: 'Row Title 2', description: 'Row Description 2', id: 'Row Id 2' }] }) .addSection({ title: 'This is title 2', rows: [{ title: 'Ping', id: '!ping' }, { title: 'Hello world', id: 'hello world' }] }) .build() ctx.sendMessage(ctx.id, { text: 'This is text', footer: 'This is footer', title: 'This is title', interactiveButtons: [section1] }, { quoted: ctx.msg }) ``` -------------------------------- ### Send and Reply Messages with Itsukichan Utils Source: https://github.com/itsukichann/utils/blob/master/README.md Demonstrates how to send and reply to messages using the ctx.reply function. It supports both text strings and structured message objects. This functionality is core to bot communication. ```typescript /* replying message */ ctx.reply({ text: 'test' }) ctx.reply('you can use string as a first parameter too!') ``` -------------------------------- ### Download and Save Image Media Source: https://github.com/itsukichann/utils/blob/master/README.md This snippet demonstrates how to download an image message and save it to the local file system using Node.js 'fs' module. It requires the MessageType and Events constants from '@itsukichan/utils'. ```typescript const { MessageType } = require('@itsukichan/utils') const fs = require('node:fs') bot.ev.on(Events.MessagesUpsert, async(m, ctx) => { if(ctx.getMessageType() === MessageType.imageMessage) { const buffer = await ctx.msg.media.toBuffer() fs.writeFileSync('./saved.jpeg', buffer) } }) ``` -------------------------------- ### Handle Bot Commands and Message Events with Itsukichan Utils Source: https://github.com/itsukichann/utils/blob/master/README.md Illustrates how to define message handlers for specific text commands or message types. The bot.hears function allows listening for exact text matches or message types like stickers, enabling custom responses. ```typescript /* same with bot.command but without prefix */ bot.hears('test', async(ctx) => ctx.reply('test 1 2 3 beep boop...')) /* will be triggered when someone sends a sticker message */ const { MessageType } = require('@itsukichan/utils') bot.hears(MessageType.stickerMessage, async(ctx) => ctx.reply('wow, cool sticker')) ``` -------------------------------- ### Implement Command Cooldowns Source: https://github.com/itsukichann/utils/blob/master/README.md Shows how to implement command cooldowns using the `Cooldown` class to prevent users from spamming commands. The cooldown time is specified in milliseconds. The code checks if a user is on cooldown and provides feedback if they are. ```javascript const { Cooldown } = require('@itsukichan/utils') // import the Cooldown class bot.command('ping', async(ctx) => { const cd = new Cooldown(ctx, 8000) // add this. Cooldown time must be in milliseconds. if(cd.onCooldown) return ctx.reply(`Slow down! wait ${cd.timeleft}ms`) // if user has cooldown stop the code by return something. ctx.reply('pong!') }) ``` -------------------------------- ### Implement Middleware for Message Interception Source: https://github.com/itsukichann/utils/blob/master/README.md Demonstrates how to use middleware to intercept and process messages before they are handled by commands. The `next()` function is used to continue processing, while omitting it will terminate the message flow. Middleware can be used for pre-processing logic. ```typescript bot.use(async (ctx, next) => { // Pre-process logic here console.log(`received: ${JSON.stringify(ctx.used)}`) await next() }) ``` -------------------------------- ### Manage Bot Profile and User Blocking with Itsukichan Utils Source: https://github.com/itsukichann/utils/blob/master/README.md Demonstrates functions for modifying the bot's profile information and managing user blocks. bot.bio() allows changing the bot's status message, while bot.fetchBio() retrieves another user's bio. bot.block() and bot.unblock() control user blocking. ```typescript /* change the client about/bio */ bot.bio('Hi there!') /* fetch someone about/bio */ await bot.fetchBio('1234@s.whatsapp.net') /* block and unblock */ await bot.block('1234@s.whatsapp.net') await bot.unblock('1234@s.whatsapp.net') ``` -------------------------------- ### Create Carousel Message with CarouselBuilder Source: https://github.com/itsukichann/utils/blob/master/README.md Builds a carousel message with multiple cards, each capable of displaying content and buttons. Utilizes ButtonBuilder and CarouselBuilder. Requires media attachments for card headers. Output is an interactive message. ```typescript const { ButtonBuilder, CarouselBuilder } = require('@itsukichan/utils') let button = new ButtonBuilder() .setId('!ping') .setDisplayText('SPEED TEST') .setType('quick_reply') .build() let mediaAttachment = await ctx.prepareWAMessageMedia({ image: { url: 'https://files.catbox.moe/i7mnhq.jpg' } }, { upload: bot.core.waUploadToServer }) let cards = new CarouselBuilder() .addCard({ body: 'BODY 1', footer: 'FOOTER 1', header: { title: 'HEADER TITLE 1', /* card headers must have media attachments */ hasMediaAttachment: true, ...mediaAttachment }, nativeFlowMessage: { buttons: [button] } // needs at least 1 button }) .addCard({ body: 'BODY 2', footer: 'FOOTER 2', header: { title: 'HEADER TITLE 2', /* card headers must have media attachments */ hasMediaAttachment: true, ...mediaAttachment // you can use other media attachments }, nativeFlowMessage: { buttons: [button] } // needs at least 1 button }) .build() ctx.replyInteractiveMessage({ body: 'this is body', footer: 'this is footer', carouselMessage: { cards, } }) ``` -------------------------------- ### Await Messages with awaitMessages Source: https://github.com/itsukichann/utils/blob/master/README.md Shows how to use ctx.awaitMessages to wait for messages for a set duration. It uses a Promise to handle the collected messages or a catch block for timeouts. ```typescript ctx.awaitMessages({ time: 10000 }).then((m) => ctx.reply(`got ${m.length} array length`)).catch(() => ctx.reply('end')) ``` -------------------------------- ### Enable Auto Mention in Client Source: https://github.com/itsukichann/utils/blob/master/README.md This snippet demonstrates how to enable the `autoMention` option when initializing a new client. This feature allows users to be mentioned by directly typing '@' followed by their number, without manually adding their JID to the `mentions` array. ```typescript const bot = new Client({ // ... autoMention: true // enable this }) ``` -------------------------------- ### Generate VCard for Contact with VCardBuilder Source: https://github.com/itsukichann/utils/blob/master/README.md Creates a vCard representation for a contact, including full name, organization, and phone number. Uses the VCardBuilder utility. The output is a vCard object suitable for sending contact information. ```typescript const { VCardBuilder } = require('@itsukichan/utils') const vcard = new VCardBuilder() .setFullName('John Doe') // full name .setOrg('PT Mencari Cinta Sejati') // organization name .setNumber('62xxx') // phone number .build() // required build function at end ctx.reply({ contacts: { displayName: 'John D', contacts: [{ vcard }] } }) ``` -------------------------------- ### Control Middleware Execution Flow Source: https://github.com/itsukichann/utils/blob/master/README.md Explains how to control message flow within middleware. By omitting the `next()` call, the execution of commands can be blocked. This is useful for implementing conditional logic or access control before a command is processed. ```typescript bot.use(async (ctx, next) => { if(condition) return // Block await next() }) ``` -------------------------------- ### Delete Message Source: https://github.com/itsukichann/utils/blob/master/README.md Demonstrates how to delete a message using ctx.deleteMessage. It first sends a message and then uses its key to remove it. ```typescript let res = await ctx.reply('testing') ctx.deleteMessage(res.key) ``` -------------------------------- ### Manage Message Reactions with Itsukichan Utils Source: https://github.com/itsukichann/utils/blob/master/README.md Provides methods for adding reactions to messages. The ctx.react function can be used with a specific message ID and emoji, or more simply by reacting to the current message with an emoji. ```typescript /* add react */ ctx.react(jid: string, emoji: string, key?: WAProto.IMessageKey) ctx.react(ctx.id, '👀') ``` -------------------------------- ### Collect Messages with MessageCollector Source: https://github.com/itsukichann/utils/blob/master/README.md Demonstrates how to use MessageCollector to collect messages within a specified time. It listens for 'collect' events to process incoming messages and 'end' events to handle the collector's termination. ```typescript let col = ctx.MessageCollector({ time: 10000 }) // in milliseconds ctx.reply({ text: 'say something... Timeout: 10s' }) col.on('collect', (m) => { console.log('COLLECTED', m) // m is an Collections ctx.sendMessage(ctx.id, { text: `Collected: ${m.content}\nFrom: ${m.sender}` }) }) col.on('end', (collector, r) => { console.log('ended', r) // r = reason ctx.sendMessage(ctx.id, { text: `Collector ended` }) }) ``` -------------------------------- ### Send a Poll Message Source: https://github.com/itsukichann/utils/blob/master/README.md Illustrates how to send a poll message with custom name and options. The 'singleSelect' option can be set to true to allow only one choice. ```typescript ctx.sendPoll(ctx.id, { name: 'ini polling', values: ['abc', 'def'], singleSelect: true }) ``` -------------------------------- ### Edit Message Content Source: https://github.com/itsukichann/utils/blob/master/README.md Shows how to edit the content of a previously sent message. It first sends a message and then uses ctx.editMessage with the message key to update its text. ```typescript let res = await ctx.reply('old text') ctx.editMessage(res.key, 'new text') ``` -------------------------------- ### Trigger Function on Cooldown End Source: https://github.com/itsukichann/utils/blob/master/README.md Demonstrates how to use the `end` event of the `Cooldown` class to trigger a function when the cooldown period finishes. This event will always be triggered when the cooldown is over, regardless of whether the command was executed successfully or not. ```typescript // ⚠ Will always be triggered when the cooldown is over (even though the users only runs the command once) cd.on('end', () => { ctx.reply({ text: 'cd timeout' }) }) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.