From 9b46baa0ac635638a941fe4c7e9b4bed5417a9f3 Mon Sep 17 00:00:00 2001 From: Nur Muhammad Date: Fri, 22 Jan 2021 07:30:50 +0800 Subject: [PATCH] Allow to send message group by group name & some fix --- app.js | 34 ++++++++++++++++++++++++++++++---- index-multiple-device.html | 4 ++-- index.html | 4 ++-- nodemon.json | 2 +- readme.md | 15 +++++++++------ 5 files changed, 44 insertions(+), 15 deletions(-) diff --git a/app.js b/app.js index fce4639..2abb500 100644 --- a/app.js +++ b/app.js @@ -204,11 +204,24 @@ app.post('/send-media', async (req, res) => { }); }); +const findGroupByName = async function(name) { + const group = await client.getChats().then(chats => { + return chats.find(chat => + chat.isGroup && chat.name.toLowerCase() == name.toLowerCase() + ); + }); + return group; +} + // Send message to group -// -- Send message !groups to get all groups (id & name) -// -- So you can use that group id to send a message +// You can use chatID or group name, yea! app.post('/send-group-message', [ - body('id').notEmpty(), + body('id').custom((value, { req }) => { + if (!value && !req.body.name) { + throw new Error('Invalid value, you can use `id` or `name`'); + } + return true; + }), body('message').notEmpty(), ], async (req, res) => { const errors = validationResult(req).formatWith(({ @@ -224,9 +237,22 @@ app.post('/send-group-message', [ }); } - const chatId = req.body.id; + let chatId = req.body.id; + const groupName = req.body.name; const message = req.body.message; + // Find the group by name + if (!chatId) { + const group = await findGroupByName(groupName); + if (!group) { + return res.status(422).json({ + status: false, + message: 'No group found with name: ' + groupName + }); + } + chatId = group.id._serialized; + } + client.sendMessage(chatId, message).then(response => { res.status(200).json({ status: true, diff --git a/index-multiple-device.html b/index-multiple-device.html index d61d847..f929e79 100644 --- a/index-multiple-device.html +++ b/index-multiple-device.html @@ -41,8 +41,8 @@ - - + + - + +