Add validation, formatter & some configs

This commit is contained in:
Nur Muhammad
2020-10-10 12:42:55 +08:00
parent 4e11203d01
commit 4c347048a7
4 changed files with 99 additions and 3 deletions

62
app.js
View File

@@ -1,9 +1,11 @@
const { Client } = require('whatsapp-web.js');
const express = require('express');
const { body, validationResult } = require('express-validator');
const socketIO = require('socket.io');
const qrcode = require('qrcode');
const http = require('http');
const fs = require('fs');
const { phoneNumberFormatter } = require('./helpers/formatter');
const app = express();
const server = http.createServer(app);
@@ -22,7 +24,22 @@ app.get('/', (req, res) => {
res.sendFile('index.html', { root: __dirname });
});
const client = new Client({ puppeteer: { headless: true }, session: sessionCfg });
const client = new Client({
puppeteer: {
headless: true,
args: [
'--no-sandbox',
'--disable-setuid-sandbox',
'--disable-dev-shm-usage',
'--disable-accelerated-2d-canvas',
'--no-first-run',
'--no-zygote',
'--single-process', // <- this one doesn't works in Windows
'--disable-gpu'
],
},
session: sessionCfg
});
client.on('message', msg => {
if (msg.body == '!ping') {
@@ -62,13 +79,52 @@ io.on('connection', function(socket) {
}
});
});
client.on('auth_failure', function(session) {
socket.emit('message', 'Auth failure, restarting...');
});
client.on('disconnected', (reason) => {
socket.emit('message', 'Whatsapp is disconnected!');
client.destroy();
client.initialize();
});
});
const checkRegisteredNumber = async function(number) {
const isRegistered = await client.isRegisteredUser(number);
return isRegistered;
}
// Send message
app.post('/send-message', (req, res) => {
const number = req.body.number;
app.post('/send-message', [
body('number').notEmpty(),
body('message').notEmpty(),
], async (req, res) => {
const errors = validationResult(req).formatWith(({ msg }) => {
return msg;
});
if (!errors.isEmpty()) {
return res.status(422).json({
status: false,
message: errors.mapped()
});
}
const number = phoneNumberFormatter(req.body.number);
const message = req.body.message;
const isRegisteredNumber = await checkRegisteredNumber(number);
if (!isRegisteredNumber) {
return res.status(422).json({
status: false,
message: 'The number is not registered'
});
}
client.sendMessage(number, message).then(response => {
res.status(200).json({
status: true,