@aidulcandra/simple-wa-bot v19.2.4
simple-wa-bot
By aidulcandra
This module wraps baileys
What's New in 19.x
Program Modifiers
mentionedOnly()
program modifierquotedOnly()
program modifierif()
modifier now passesmessage
as the argument
Bot Functionality
bot.sendContacts()
bot.command()
'sdescription
andcategory
arguments- Load settings from
bot-config.json
- Command Menu Maker
bot.createCommandMenu()
Message Functionality
message.forward()
message.react()
message.delete()
message.getBaileysMessage()
replacesmessage.baileysMessage
message.replyImage()
message.replyVideo()
message.replyAudio()
message.replySticker()
message.replyContacts()
- Auto mention when detecting
@<number>
in texts when sending messages
Other
- Fix bugs
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.
{
// 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,
// 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("ABCDE@g.us").reply("hi");
// Only respond to specific id(s)
bot.receive("hello").from("6282123456789@s.whatsapp.net").reply("hi");
bot.receive("hello").from("xxx@s.wa.net", "yyy@s.wa.net").reply("hi");
bot
.receive("hello")
.from(["6282123456789@s.whatsapp.net", "6282987654321@s.whatsapp.net"])
.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 object | |
message.text | The text or caption of the message | |
message.room | Chat ID where this message was sent to | "628123456789@s.whatsapp.net" |
message.sender | An object of the sender's info | |
message.sender.name | Sender's name | |
message.sender.id | Sender's ID | "628123456789@s.whatsapp.net" |
message.senderi.isMe | Whether the sender is the bot itself. | |
message.sender.isBlacklisted | Whether the sender is blacklisted | |
message.type | Type of the message | "text" , "image" , "video" , etc. |
message.image | Image object of the message | |
message.image.getBuffer() | Get the buffer object of the image | |
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(url, caption) | Reply with image | |
message.replyVideo(url, caption) | Reply with video | |
message.replyAudio(url, 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.replyContacts(contacts) | Reply with contact(s). contacts is an array of object {name, number} | |
message.edit(text) | Edit this message | |
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 |
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({year, month, date, day, hour, minute, second}) | Trigger this program time-based. Unspecified value will be treated as 'any'. Constraints: month: 0-11, date: 1-31, day: 0-6, hour: 0-23, minute: 0-59, second: 0-59 | bot.schedule({day:0, hour:5, minute:0, second:0}) Trigger this program every Sunday (0) at 5:00:00 AM. |
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("628212345678@s.whatsapp.net", "Hello world") |
bot.sendImage(targetId, link, caption) | Send an image from given link to the chat id | bot.sendImage("628212345678@s.whatsapp.net", "https://picsum.photos/300") |
bot.sendVideo(targetId, link, caption) | Send a video | |
bot.sendAudio(targetId, link, 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.sendContacts(to, contacts) | Send one or more contacts. Contacts argument is an array of {name, number} . The number can include symbols (ex:"+628123456789" ) | |
bot.updateStatus(newStatus) | Change your status text | |
bot.checkAdmin(id, groupId) | Check whether id is an admin of a group | |
bot.getId() | Get the id of the bot | |
bot.waitForMessage(roomId) | Wait for a message to appear in a room then return the message object | |
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 |
Methods Of Program
Object (Program Modifiers)
Method | Description | Example |
---|---|---|
reply(text) | Set the text/caption that will be send as a response | |
replyRandom(text) | Same as above, but picked randomly from arguments. Can be arrays too. | |
text(text) | Set the response text, but this will not quote/reply to the message | |
textRandom(text) | ||
similarity(value) | Set the similarity threshold (0-1). Bot will respond if the input text is similar enough to the expected text | |
ignoreCase() | Tell this program to ignore the case | |
privateOnly() | Only respond to private chats | |
groupOnly() | Only respond to group chats | |
adminOnly() | Only respond to admins (must be in a group chat) | |
mentionedOnly() | Only respond 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() | Only respond to messages quoting to bot's message | |
in(ids) | Only respond 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) | |
withImage() | Only respond to image messages | |
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) |
includeBlacklist() | Allow receiving the message from blacklisted ids | |
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'}) |
react(emoji) | Give a reaction emoji as a response | react("😁") |
showTyping() | Show the is typing ... text before sending response | |
showRecording() | Show the is recording ... text before sending response | |
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 |
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.
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
27 days ago
27 days ago
27 days ago
27 days ago
27 days ago
27 days ago
27 days ago
27 days ago
27 days ago
27 days ago
27 days ago
27 days ago
27 days ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
1 month ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
4 months ago
4 months ago
4 months ago
4 months ago