Skip to main content

Overview

@kreisler/bot-wa-ts is a powerful TypeScript framework for building WhatsApp bots using the Baileys library. It provides a clean API for handling messages, media, stickers, and more. Package: @kreisler/bot-wa-ts
Version: 1.0.0
License: MIT

Installation

npm install @kreisler/bot-wa-ts

Quick Start

import { Whatsapp } from '@kreisler/bot-wa-ts';

const bot = new Whatsapp();

await bot.WAConnect();
await bot.loadHandlers();
await bot.loadCommands();

Classes

Whatsapp

Main WhatsApp bot client class that handles connections, messages, and commands.

Constructor

const bot = new Whatsapp();

Properties

upTime
number
Timestamp when the bot started (in milliseconds).
logger
any
Pino logger instance for debugging (set to silent by default).
sock
WASocket
The Baileys WhatsApp socket connection.
status
number
Current connection status (0 = disconnected).
qr
string | null | undefined
QR code string for WhatsApp authentication.
commands
Map<RegExp, CommandImport>
Map of registered commands with their RegExp patterns.
folderCreds
string
default:"'creds'"
Folder name for storing authentication credentials.

Methods

WAConnect()
Establishes connection to WhatsApp servers and handles authentication.
return
Promise<void>
Promise that resolves when connection is established.
await bot.WAConnect();
getMeInfo()
Retrieves the bot’s WhatsApp profile information.
return
Promise<{ id: string, name: string }>
Bot user information.
const info = await bot.getMeInfo();
console.log('Bot name:', info?.name);
sendMsgGroup()
Sends multiple messages to one or more chats with batch processing.
jids
string | string[]
required
WhatsApp JID(s) to send messages to (e.g., “[email protected]”).
media
AnyMessageContent[] | Promise<AnyMessageContent[]>
required
Array of message content to send.
options
MiscMessageGenerationOptions
Additional message options.
batchSize
number
default:"10"
Number of messages to send per batch.
return
Promise<(proto.WebMessageInfo | undefined)[]>
Array of sent message info objects.
const messages = [
  { text: 'Hello!' },
  { text: 'How are you?' }
];

