@aidulcandra/simple-wa-bot
v23.0.2
Published
A baileys wrapper module
Downloads
310
Readme
simple-wa-bot
By aidulcandra. Email me at [email protected]
This module wraps baileys
What's New in 23.x
Bot
bot.removeProgram(uid)
Removes a program by its UID. A UID is now generated for each program. Can be accessed viaprogram.uid
Program
program.uid
Other
- Fix bugs
- Code refactor
Installation
npm install @aidulcandra/simple-wa-bot
Config File
When first run, a config file bot-config.json
will be created if not exists. Default config is as follows. You can save this as bot-config.json
to configure things beforehand.
{
// Array of owner/co-owners ids
"ownerIds": [],
// Whether to parse mentions into their usernames
"parseMentions": true,
// Whether to keep track of user pushnames and the changes.
// Will allow you to get a user's pushnames outside the event of receiving their message.
"recordPushnames": true,
// Auto read received messages (send double blue-tick mark)
"autoRead": false,
// List of prefixes that can be used to invoke commands
"commandPrefixes": ["/"],
// Command Menu Template
"commandMenu": {
// @categorylist will be replaced by category list
"menuTemplate": "> COMMAND LIST\n\n@categorylist\n\n_Created by: @aidulcandra_",
// @category will be replaced by category name, @commandlist will be replaced by the list of the commands
"categoryTemplate": "[@category]----\n@commandlist\n------------",
// Separator for each category list
"categorySeparator": "\n\n",
// @command will be replaced by command name, @description will be replaced by the description of the command
"commandTemplate": "`/@command` - @description",
// Separator for each command item
"commandSeparator": "\n"
}
}
Usage
const bot = require("@aidulcandra/simple-wa-bot");
// Receiving exact match of text and replying
bot.receive("Hello").reply("Hi there");
// Receiving text with similarity value (value is 0 thru 1)
bot.receive("Hello").similarity(0.6).reply("Hi there");
// Ignore case
bot.receive("Good morning").ignoreCase().reply("Good morning to you too!");
// Ignore case and check similarity
bot.receive("How are you?").ignoreCase().similarity(0.7).reply("I'm fine");
// Reply with image
bot
.receive("send pic")
.reply() // Insert string for caption
.image("https://url.to/your/image");
// Or path to your local image
// Multi input (will respond to either one)
bot.receive(["text1", "text2", "text3"]).reply("Yes");
// Only respond in private chats
bot.receive("hello").privateOnly().reply("hi");
// Only respond in group chats
bot.receive("hello").groupOnly().reply("hi");
// Only respond in specific chat rooms
bot.receive("hello").in("[email protected]").reply("hi");
// Only respond to specific id(s)
bot.receive("hello").from("[email protected]").reply("hi");
bot.receive("hello").from("[email protected]", "[email protected]").reply("hi");
bot
.receive("hello")
.from(["[email protected]", "[email protected]"])
.reply("hi");
// Respond to texts beginning with specific substring
bot.receiveBeginning("Do you").ignoreCase().reply("Maybe");
// Respond to texts containing specific substring
bot
.receiveContaining("ice cream")
.ignoreCase()
.reply("Did you say ICE CREAM???");
// Respond to texts ending with specific substring
bot.receiveEnding("?").ignoreCase().reply("You were asking?");
// Testing incoming message on a regex pattern
bot.receive(/Do you know .+ \?/i).reply("No.");
// RegEx pattern matching, use <<number>> to insert captured match (in order starting from 1)
bot.receive(/My name is (\w+)/).reply("Nice to meet you, <<1>>!");
// Custom condition (must input a function)
let isActive = true;
function checkActive() {
return isActive;
}
bot.receive("hey").if(checkActive).reply("heyo");
bot
.receive("test")
.if(function () {
return true;
})
.reply("test back");
// Random reply
bot.receive("Hi").ignoreCase().replyRandom("Hey", "Hello", "Sup?"); // Can input array
// Default response if no programs are executed
bot.defaultResponse("I don't understand.");
// Send
//Don't forget to start the bot after programming responses
bot.start();
// Instead of bot.start(), you can test your bot in the console using this
bot.test();
Custom Script
// Run script
bot.receive("date").run(function (message) {
const name = message.sender.name
const date = Date()
message.reply(`Hello, ${name}! Today's date is ${date}`)
})
// 2nd argument of the run function is the array of captured matches when using regex as input
bot.receive(/my name is (\w+)/i).run(function (message, matches)) {
message.reply(`Hello, ${matches[0]}!`)
}
// 3rd argument is the group if the message is received in a group
bot.receive("group name").run(function (msg, m, group) {
msg.reply(`The group name is ${group.name}`)
})
// 4th argument is the bot object
function (msg, m, group, bot) {}
// Can also provide path to module that exports a function
bot.receive("import").run("commands/import.js")
// Inside commands/import.js:
module.exports = async function (msg, m, group) {
msg.reply("I was called from outside")
}
The message
Object's Properties and Methods
| Name | Description | Example |
| --------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------ |
| message.id
| ID of the message objectmessage.text
|The text or caption of the message
message.isEdit
|Whether the message is an edit
| message.room
| Chat ID where this message was sent to | "[email protected]"
|
| message.sender
| An object of the sender's info |
| message.sender.name
| Sender's name |
| message.sender.id
| Sender's ID | "[email protected]"
|
| message.sender.isMe
| Whether the sender is the bot itself. |
message.sender.isBlacklisted
| Whether the sender is blacklisted
message.sender.isOwner
|Whether the sender is the owner or a co-owner
message.sender.getPPUrl()
|Get the profile picture url of the sender
| message.type
| Type of the message | "text"
, "image"
, "video"
, etc. |
message.isMedia
|Whether this message is a media message (image, video, document, audio, sticker)
message.image?
|Image object of the message
message.image?.getBuffer()
|Get the buffer object of the image
message.image?.saveTo(path)
|Save the image to path
message.video?
message.video?.getBuffer()
message.video?.saveTo(path)
|Save the video to path
message.audio?
message.audio?.getBuffer()
message.audio?.saveTo(path)
|Save the audio to path
message.sticker?
message.sticker?.getBuffer()
message.sticker?.saveTo(path)
|Save the sticker to path
message.document?
message.document?.getBuffer()
message.document?.saveTo(path)
|Save the document to path
message.mentions
| Array of mentioned ids |
| message.groupMentions
| Array of mentioned group ids |
| message.getBaileysMessage()
| Get the original baileys' MessageInfo object |
| message.reply(text)
| Reply to the message | message.reply("Of course")
|
message.replyImage(source, caption)
|Reply with image. source
can be a Buffer
or a string of url/path
message.replyVideo(source, caption)
|Reply with video
message.replyAudio(source, mimetype?)
|Reply with audio. Default mimetype is audio/mp4
message.replySticker(source, options)
|Reply with audio. Options: pack = string; author = string; type = 'default'/'crop'/'full'/'circle'/'rounded'; background=hex color string; quality = number
message.replyDocument(source, mimetype, fileName, caption)
|Reply with a document.
message.replyContacts(contacts)
| Reply with contact(s). contacts
is an array of object {name, number}
message.edit(text)
|Edit this message (text only)
message.forward(to)
|Forward this message to target id
message.react(emoji)
|React to this message|message.react("😂")
message.delete()
|Delete this message. Remember to delete others' messages the bot needs to be an admin of the group|
message.read()
|"Read" the message. This will send the double blue-ticks mark to the sender's end.
message.saveTextTo(path)
|Save the text in the disk
The group
Object's Properties and Methods
Name|Description|Example
-|-|-
group.id
|Id of the group|"[email protected]"
group.getSubject()
|Get the subject (name) of the group
group.getParticipants()
|Get the list of participants and their admin status
group.mute()
|Only allow admins to send messages
group.unmute()
|Allow members to send messages
The bot
Object's Properties and Methods
Name|Description|Example
-|-|-
| bot.settings
| Contains settings that can be tweaked real time. |
| bot.settings.parseMentions
| Whether to parse mention numbers into username if has been recorded. It's recommended to set recordPushnames
to true as well. |
| bot.settings.recordPushnames
| Whether to keep track of pushnames |
| bot.settings.commandPrefixes
| Array of prefixes for popular command-style input | ["/", ".", "!"]
(Empty array for no prefix). Use in conjunction with bot.command()
|
| bot.receive(input(s))
| Register new message-response program | See explanations above. This returns a Program
object which can be chained to methods to modify this particular program. |
| bot.receiveBeginning(input(s))
| Register new program with the input as message beginning with a string |
| bot.receiveContaining(input(s))
| Register new program with the input as message containing with a string |
| bot.receiveEnding(input(s))
| Register new program with the input as message ending with a string |
| bot.receiveAny()
| Register new program responding to any message |
| bot.command(name, description)
| Register new program responding to a command-style input. Only input the command name, the program will automatically detect the prefix based on bot.settings.commandPrefixes
. Description will be displayed in the menu maker. | bot.command("check")
will read input /check
from user. You can also specify one or more parameters separated with space(s) and they will be treated like match captures for regex. Example: /check foo bar
will make the match array ["foo", "bar"]
. You can also use them using templating in your string (<<1>>
, <<2>>
, etc.). You can change the list of accepted prefixes in bot.settings.commandPrefixes
|
| bot.sent(input(s))
| Register new self-message response program (when a message was sent from the bot's number itself). Returns a Program
|
| bot.defaultResponse(text)
| If any other programs were not executed, send this text |
| bot.schedule(cronTime, timezone?)
| Trigger this program time-based. Uses cron time format documentation. Note: the format allows 1 extra field for second as the first field. So there can be 5 or 6 fields. timezone
is the timezone name. Check here or leave it (by default local timezone)| bot.schedule("*/5 * * * * *")
Triggers every five secondsbot.schedule("30 18 * * sun")
Triggers every Sunday at 6:30 PM|
| bot.start()
| Start the bot |
| bot.getConnectionState()
| Returns open
, connecting
, or closed
|
bot.sendText(targetId, text)
|Send a text to the chat id|bot.sendText("[email protected]", "Hello world")
bot.sendImage(targetId, source, caption)
|Send an image from given link to the chat id. source
can be a buffer or a string of path/url| bot.sendImage("[email protected]", "https://picsum.photos/300")
bot.sendVideo(targetId, source, caption)|Send a video
bot.sendAudio(targetId, source, mimetype)|Send an audio. Default mimetype:
"audio/mp4"
bot.sendSticker(targetId, source, options)|Send a sticker. Source is path to image, or an image buffer. Options: pack = string; author = string; type = 'default'/'crop'/'full'/'circle'/'rounded'; background=hex color string; quality = number
bot.sendDocument(targetId, source, mimetype, fileName, caption)|Send a document
bot.sendContacts(to, contacts)|Send one or more contacts. Contacts argument is an array of
{name, number}. The
number can include symbols (ex:
"+628123456789")
bot.sendLocation(to, latitude, longitude)|Send a location message. Latitude and longitude are in degrees.
bot.updateStatus(newStatus)|Change your status text|
bot.updateName(newName)|Change your display name|
bot.checkAdmin(id, groupId)|Check whether id is an admin of a group
bot.checkOwner(id)|Check whether id is the owner or a co-owner
bot.getPushnames()|Get the list of recorded pushnames
bot.getPushname(id)|Get last recorded pushname for this id
bot.getId()|Get the id of the bot
bot.getPPUrl(id, hq)|Get profile picture url from a user. Set
hqto
trueto get a high res image.
bot.getStatus(id)|Get status text from a user
bot.waitForMessage(roomId, options)|Wait for a message to appear in a room then return the message object.
options:
timeoutin ms (default 10000), and
filter, a function that can be used to filter messages|
bot.waitForMessage(roomId, {filter:msg=>msg.sender.id===ownerId})|
bot.setVar(name, value) | Set a variable |
setVar("count", 5) |
|
bot.getVar(name) | Get a variable's value |
getVar("my_var") |
|
bot.deleteVar(name) | Delete a variable |
|
bot.blacklistGetList() | Get an array of blacklisted ids |
|
bot.blacklistAdd(ids) | Add a number(s) or id(s) to the blacklist |
|
bot.blacklistRemove(ids) | Remove number(s) / id(s) from the blacklist |
|
bot.blacklistCheck(id) | Check if an id is blacklisted |
|
bot.createCommandMenu() | Create a string of auto generated menu for command list | See [here](#command-menu-template)|
bot.addOwner(ids)|Add id(s) to owner list. Can use arrays.
bot.removeOwner(ids)|Remove id(s) from owner list.
bot.addPrefix(prefix)|Add new prefix(es). Can use arrays.
bot.removePrefix(prefix)|Remove prefix(es).
bot.saveSettings()`|Save bot config file.
Programs
In this module there are types of Program
s that can be created using the bot
's trigger definers:
bot.receive()
,bot.receiveBeginning()
,bot.receiveContaining()
,bot.receiveEnding()
,bot.receiveAny()
,bot.command()
andbot.sent()
creates anInputReaderProgram
bot.started()
creates aStartupProgram
bot.schedule()
creates aScheduledProgram
Methods and Properties Of Program
Object (Program Modifiers)
These modifiers works for all type of Program
s
Method/Property|Description|Example
--|--|--
uid
|Unique identifier for each program|"a2090b87-e3bf-4ab7-9e4a-4e08defaa13e"
ifVarIs(name, value)
|Respond if variable's value is equal to something|ifVarIs("customers", 0)
|
ifVarExists(name)
|Respond if a variable exists|ifVarExists("money")
ifVarNotExists(name)
|Respond if a variable does not exist|ifVarNotExists("money")
if(conditionFunction)
|Custom condition (must input a function name). The function's only parameter is the message
|if(checkCustomers)
showTyping()
|Show the is typing ...
text before sending response
showRecording()
|Show the is recording ...
text before sending response
text(text)
|Send a text message as a response
textRandom(text)
|Randomly picks the response, can also pick from arrays|textRandom("choice1", "choice2", choice3")
image(link)
|Set the image to be sent in the response. Uses link or path
video(link)
|Set the video to be sent in the response.
audio(link, mimetype)
|Set the audio to be sent in the response. Mimetype: default set to audio/mp4
sticker(link, options)
|Set the sticker to be sent in the response. Options: pack = string; author = string; type = 'default'/'crop'/'full'/'circle'/'rounded'; background=hex color string; quality = number|sticker(link, {type:'crop', author:'SimpleBot'})
document(link, mimetype, fileName)
|Set the document to be sent in the response
contacts(contacts)
|Send a contact(s) (vcards) as a response. contacts
argument is an array of {name, number}
sendMenu()
|Send the command menu. See here.
to(ids)
|Assign id(s) to send responses to. Can be used to broadcast messages.
setVar(name,value)
|Set a variable when responding to the input
blacklist(ids)
|Assign id(s) to be blacklisted (multiple arguments or array). If not specified, blacklist the sender instead.
whitelist(ids)
|Assign id(s) to be whitelisted. If not specified, whitelist the sender instead.
run(callback or path)
|Run a custom script|See above
stopHere()
|Stop responding to any other programs after this
InputReaderProgram
's modifiers
Created with bot.receive()
, bot.receiveAny()
, bot.receiveBeginning()
, bot.receiveEnding()
, bot.receiveContaining()
, bot.sent()
. This basically is responding to an incoming message.
Method | Description | Example
--|--|--
in(ids)
|Respond only inside this chat id(s). Can input array or multiple arguments
from(ids)
|Only respond to this id(s). This will check the sender id, not the room id
notIn(ids)
|Don't respond inside this chat id(s)
notFrom(ids)
|Don't respond to this id(s)
privateOnly()
|Respond only to private messages
groupOnly()
|Respond only to group messages
adminOnly()
|Respond only to admins' messages (must be in a group)|
ownerOnly()
|Respond only to the owner or co-owners
mentionedOnly()
|Respond only to messages mentioning the bot. Keep in mind that the mentions are included in the text, so using exact match of text can't be done with this (using bot.receive()
). It's recommended to use this with regex type inputs, or bot.receiveContaining()
quotedOnly()
|Respond only to messages quoting the bot's message
withImage()
|Only respond to image messages
withVideo()
|Only respond to video messages
withAudio()
|Only respond to audio messages
withSticker()
|Only respond to sticker messages
withContacts()
|Only respond to contact messages
includeBlacklist()
|Allow receiving the message from blacklisted ids
reply(text)
|Reply to this message. This can be used to quote to the message when sending media messages, for example with image()
modifier (the text then becomes optional)
replyRandom(text)
|Same as above, but picked randomly from arguments. Can be arrays too.
react(emoji)
|React to this message|react("😁")
forward()
|Forward this message. Use to()
modifier to specify target id(s)
delete()
|Delete this message
read()
|Read this message (send blue ticks mark)
ignoreCase()
| Tell this program to ignore the case
stripMentions()
|Remove mentions from text
hideCommand()
|Hide this command from menu maker
ScheduledProgram
's modifiers
Created with bot.schedule()
. This will trigger the response based on provided interval.
Modifier|Description|Example -|-|- No special modifiers (probably will be added later)
Templating Notation
| Notation | Description | Example |
| ---------------- | ---------------------------------------------------------------------- | --------------------------------- |
| "<<number>>"
| Insert a captured match when input is a RegExp. Starting from number 1 | "<<1>>"
|
| "%%var_name%%"
| Insert the value of a variable that has been set using bot.setVar()
| "Hello my name is %%bot_name%%"
|
Command Menu Template
You can use bot.createCommandMenu()
to generate menu string for your command list. You can edit the template in the bot-config.json
file. See the default template
You can pass in extraCommands
as the argument. It is an array of commands ({name, description, category}
) that you want to show in the result.
Mentioning
If the message text contains the pattern @phonenumber
(ex:@62821234567
) it will be automatically converted to a mention.
Baileys' Objects
In case you want to do your own functionality
bot.getSocket()
: The sock/socket/client object that is typically used in baileysmessage.getBaileysMessage()
: See above in the section aboutmessage
object