mirror of
https://github.com/cheveguerra/whatsapp-api-tutorial.git
synced 2026-04-17 19:36:59 +00:00
Add send message to group
This commit is contained in:
281
app.js
281
app.js
@@ -14,165 +14,226 @@ const server = http.createServer(app);
|
|||||||
const io = socketIO(server);
|
const io = socketIO(server);
|
||||||
|
|
||||||
app.use(express.json());
|
app.use(express.json());
|
||||||
app.use(express.urlencoded({ extended: true }));
|
app.use(express.urlencoded({
|
||||||
|
extended: true
|
||||||
|
}));
|
||||||
app.use(fileUpload({
|
app.use(fileUpload({
|
||||||
debug: true
|
debug: true
|
||||||
}));
|
}));
|
||||||
|
|
||||||
const SESSION_FILE_PATH = './whatsapp-session.json';
|
const SESSION_FILE_PATH = './whatsapp-session.json';
|
||||||
let sessionCfg;
|
let sessionCfg;
|
||||||
if (fs.existsSync(SESSION_FILE_PATH)) {
|
if (fs.existsSync(SESSION_FILE_PATH)) {
|
||||||
sessionCfg = require(SESSION_FILE_PATH);
|
sessionCfg = require(SESSION_FILE_PATH);
|
||||||
}
|
}
|
||||||
|
|
||||||
app.get('/', (req, res) => {
|
app.get('/', (req, res) => {
|
||||||
res.sendFile('index.html', { root: __dirname });
|
res.sendFile('index.html', {
|
||||||
|
root: __dirname
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
const client = new Client({
|
const client = new Client({
|
||||||
puppeteer: {
|
puppeteer: {
|
||||||
headless: true,
|
headless: true,
|
||||||
args: [
|
args: [
|
||||||
'--no-sandbox',
|
'--no-sandbox',
|
||||||
'--disable-setuid-sandbox',
|
'--disable-setuid-sandbox',
|
||||||
'--disable-dev-shm-usage',
|
'--disable-dev-shm-usage',
|
||||||
'--disable-accelerated-2d-canvas',
|
'--disable-accelerated-2d-canvas',
|
||||||
'--no-first-run',
|
'--no-first-run',
|
||||||
'--no-zygote',
|
'--no-zygote',
|
||||||
'--single-process', // <- this one doesn't works in Windows
|
'--single-process', // <- this one doesn't works in Windows
|
||||||
'--disable-gpu'
|
'--disable-gpu'
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
session: sessionCfg
|
session: sessionCfg
|
||||||
});
|
});
|
||||||
|
|
||||||
client.on('message', msg => {
|
client.on('message', msg => {
|
||||||
if (msg.body == '!ping') {
|
if (msg.body == '!ping') {
|
||||||
msg.reply('pong');
|
msg.reply('pong');
|
||||||
} else if (msg.body == 'good morning') {
|
} else if (msg.body == 'good morning') {
|
||||||
msg.reply('selamat pagi');
|
msg.reply('selamat pagi');
|
||||||
}
|
} else if (msg.body == '!groups') {
|
||||||
|
client.getChats().then(chats => {
|
||||||
|
const groups = chats.filter(chat => chat.isGroup);
|
||||||
|
|
||||||
|
if (groups.length == 0) {
|
||||||
|
msg.reply('You have no group yet.');
|
||||||
|
} else {
|
||||||
|
let replyMsg = '*YOUR GROUPS*\n\n';
|
||||||
|
groups.forEach((group, i) => {
|
||||||
|
replyMsg += `ID: ${group.id._serialized}\nName: ${group.name}\n\n`;
|
||||||
|
});
|
||||||
|
replyMsg += '_You can use the group id to send a message to the group._'
|
||||||
|
msg.reply(replyMsg);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
client.initialize();
|
client.initialize();
|
||||||
|
|
||||||
// Socket IO
|
// Socket IO
|
||||||
io.on('connection', function(socket) {
|
io.on('connection', function(socket) {
|
||||||
socket.emit('message', 'Connecting...');
|
socket.emit('message', 'Connecting...');
|
||||||
|
|
||||||
client.on('qr', (qr) => {
|
client.on('qr', (qr) => {
|
||||||
console.log('QR RECEIVED', qr);
|
console.log('QR RECEIVED', qr);
|
||||||
qrcode.toDataURL(qr, (err, url) => {
|
qrcode.toDataURL(qr, (err, url) => {
|
||||||
socket.emit('qr', url);
|
socket.emit('qr', url);
|
||||||
socket.emit('message', 'QR Code received, scan please!');
|
socket.emit('message', 'QR Code received, scan please!');
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
});
|
||||||
|
|
||||||
client.on('ready', () => {
|
client.on('ready', () => {
|
||||||
socket.emit('ready', 'Whatsapp is ready!');
|
socket.emit('ready', 'Whatsapp is ready!');
|
||||||
socket.emit('message', 'Whatsapp is ready!');
|
socket.emit('message', 'Whatsapp is ready!');
|
||||||
});
|
});
|
||||||
|
|
||||||
client.on('authenticated', (session) => {
|
client.on('authenticated', (session) => {
|
||||||
socket.emit('authenticated', 'Whatsapp is authenticated!');
|
socket.emit('authenticated', 'Whatsapp is authenticated!');
|
||||||
socket.emit('message', 'Whatsapp is authenticated!');
|
socket.emit('message', 'Whatsapp is authenticated!');
|
||||||
console.log('AUTHENTICATED', session);
|
console.log('AUTHENTICATED', session);
|
||||||
sessionCfg=session;
|
sessionCfg = session;
|
||||||
fs.writeFile(SESSION_FILE_PATH, JSON.stringify(session), function (err) {
|
fs.writeFile(SESSION_FILE_PATH, JSON.stringify(session), function(err) {
|
||||||
if (err) {
|
if (err) {
|
||||||
console.error(err);
|
console.error(err);
|
||||||
}
|
}
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
});
|
||||||
|
|
||||||
client.on('auth_failure', function(session) {
|
client.on('auth_failure', function(session) {
|
||||||
socket.emit('message', 'Auth failure, restarting...');
|
socket.emit('message', 'Auth failure, restarting...');
|
||||||
});
|
});
|
||||||
|
|
||||||
client.on('disconnected', (reason) => {
|
client.on('disconnected', (reason) => {
|
||||||
socket.emit('message', 'Whatsapp is disconnected!');
|
socket.emit('message', 'Whatsapp is disconnected!');
|
||||||
client.destroy();
|
client.destroy();
|
||||||
client.initialize();
|
client.initialize();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
const checkRegisteredNumber = async function(number) {
|
const checkRegisteredNumber = async function(number) {
|
||||||
const isRegistered = await client.isRegisteredUser(number);
|
const isRegistered = await client.isRegisteredUser(number);
|
||||||
return isRegistered;
|
return isRegistered;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Send message
|
// Send message
|
||||||
app.post('/send-message', [
|
app.post('/send-message', [
|
||||||
body('number').notEmpty(),
|
body('number').notEmpty(),
|
||||||
body('message').notEmpty(),
|
body('message').notEmpty(),
|
||||||
], async (req, res) => {
|
], async (req, res) => {
|
||||||
const errors = validationResult(req).formatWith(({ msg }) => {
|
const errors = validationResult(req).formatWith(({
|
||||||
return msg;
|
msg
|
||||||
|
}) => {
|
||||||
|
return msg;
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!errors.isEmpty()) {
|
||||||
|
return res.status(422).json({
|
||||||
|
status: false,
|
||||||
|
message: errors.mapped()
|
||||||
});
|
});
|
||||||
|
}
|
||||||
|
|
||||||
if (!errors.isEmpty()) {
|
const number = phoneNumberFormatter(req.body.number);
|
||||||
return res.status(422).json({
|
const message = req.body.message;
|
||||||
status: false,
|
|
||||||
message: errors.mapped()
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
const number = phoneNumberFormatter(req.body.number);
|
const isRegisteredNumber = await checkRegisteredNumber(number);
|
||||||
const message = req.body.message;
|
|
||||||
|
|
||||||
const isRegisteredNumber = await checkRegisteredNumber(number);
|
if (!isRegisteredNumber) {
|
||||||
|
return res.status(422).json({
|
||||||
if (!isRegisteredNumber) {
|
status: false,
|
||||||
return res.status(422).json({
|
message: 'The number is not registered'
|
||||||
status: false,
|
|
||||||
message: 'The number is not registered'
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
client.sendMessage(number, message).then(response => {
|
|
||||||
res.status(200).json({
|
|
||||||
status: true,
|
|
||||||
response: response
|
|
||||||
});
|
|
||||||
}).catch(err => {
|
|
||||||
res.status(500).json({
|
|
||||||
status: false,
|
|
||||||
response: err
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
client.sendMessage(number, message).then(response => {
|
||||||
|
res.status(200).json({
|
||||||
|
status: true,
|
||||||
|
response: response
|
||||||
|
});
|
||||||
|
}).catch(err => {
|
||||||
|
res.status(500).json({
|
||||||
|
status: false,
|
||||||
|
response: err
|
||||||
|
});
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
// Send media
|
// Send media
|
||||||
app.post('/send-media', async (req, res) => {
|
app.post('/send-media', async (req, res) => {
|
||||||
const number = phoneNumberFormatter(req.body.number);
|
const number = phoneNumberFormatter(req.body.number);
|
||||||
const caption = req.body.caption;
|
const caption = req.body.caption;
|
||||||
const fileUrl = req.body.file;
|
const fileUrl = req.body.file;
|
||||||
|
|
||||||
// const media = MessageMedia.fromFilePath('./image-example.png');
|
|
||||||
// const file = req.files.file;
|
|
||||||
// const media = new MessageMedia(file.mimetype, file.data.toString('base64'), file.name);
|
|
||||||
let mimetype;
|
|
||||||
const attachment = await axios.get(fileUrl, { responseType: 'arraybuffer' }).then(response => {
|
|
||||||
mimetype = response.headers['content-type'];
|
|
||||||
return response.data.toString('base64');
|
|
||||||
});
|
|
||||||
|
|
||||||
const media = new MessageMedia(mimetype, attachment, 'Media');
|
// const media = MessageMedia.fromFilePath('./image-example.png');
|
||||||
|
// const file = req.files.file;
|
||||||
|
// const media = new MessageMedia(file.mimetype, file.data.toString('base64'), file.name);
|
||||||
|
let mimetype;
|
||||||
|
const attachment = await axios.get(fileUrl, {
|
||||||
|
responseType: 'arraybuffer'
|
||||||
|
}).then(response => {
|
||||||
|
mimetype = response.headers['content-type'];
|
||||||
|
return response.data.toString('base64');
|
||||||
|
});
|
||||||
|
|
||||||
client.sendMessage(number, media, { caption: caption }).then(response => {
|
const media = new MessageMedia(mimetype, attachment, 'Media');
|
||||||
res.status(200).json({
|
|
||||||
status: true,
|
client.sendMessage(number, media, {
|
||||||
response: response
|
caption: caption
|
||||||
});
|
}).then(response => {
|
||||||
}).catch(err => {
|
res.status(200).json({
|
||||||
res.status(500).json({
|
status: true,
|
||||||
status: false,
|
response: response
|
||||||
response: err
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
}).catch(err => {
|
||||||
|
res.status(500).json({
|
||||||
|
status: false,
|
||||||
|
response: err
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// Send message to group
|
||||||
|
// -- Send message !groups to get all groups (id & name)
|
||||||
|
// -- So you can use that group id to send a message
|
||||||
|
app.post('/send-group-message', [
|
||||||
|
body('id').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 chatId = req.body.id;
|
||||||
|
const message = req.body.message;
|
||||||
|
|
||||||
|
client.sendMessage(chatId, message).then(response => {
|
||||||
|
res.status(200).json({
|
||||||
|
status: true,
|
||||||
|
response: response
|
||||||
|
});
|
||||||
|
}).catch(err => {
|
||||||
|
res.status(500).json({
|
||||||
|
status: false,
|
||||||
|
response: err
|
||||||
|
});
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
server.listen(8000, function() {
|
server.listen(8000, function() {
|
||||||
console.log('App running on *: ' + 8000);
|
console.log('App running on *: ' + 8000);
|
||||||
});
|
});
|
||||||
|
|||||||
Reference in New Issue
Block a user