By aidulcandra. Email me at aidulcandra@gmail.com
.
This module wraps baileys
-
message.reactedId
for reaction messages -
message.protocolData
settings modified by protocol messages -
message.protocolData.chatDisappearingTime
number in miliseconds that represents this chat's message disappearing time than has been set by this protocol message -
message.disappearingTime
this message's disappearing time
-
run(script_path, function_name)
- 2nd parameter is the name of the function that you want to run if the module exports an object with multiple functions
- Fix bugs
- Code refactor
- Readme cleanup
npm install @aidulcandra/simple-wa-bot
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.
{
"ownerIds": [],
"parseMentions": true,
"recordPushnames": true,
"autoRead": false,
"commandPrefixes": ["/"],
"commandMenu": {
"menuTemplate": "> COMMAND LIST\n\n@categorylist\n\n_Created by: @aidulcandra_",
"categoryTemplate": "[@category]----\n@commandlist\n------------",
"categorySeparator": "\n\n",
"commandTemplate": "`/@command` - @description",
"commandSeparator": "\n"
}
}
Description:
-
ownerIds
: Array of owner/co-owners ids -
parseMentions
: Whether to parse mentions into their usernames -
recordPushnames
: Whether to keep track of user pushnames and the changes. Will allow you to get a user's last pushnames outside the event of receiving their message. -
autoRead
: Auto read received messages (send double blue-tick mark) -
commandPrefixes
: Array of prefixes that can be used to invoke commands -
commandMenu
: Command menu template-
menuTemplate
: @categorylist will be replaced by category list -
categoryTemplate
: @category will be replaced by category name, @commandlist will be replaced by the list of the commands -
categorySeparator
: Separator for each category list -
commandTemplate
: @command will be replaced by command name, @description will be replaced by the description of the command -
commandSeparator
: Separator for each command item
-
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.");
//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();
// 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")
}
// If the module exports an object with multiple functions, you can use the 2nd parameter to identify the function name
bot.receive("calculate").run("commands/my-module.js", "calculate")
Name | Description | Example |
---|---|---|
message.id |
ID of the message object | |
message.text |
The text or caption of the message | |
message.quoted |
Another message object, which is what this message is replying to | |
message.reactedId |
The ID of the reacted message this message is reacting to, if this is a reaction message. | |
message.isEdit |
Whether the message is an edit | |
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.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.protocolData? |
If message type is 'protocol' , this property will be available. This contains settings modified by a protocol message |
|
message.protocolData?.chatDisapperingTime? |
This chat's disappearing time in miliseconds. | |
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 |
Name | Description | Example |
---|---|---|
group.id |
Id of the group | "1234@g.us" |
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 |
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.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, 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("628212345678@s.whatsapp.net", "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 hq to true to 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 : timeout in 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 |
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. |
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
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 |
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 |
Created with bot.schedule()
. This will trigger the response based on provided interval.
Modifier | Description | Example |
---|---|---|
No special modifiers (probably will be added later) |
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%%" |
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.
If the message text contains the pattern @phonenumber
(ex:@62821234567
) it will be automatically converted to a mention.
In case you want to do your own functionality
-
bot.getSocket()
: The sock/socket/client object that is typically used in baileys -
message.getBaileysMessage()
: See above in the section aboutmessage
object