await bot.sendMsgGroup(
  '[email protected]',
  messages
);
sendMsgGroupBatch()
Sends messages in controlled batches with delays to avoid rate limits.
jids
string | string[]
required
WhatsApp JID(s) to send messages to.
media
AnyMessageContent[] | Promise<AnyMessageContent[]>
required
Array of message content to send.
options
MiscMessageGenerationOptions
Additional message options.
batchSize
number
default:"5"
Number of messages per batch.
return
Promise<(proto.WebMessageInfo | undefined)[]>
Array of sent message info objects.
getTextMessage()
Extracts text content and message type from a WhatsApp message.
c
proto.IMessage | null | undefined
required
The message object to parse.
return
BodyMsg
Object containing body text and message type.
const { body, typeMessage } = bot.getTextMessage(message);
console.log('Message text:', body);
console.log('Message type:', typeMessage);
getMessageBody()
Extracts full message body including quoted messages.
c
proto.IMessage | null | undefined
required
The message object to parse.
return
MessageBody
Object with message body and quoted message body if present.
sendText()
Sends a text message to a chat.
jid
string
required
WhatsApp JID of the recipient.
str
AnyMessageContent
required
Message content to send.
op
MiscMessageGenerationOptions
default:"{}"
Additional options for the message.
return
Promise<void>
Promise that resolves when message is sent.
await bot.sendText(
  '[email protected]',
  { text: 'Hello from bot!' }
);
imageUrl2Base64()
Converts an image URL to base64 buffer with MIME type validation.
url
string
required
URL of the image to download.
return
Promise<[Buffer, string]>
Tuple containing the image buffer and MIME type.
const [buffer, mimeType] = await bot.imageUrl2Base64(
  'https://example.com/image.jpg'
);
console.log('Image type:', mimeType);
buffer2base64()
Converts a buffer to base64 data URL.
buffer
Buffer
required
The buffer to convert.
mimeType
string
required
MIME type of the image (e.g., ‘image/png’).
return
string
Base64 data URL string.
const dataUrl = bot.buffer2base64(buffer, 'image/png');
// Returns: "data:image/png;base64,iVBORw0KG..."
stickerGenerator()
Generates a WhatsApp sticker from image data.
mediaData
string | Buffer
required
Image data (path or buffer) to convert to sticker.
return
Promise<Buffer>
WebP sticker buffer.
const stickerBuffer = await bot.stickerGenerator(imageBuffer);
await bot.sock.sendMessage(jid, {
  sticker: stickerBuffer
});
stickerGeneratorFromPath()
Generates a sticker from an image path or buffer and returns it ready to send.
image
string | Buffer
required
Path to image file or image buffer.
return
Promise<AnyMessageContent>
Message content object ready to send as sticker.
const stickerMsg = await bot.stickerGeneratorFromPath('./image.jpg');
await bot.sock.sendMessage(jid, stickerMsg);
getMedia()
Downloads media from a WhatsApp message.
msg
DownloadableMessage
required
The downloadable message object.
type
MediaType
required
Type of media to download (‘image’, ‘video’, ‘audio’, ‘document’, ‘sticker’).
opt
MediaDownloadOptions
Options for downloading the media.
return
Promise<Buffer>
Buffer containing the downloaded media.
if (message.imageMessage) {
  const buffer = await bot.getMedia(
    message.imageMessage,
    'image'
  );
  // Process image buffer...
}
hasOwnProp()
Checks if an object has a nested property using dot notation.
obj
any
required
The object to check.
prop
string
required
Property path in dot notation (e.g., ‘user.profile.name’).
return
boolean
True if the property exists, false otherwise.
if (bot.hasOwnProp(message, 'extendedTextMessage.text')) {
  const text = message.extendedTextMessage.text;
}
getNestedProp()
Retrieves a nested property value from an object using dot notation.
obj
any
required
The object to retrieve from.
propPath
string
required
Property path in dot notation.
return
U | undefined
The property value or undefined if not found.
const caption = bot.getNestedProp<string>(
  message,
  'imageMessage.caption'
);
loadEvents()
Loads all WhatsApp event handlers (connection updates, message upsert, credentials).
return
Promise<void>
Promise that resolves when events are loaded.
await bot.loadEvents();
loadCommands()
Loads all bot commands from the commands directory.
return
Promise<void>
Promise that resolves when commands are loaded.
await bot.loadCommands();
console.log(`${bot.getCommands().length} commands loaded`);
loadHandlers()
Loads error handlers, anti-crash handlers, and command registration.
return
Promise<void>
Promise that resolves when handlers are loaded.
getCommands()
Returns all registered commands as an array of tuples.
return
[RegExp, CommandImport][]
Array of [pattern, command] tuples.
const commands = bot.getCommands();
commands.forEach(([pattern, cmd]) => {
  console.log('Pattern:', pattern);
});
findCommand()
Finds a command that matches the given string.
str
string
required
The string to test against command patterns.
return
[boolean, [RegExp, CommandImport] | []]
Tuple with match status and command if found.
const [found, [pattern, command]] = bot.findCommand('.ping');
if (found) {
  await command.cmd(bot, context, []);
}
send()
Sends various types of content to a chat.
id
string
required
WhatsApp JID of the recipient.
content
string | Media | AnyMessageContent
required
Content to send (text, Media object, or Baileys message content).
opts
MiscMessageGenerationOptions
Additional message options.
return
Promise<Message>
The sent message wrapped in Message class.
// Send text
await bot.send(jid, 'Hello!');

// Send media
const media = new Media(buffer, {
  mimetype: 'image/jpeg',
  size: buffer.length,
  text: 'Caption'
});
await bot.send(jid, media);

Message Class

Wrapper class for WhatsApp messages with helper methods.

Constructor

client
Whatsapp
required
The Whatsapp bot instance.
data
proto.IWebMessageInfo
required
The raw WhatsApp message data.

Properties

id
string
Unique message identifier.
author
User | GroupUser
The message sender.
content
string
Text content of the message.
isReply
boolean
Whether this message is a reply to another message.
isGroup
boolean
Whether the message was sent in a group.
fromMe
boolean
Whether the message was sent by the bot.
hasMedia
boolean
Whether the message contains media (image, video, document, etc.).
isViewOnce
boolean
Whether the message is a view-once message.
type
WaMessageTypes
The type of the message (conversation, imageMessage, etc.).

