92
loading...
This website collects cookies to deliver better user experience
whatsapp-web.js
to ease authentication and messaging controls. It provides a simple WhatsApp Web client built using Node & Puppeteer.$ npm init
whatsapp-web.js
for WhatsApp client and qrcode-terminal
to parse the auth information into visible QR code.$ npm i whatsapp-web.js qrcode-terminal
index.js
and add the following code.const qrcode = require('qrcode-terminal')
const { Client } = require('whatsapp-web.js')
// open whatsapp web in a headless browser (no gui)
const puppeteerOptions = {
headless: true,
args: ['--no-sandbox'],
}
// initialize client object
const client = new Client({
puppeteer: puppeteerOptions,
})
// prints QR code to console when received
client.on('qr', (qr) => {
qrcode.generate(qr, { small: true })
})
client.on('ready', () => {
console.log('Client is ready!')
})
// listen for new messages
client.on('message_create', (message) => {
const messageBody = message.body
console.log(messageBody)
if (messageBody == '!ping') {
message.reply('pong')
}
})
client.initialize()
puppeteerOptions
to client
to disable a GUI. message_create
event. The client listens for any new messages. Right now, we will listen to only !ping
and respond with pong
.package.json
."scripts": {
"start": "node index.js"
},
$ npm start
.env
and paste the APPID
.APPID=<App ID from Wolfram|Alpha API here>
dotenv
:npm i dotenv
index.js
:require('dotenv').config()
...
const { Client } = require('whatsapp-web.js')
const appid = process.env.APPID
const WolframAlphaAPI = require('./WolframAlphaAPI.js')
let wraAPI = WolframAlphaAPI(appid)
const invokeKey = '!b'
const puppeteerOptions = {
...
appid
from process and then initializing WolframAlphaAPI instance wraAPI
which will later handle all functions.npm start
to make sure no errors are present. You should still see a QR code and after authenticating any new messages should be logged.index.js
to handle message.client.on('message_create', (message) => {
const messageBody = message.body
if (messageBody.startsWith(invokeKey)) {
messageHandler(message)
}
})
// receive all bot commands and reply accordingly
const messageHandler = (message) => {
// get message body and trim invokeKey
let query = message.body.substring(invokeKey.length + 1)
console.log(`Querying result for ${query}`)
handleImage(message, query, wraAPI)
}
npm start
again, wait a sec! We also need to define the logic for handling image responses in handleImage
.npm i parse-data-url
index.js
const parseDataUrl = require('parse-data-url')
const { MessageMedia } = require('whatsapp-web.js')
const handleImage = (message, text, wraAPI) => {
try {
console.log('Image request')
// send the rest of the message to Wolfram|Alpha API
wraAPI
.getSimple({
i: text,
timeout: 5,
})
.then((res) => {
const parsed = parseDataUrl(res)
message.reply(new MessageMedia(parsed.contentType, parsed.data))
})
.catch((err) => {
message.reply(String(err))
})
} catch (err) {
console.log(err)
}
}
92