I've always wanted to build or have my own WHATSAPP BOT, to reply my messages as I've never being one to read and reply chats and also send scheduled and automated messages sure as birthday wishes (is kind of a big deal over here)
I hate Chatting
So i start by building a uni-gram Pattern Bot in node and fed it some data, it was super dumb at first but the more data i fed it, the more manageable it was getting
Now What was left was to integrate it with Whatsapp
So I jumped to Twilio WhatsApp Business API ππ and the cost was fair $0.0042 to send a WhatsApp Template message and $0.005 for WhatsApp Session messages; BUT sadly that much ππ for me as a student in a third world country with high exchange rate, I couldn't waste that amount for the Restriction Twilio was giving and I wanted it to come from a regular account(i figured much later).
So I hopped to google and searched for 'Free Whatsapp bot', cause I wasn't gonna build one from scratch; Like I have the skills for that or the time to maintain itπ π π π.
All I could find were third-party Service Provider and not what i anticipated, then something hit me and i went to GitHub to find an open source freeware
And I Met VENOM
VENOM
love at first sight
The documentation was straight forward and it got the right amount of stars and maintainers
so I $~
and started coding.
npm install venom-bot
when i started with the demo script from their readme file, I noticed the Application was reading all my incoming messages, down to my friends status caption with a Base64-encoded string to represent the image/gif
So I first made a condition to ignore messages coming from the groups am in and I then imported my bot as a module and passed it the messages coming from my friends as a parameter and replied with the return values from my bot
I did all this in less than 10 min for the first time
I got about a few messages and the bot auto responded for me, I let this process go on for about 15 min unsupervised and 4 out of my friends that interacted with it, only 3 figured it was an auto response system.
I just figured out a new toy
I manage a site that sale and answer assignment for university and since i got access to the server I created an endpoint for it and added cors();
I called my route using a package called node-fetch and got my json data.
So I Sorted Or Used The User Phone Number To Query The Database
My Controller File
const siteName = "https://sitename.com/{secretkey}/"
const fetch = require('node-fetch');
/**
*
* @param {number} phone
* @param {*} id
*/
// get balance
exports.bal = async (phone) =>{
const dataStream = await fetch(siteName + 'bal/'+ phone);
const dataJson = await dataStream.json();
return await dataJson;
}
My Index File
const venom = require('venom-bot');
const controller = require('./function/fetch');
// Starting Venom
venom.create()
.then((client) => start(client))
.catch((erro) =>{
console.error(erro);
});
// To Read All incoming Messages
const start = async (client)=>{
client.onMessage((message) =>{
// converting all the user message to lowercase for easy computing
const data = message.body.toLowerCase();
const caller = data.split(' ');
// This is to reformat the users number Base on your location
const phone = message.from
var formatednumber = phone.split("@");
// removing the 234 and adding 0 to the end
var count = "0" + formatednumber[0].slice(3)
// if startment to check messages string and ignore group messages
if(message.isGroupMsg === false && caller[0] == 'KeyWord'){
switch (caller[1]) {
// send a help meassage listing params
case 'help' :
// to send a message
client.sendText(message.from, controller.help())
.catch((erro) => {
console.error('Error when sending: ', erro);
//return object error
});
break;
// to get user balance in the application
case 'balance' :
const cyril1 = controller.bal(count).then(res =>
{
const reply = `Your Account Balance Is *NGN ${res.wallet}* `
client.sendText(message.from, reply).catch(erro=>{
console.log(erro);
})
}).catch(error =>{
console.log(error)
})
break;
default:
controller.invalidRes
client.sendText(message.from, controller.invalidRes())
.catch((erro) => {
console.error('Error when sending: ', erro); //return object error
});
client.sendText(message.from, controller.help())
.catch((erro) => {
console.error('Error when sending: ', erro); //return object error
});
break;
}
}
}).catch
}
this gave me the ability to handle almost all the macro tasks in my site on Whatsapp
The Code Running On My Terminal
The chat between a user and a bot
I enjoyed my building process and also didn't roll out that feature π
Why ?
The venom library runs in a headless version on chrome using
web.whatsapp.com API
So you must have an activate Whatsapp running on your Mobile Device and that's stressful
and running the process consume much CPU memory
So I could deploy my Whatsapp bot the server but the downside my phone must be online too if I need the bot to work
If you want the full code I could make them available on my Git Repo.
I hope You Enjoyed this
It's my first article
And might not be entirely correct I'm totally open to corrections
Thanks
Top comments (2)
Good.. this is far better from others out there - in terms of using the business api and having a different identitiy. Would like to try this out...
Am happy you found this interesting,would love to see your implementation when your done.
Good luck.