Methods

send()

Sends a message to the same chat.
content
AnyMessageContent
required
Content to send.
opts
MiscMessageGenerationOptions
Additional options.
return
Promise<proto.WebMessageInfo | undefined>
The sent message info.
await message.send({ text: 'Reply message' });

reply()

Replies to the message.
content
AnyMessageContent
required
Content to send as reply.
opts
MiscMessageGenerationOptions
Additional options.
return
Promise<proto.WebMessageInfo | undefined>
The sent reply message info.
await message.reply({ text: 'Thanks for your message!' });

react()

Reacts to the message with an emoji.
reaction
string
required
Emoji to react with.
return
Promise<proto.WebMessageInfo | undefined>
The reaction message info.
await message.react('👍');

delete()

Deletes the message.
return
Promise<Message>
Result of the delete operation.
await message.delete();

getChat()

Gets the chat where this message was sent.
return
Promise<Chat | Group>
Chat or Group instance.
const chat = await message.getChat();
if (chat.isGroup()) {
  console.log('Group name:', chat.name);
}

downloadMediaV2()

Downloads media from the message with file type detection.
return
Promise<FetchBuffer | undefined>
Object containing buffer and detected file type.
if (message.hasMedia) {
  const media = await message.downloadMediaV2();
  if (media) {
    console.log('File type:', media.fileType?.ext);
    // Process media.buffer...
  }
}

downloadMedia()

Downloads media and wraps it in a Media class instance.
return
Promise<Media> | undefined
Media instance with buffer and metadata.
const media = await message.downloadMedia();
if (media) {
  console.log('MIME type:', media.mimetype);
  console.log('Size:', media.size);
}

readMessage()

Marks the message as read.
return
Promise<void>
Promise that resolves when message is marked as read.
await message.readMessage();

getQuotedMsg()

Gets the quoted/replied message if this is a reply.
return
Message | undefined
The quoted message or undefined.
if (message.isReply) {
  const quoted = message.getQuotedMsg();
  console.log('Replying to:', quoted?.content);
}

getMentions()

Gets all users mentioned in the message.
return
Promise<User[]>
Array of mentioned users.
const mentions = await message.getMentions();
mentions.forEach(user => {
  console.log('Mentioned:', user.number);
});

Media Class

Represents media content with metadata.

Constructor

buffer
Buffer
required
The media buffer.
opts
object
required

Properties

buffer
Buffer
The media buffer data.
mimetype
string
MIME type (e.g., ‘image/jpeg’).
size
number
Size in bytes.
text
string | undefined
Caption text.
isImage
boolean
True if media is an image.
isVideo
boolean
True if media is a video.
isAudio
boolean
True if media is audio.
isDocument
boolean
True if media is a document.
viewOnce
boolean
Whether the media is view-once.

Static Methods

Media.create()

Creates a Media instance from a file path.
path
string
required
Path to the media file.
opts
object
required
return
Media
Media instance.
const media = Media.create('./photo.jpg', {
  mimetype: 'image',
  text: 'Check this out!'
});

await bot.send(jid, media);

User Class

Represents a WhatsApp user.

Properties

pushname
string | undefined
User’s display name.
number
string
User’s phone number.
id
string
WhatsApp JID.
countryCode
string
Country code.

Methods

getProfile()

Retrieves the user’s WhatsApp business profile.
return
Promise<WABusinessProfile>
Business profile information.

GroupUser Class

Extends User for group chat members.

Additional Properties

groupId
string
The group’s JID.
isAdmin
boolean
Whether the user is a group admin.

Methods

sendDM()

Sends a direct message to the user.
content
string | Media | AnyMessageContent
required
Content to send.
opts
MiscMessageGenerationOptions
Additional options.
await groupUser.sendDM('Private message!');

getGroup()

Gets the Group instance for this user’s group.
return
Promise<Group>
The Group instance.

Chat Class

Represents a WhatsApp chat.

Properties

id
string
Chat JID.

Methods

send()

Sends a message to the chat.
content
string | Media | AnyMessageContent
required
Content to send.
return
Promise<Message>
The sent message.

isGroup()

Checks if the chat is a group.
return
boolean
True if the chat is a group.

Group Class

Extends Chat for group chats.

Additional Properties

name
string
Group name.
description
string
Group description.

