fhy-wabot is a Node.js package designed to simplify the use of WhatsApp Bots.
To install the fhy-wabot
package, run the following command in the terminal:
npm install fhy-wabot
After installing the package, you can use it in your Node.js project as follows (server.js):
First, import WaBot
from fhy-wabot
:
const { WaBot } = require('fhy-wabot');
Next, call the WaBot()
function to initialize and run the bot
Initialization has fixed rules:
WaBot(QRUrl = false, QRCustom, AutoResponse, ManualResponse, self = false);`
QRUrl
: to set the use of QR Url (set:true
orfalse
)QRCustom
: to create a custom QR url function (if you don't want to use it set to:null
)AutoResponse
: to Initialize the function ofAutoResponse
(if you don't want to use it set to:null
ManualResponse
: to Initialize the function ofManualResponse
(if you don't want to use it set to:null
self
: to set the use of self mode (set:true
orfalse
)
Basic usage example that just uses the defaults:
WaBot(QRUrl = false, null, null, null, self = false);
You can use another method
WaBot(false, null, null, null, false);
or
WaBot(true, null, null, null, true);
Here’s a complete example of how to use fhy-wabot
:
const { WaBot } = require('fhy-wabot');
// Default Initialize and run the bot
WaBot(false, null, null, null, false);
You can make the QRcode a data URL with the following command:
const { WaBot } = require('fhy-wabot');
const QRCode = require('qrcode');
const QRCustom = async (qr) => {
try {
const url = await QRCode.toDataURL(qr);
console.log('Custom QRCode URL:', url);
} catch (err) {
console.error('Failed to generate QR URL:', err);
}
};
WaBot(true, QRCustom, null, null, false);
WaBot(false, null, null, null, true);
AutoResponse
is an object used to configure automatic responses that will be given by the bot based on the received input. (supports multi-message).
const { WaBot } = require('fhy-wabot');
const AutoResponse = {
'text': {
'!text': {
response: 'pong!',
reply: false
}
// You can add other data here
},
// You can add other data types here
};
WaBot(false, null, AutoResponse, null, false);
- response: The message that will be sent (e.g., 'pong!').
- reply: If set to
true
, the bot will reply to the message with a quote.
'text': {
'!text': {
response: 'I sent text!',
reply: false
}
},
'textReact': {
'!text-react': {
response: 'I sent text with reaction!',
preReact: '⏳',
postReact: 'âś…',
errReact: '❌',
reply: false
}
},
- preReact: Emoji displayed before sending the message (e.g., '⏳').
- postReact: Emoji displayed after the message is sent (e.g., 'âś…').
- errReact: Emoji displayed if an error occurs (e.g., '❌').
'mention': {
'!mention': {
response: '@628xxxxxxxx',
mention: '[email protected]',
reply: false
}
},
- mention: The ID number of the user to mention.
'mention': {
'!mention-react': {
response: '@628xxxxxxxx',
mention: '[email protected]',
preReact: '⏳',
postReact: 'âś…',
errReact: '❌',
reply: false
}
},
'location': {
'!location': {
latitude: 24.121231,
longitude: 55.1121221,
reply: false
}
},
- latitude: The latitude of the location to be shared.
- longitude: The longitude of the location to be shared.
'locationReact': {
'!location-react': {
latitude: '24.121231',
longitude: '55.1121221',
preReact: '⏳',
postReact: 'âś…',
errReact: '❌',
reply: false
}
},
'images': {
'!image': {
url: './uploads/default.jpg',
caption: 'I sent caption image!',
reply: false
}
},
- url: Image location
- caption: Image caption
'imagesReact': {
'!image-react': {
url: './uploads/default.jpg',
caption: 'I sent caption image with reaction!',
preReact: '⏳',
postReact: 'âś…',
errReact: '❌',
reply: false
}
},
'video': {
'!video': {
url: './uploads/default.mp4',
caption: 'I sent caption video!',
reply: false
},
},
'videoReact': {
'!video-react': {
url: './uploads/default.mp4',
caption: 'I sent caption video with reaction!',
preReact: '⏳',
postReact: 'âś…',
errReact: '❌',
reply: false
},
},
'audio': {
'!audio': {
url: './uploads/default.mp3',
caption: 'I sent caption audio!',
reply: false
},
},
'audioReact': {
'!audio-react': {
url: './uploads/default.mp3',
caption: 'I sent caption audio with caption!',
preReact: '⏳',
postReact: 'âś…',
errReact: '❌',
reply: true
},
},
'polling': {
'!poll': {
poll: {
name: 'Title Polling:',
values: ['Option 1', 'Option 2', 'Option 3'],
selectableCount: 1
},
reply: false
}
},
- name: Poll Title
- values: Fill in the poll options
- selectableCount:
1
for just one option,0
for multiple options
'pollingReact': {
'!poll-react': {
poll: {
name: 'Title Polling:',
values: ['Option 1', 'Option 2', 'Option 3'],
selectableCount: 1
},
preReact: '⏳',
postReact: 'âś…',
errReact: '❌',
reply: false
}
}
'vcard': {
'!vcard': {
contacts: {
fullName: 'Your Name',
organization: 'Organization Name',
phoneId: '+62 8xx xxxx xxxx',
whatsappId: '628xxxxxxxxxx'
},
reply: false
}
},
- fullName: Contact Name
- organization: Organization Name
- phoneId: Phone number
- whatsappId: Whatsapp number
'vcardReact': {
'!vcard-react': {
contacts: {
fullName: 'Your Name',
organization: 'Organization Name',
phoneId: '+62 8xx xxxx xxxx',
whatsappId: '628xxxxxxxxxx'
},
preReact: '⏳',
postReact: 'âś…',
errReact: '❌',
reply: false
}
},
ManualResponse
is an object used to configure various types of messages you want to send (supports multi-message).
const { WaBot } = require('fhy-wabot');
const ManualResponse = {
text: [
{
id: '[email protected]',
messageText: 'I sent text!'
}
],
};
WaBot(false, null, null, ManualResponse, false);
text: [
{
id: '[email protected]',
messageText: 'I sent text!'
}
],
- id: Message recipient number
- messageText: Message content
images: [
{
id: '[email protected]',
url: './uploads/default.jpg',
caption: 'I sent image!'
}
],
- url: Image location
- caption: Image caption
video: [
{
id: '[email protected]',
url: './uploads/default.mp4',
caption: 'I sent video!'
}
],
audio: [
{
id: '[email protected]',
url: './uploads/default.mp3',
caption: 'I sent audio!'
}
],
mention: [
{
id: '[email protected]',
messageText: '@6281xxxxxxxxx',
mention: '[email protected]'
}
],
- mention: ID number to mention
location: [
{
id: '[email protected]',
latitude: 24.121231,
longitude: 55.1121221
}
],
- latitude: The latitude of the location to be shared.
- longitude: The longitude of the location to be shared.
polling: [
{
id: '[email protected]',
name: 'Title Polling:',
values: ['Option 1', 'Option 2', 'Option 3'],
selectableCount: 1
}
],
- name: Poll Title
- values: Fill in the poll options
- selectableCount:
1
for just one option,0
for multiple options
vcard: [
{
id: '[email protected]',
fullName: 'Your Name',
organization: 'Organization Name',
phoneId: '+62 8xx xxxx xxxx',
whatsappId: '628xxxxxxxxxx'
}
],
- fullName: Contact Name
- organization: Organization Name
- phoneId: Phone number
- whatsappId: Whatsapp number
const { WaBot } = require('fhy-wabot');
const QRCode = require('qrcode');
const QRCustom = async (qr) => {
try {
const url = await QRCode.toDataURL(qr);
console.log('Custom QRCode URL:', url);
} catch (err) {
console.error('Failed to generate QR URL:', err);
}
};
const AutoResponse = {
'text': {
'!text': {
response: 'pong!',
reply: false
}
// You can add other data here
},
// You can add other data types here
};
const ManualResponse = {
text: [
{
id: '[email protected]',
messageText: 'I sent text!'
}
// You can add other data here
],
// You can add other data types here
};
WaBot(true, QRCustom, AutoResponse, ManualResponse, false);
const { WaBot } = require('fhy-wabot');
const AutoResponse = {};
const ManualResponse = {};
(async () => {
const sock = await WaBot(false, null, AutoResponse, ManualResponse, false);
sock.ev.on('messages.upsert', async (messageUpdate) => {
const message = messageUpdate.messages[0];
const sender = message.key.remoteJid;
const text = message.message.conversation || message.message.extendedTextMessage?.text || '';
if (text.toLowerCase() === '!hi') {
try {
await sock.sendMessage(sender, { text: 'oh hello there' });
} catch (error) {
console.error(`Error occurred: ${error.message}`);
}
}
});
})();
To download media you need downloadMediaMessage
, fs
, and path
const { WaBot, downloadMediaMessage } = require('fhy-wabot');
const fs = require('fs');
const path = require('path');
Usage example for downloading media when quoting a media message with the .download
command:
if (text.toLowerCase() === '.download') {
const quotedMessage = message.message.extendedTextMessage?.contextInfo?.quotedMessage;
if (quotedMessage?.imageMessage) {
try {
const buffer = await downloadMediaMessage({ message: quotedMessage }, 'buffer');
const inputFilePath = path.join(__dirname, './download.jpg');
fs.writeFileSync(inputFilePath, buffer);
console.log(`Image downloaded: ${inputFilePath}`);
} catch (error) {
console.error(`Error occurred: ${error.message}`);
}
} else {
console.log("Quoted message is not an image.");
}
}
const { WaBot } = require('fhy-wabot');
const QRCode = require('qrcode');
const QRCustom = async (qr) => {
try {
const url = await QRCode.toDataURL(qr);
console.log('Custom QRCode URL:', url);
} catch (err) {
console.error('Failed to generate QR URL:', err);
}
};
const AutoResponse = {
'text': {
'!text': {
response: 'pong!',
reply: false
}
// You can add other data here
},
// You can add other data types here
};
const ManualResponse = {
text: [
{
id: '[email protected]',
messageText: 'I sent text!'
}
// You can add other data here
],
// You can add other data types here
};
(async () => {
const sock = await WaBot(true, QRCustom, AutoResponse, ManualResponse, false);
sock.ev.on('messages.upsert', async (messageUpdate) => {
const message = messageUpdate.messages[0];
const sender = message.key.remoteJid;
const text = message.message.conversation || message.message.extendedTextMessage?.text || '';
if (text.toLowerCase() === '.test') {
try {
await sock.sendMessage(sender, { text: 'oh hello there' });
} catch (error) {
console.error(`Error occurred: ${error.message}`);
}
}
// You can add other advanced data here
});
})();
const express = require('express');
const { WaBot } = require('fhy-wabot');
const app = express();
const PORT = process.env.PORT || 3000;
app.use(express.json());
app.post('/send-message', async (req, res) => {
const { id, messageText } = req.body;
if (!id || !messageText) {
return res.status(400).json({ error: 'ID and messageText are required.' });
}
const ManualResponse = {
text: [{ id: `${id}@s.whatsapp.net`, messageText }]
};
try {
await WaBot(false, null, null, ManualResponse, false);
res.json({ message: 'Message sent successfully.', recipient: `${id}@s.whatsapp.net` });
} catch (error) {
console.error('Failed to send message:', error);
res.status(500).json({ error: 'Failed to send message.' });
}
});
- npm install express
- Endpoint:
http://localhost:3000/send-message
- Body Request:
{ "id": "628xxxxxxxxxx", "messageText": "Hello from Endpoint!" }
If you encounter any issues or have questions regarding the use of this package, please open an issue in your GitHub repository. Contributions are also very welcome to improve the features and functionality of fhy-wabot
.