Methods

isAdmin()

Checks if a user is a group admin.
user
User
required
User to check.
return
boolean
True if the user is an admin.
const group = await message.getChat() as Group;
if (group.isAdmin(message.author)) {
  // User is admin
}

Interfaces

CommandImport

Command definition interface.
active
boolean
Whether the command is active.
ExpReg
RegExp
Regular expression pattern for matching.
cmd
(client: Whatsapp, context: ContextMsg, match: RegExpMatchArray) => Promise<void>
Command handler function.

ContextMsg

Context passed to command handlers.
wamsg
WAMessage
Raw WhatsApp message.
msg
Message
Wrapped Message instance.
body
string | null | undefined
Message text content.
typeMessage
WaMessageTypes
Message type.
quotedBody
BodyMsg | undefined
Quoted message body if present.

WaMessageTypes

Enum of WhatsApp message types.
enum WaMessageTypes {
  extendedTextMessage = 'extendedTextMessage',
  imageMessage = 'imageMessage',
  videoMessage = 'videoMessage',
  stickerMessage = 'stickerMessage',
  audioMessage = 'audioMessage',
  documentMessage = 'documentMessage',
  documentWithCaptionMessage = 'documentWithCaptionMessage',
  ephemeralMessage = 'ephemeralMessage',
  conversation = 'conversation',
  viewOnceMessage = 'viewOnceMessage',
  viewOnceMessageV2 = 'viewOnceMessageV2'
}

Usage Examples

Basic Bot Setup

import { Whatsapp } from '@kreisler/bot-wa-ts';

const bot = new Whatsapp();

await bot.WAConnect();
await bot.loadHandlers();
await bot.loadCommands();

console.log('Bot is ready!');

Creating a Command

import { CommandImport, ContextMsg } from '@kreisler/bot-wa-ts';

const pingCommand: CommandImport = {
  active: true,
  ExpReg: /^\.ping$/i,
  cmd: async (client, context, match) => {
    const { msg } = context;
    const start = Date.now();
    
    const sent = await msg.reply({ text: 'Pinging...' });
    const latency = Date.now() - start;
    
    await client.sock.sendMessage(
      sent.key.remoteJid!,
      { text: `Pong! ${latency}ms`, edit: sent.key }
    );
  }
};

export default pingCommand;

Handling Media Messages

bot.sock.ev.on('messages.upsert', async ({ messages }) => {
  for (const m of messages) {
    const message = new Message(bot, m);
    
    if (message.hasMedia && message.type === 'imageMessage') {
      const media = await message.downloadMediaV2();
      
      if (media) {
        await message.reply({
          text: `Received image: ${media.fileType?.ext}`
        });
      }
    }
  }
});

Creating Stickers

const imageBuffer = /* get image buffer */;
const stickerBuffer = await bot.stickerGenerator(imageBuffer);

await bot.sock.sendMessage(jid, {
  sticker: stickerBuffer
});

Batch Sending Messages

const recipients = [
  '[email protected]',
  '[email protected]',
  '[email protected]'
];

const messages = [
  { text: 'Hello!' },
  { text: 'This is a broadcast message' }
];

await bot.sendMsgGroupBatch(
  recipients,
  messages,
  {},
  5 // Send 5 messages at a time
);

Checking Nested Properties

if (bot.hasOwnProp(m.message, 'imageMessage.caption')) {
  const caption = bot.getNestedProp<string>(
    m.message,
    'imageMessage.caption'
  );
  console.log('Image caption:', caption);
}

Helper Functions

printLog()

Colored console logging utility.
message
string
required
Message to log.
color
'red' | 'green' | 'yellow' | 'cyan'
required
Console color.
import { printLog } from '@kreisler/bot-wa-ts';

printLog('Bot started successfully', 'green');
printLog('Warning: Low memory', 'yellow');
printLog('Error occurred', 'red');

Dependencies

  • baileys - WhatsApp Web API library
  • pino - Fast JSON logger
  • qrcode-terminal - QR code display in terminal
  • wa-sticker-formatter - WhatsApp sticker creation
  • @kreisler/bot-services - Shared bot services
  • @kreisler/createapi - API utilities
  • crypto-js - Cryptographic functions
  • file-type - File type detection

Build docs developers (and LLMs) love