Browse Source

initial commit

main
Angga 1 year ago
commit
c085755de5
  1. 3
      .gitignore
  2. 20
      Dockerfile
  3. 159
      botmon.js
  4. 9
      config.js
  5. 8162
      package-lock.json
  6. 6
      package.json
  7. BIN
      screenshot.png
  8. 71
      utils.js

3
.gitignore vendored

@ -0,0 +1,3 @@ @@ -0,0 +1,3 @@
assets/images/
node_modules/
tokens/

20
Dockerfile

@ -0,0 +1,20 @@ @@ -0,0 +1,20 @@
FROM node:22
RUN apt update && apt install curl gnupg -y \
&& curl --location --silent https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add - \
&& sh -c 'echo "deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google.list' \
&& apt update \
&& apt install google-chrome-stable -y --no-install-recommends \
&& rm -rf /var/lib/apt/lists/*
RUN mkdir -p /home/node/app && mkdir -p /home/node/app/assets/images
WORKDIR /home/node/app
COPY package*.json ./
COPY botmon.js config.js utils.js ./
RUN npm install
RUN chown -R node:node /home/node/app
EXPOSE 5000
CMD [ "node", "botmon.js" ]

159
botmon.js

@ -0,0 +1,159 @@ @@ -0,0 +1,159 @@
const express = require('express');
const venom = require('venom-bot');
const app = express();
let botClient;
app.use(express.json({ limit: '10mb' }));
const { session_name, port, browser_args } = require('./config.js');
const { send_message, send_image, get_all_chats, base64ToFile } = require('./utils.js');
venom
.create(
//session
session_name, //Pass the name of the client you want to start the bot
//catchQR
(base64Qrimg, asciiQR, attempts, urlCode) => {
console.log('Number of attempts to read the qrcode: ', attempts);
console.log('Terminal qrcode: ', asciiQR);
console.log('base64 image string qrcode: ', base64Qrimg);
console.log('urlCode (data-ref): ', urlCode);
},
// statusFind
(statusSession, session) => {
console.log('Status Session: ', statusSession); //return isLogged || notLogged || browserClose || qrReadSuccess || qrReadFail || autocloseCalled || desconnectedMobile || deleteToken || chatsAvailable || deviceNotConnected || serverWssNotConnected || noOpenBrowser || initBrowser || openBrowser || connectBrowserWs || initWhatsapp || erroPageWhatsapp || successPageWhatsapp || waitForLogin || waitChat || successChat
//Create session wss return "serverClose" case server for close
console.log('Session name: ', session);
},
// options
{
browserPathExecutable: '/usr/bin/google-chrome-stable', // browser executable path
folderNameToken: 'tokens', //folder name when saving tokens
mkdirFolderToken: '', //folder directory tokens, just inside the venom folder, example: { mkdirFolderToken: '/node_modules', } //will save the tokens folder in the node_modules directory
headless: 'new', // you should no longer use boolean false or true, now use false, true or 'new' learn more https://developer.chrome.com/articles/new-headless/
devtools: false, // Open devtools by default
debug: false, // Opens a debug session
logQR: true, // Logs QR automatically in terminal
browserWS: '', // If u want to use browserWSEndpoint
browserArgs: ['--no-sandbox', browser_args], // Original parameters ---Parameters to be added into the chrome browser instance
addBrowserArgs: [], // Add broserArgs without overwriting the project's original
puppeteerOptions: {}, // Will be passed to puppeteer.launch
disableSpins: true, // Will disable Spinnies animation, useful for containers (docker) for a better log
disableWelcome: true, // Will disable the welcoming message which appears in the beginning
updatesLog: true, // Logs info updates automatically in terminal
autoClose: 60000, // Automatically closes the venom-bot only when scanning the QR code (default 60 seconds, if you want to turn it off, assign 0 or false)
createPathFileToken: false, // creates a folder when inserting an object in the client's browser, to work it is necessary to pass the parameters in the function create browserSessionToken
addProxy: [''], // Add proxy server exemple : [e1.p.webshare.io:01, e1.p.webshare.io:01]
userProxy: '', // Proxy login username
userPass: '' // Proxy password
},
// BrowserInstance
(browser, waPage) => {
console.log('Browser PID:', browser.process().pid);
waPage.screenshot({ path: 'screenshot.png' });
}
)
.then((client) => {
botClient = client
start(client);
})
.catch((erro) => {
console.log(erro);
});
function start(client) {
client.onMessage((message) => {
if (message.body === 'Hi' && message.isGroupMsg === false) {
client
.sendText(message.from, 'Welcome!')
.then((result) => {
console.log('Result: ', result); //return object success
})
.catch((erro) => {
console.error('Error when sending: ', erro); //return object error
});
}
});
}
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.get('/botmon/get-all-chats', (req, res) => {
var result = get_all_chats(botClient);
console.log('================ /botmon/get-all-chats');
result.then(function(data) {
if (data.code === 200) {
return res.status(200).json({status: 'success', result: data.result});
} else {
return res.status(500).json({status: 'error', result: data.result});
}
});
});
app.post('/botmon/send-message', (req, res) => {
const { to, message } = req.body;
console.log('================ /botmon/send-message');
if (!botClient) {
return res.status(500).json({ error: 'Bot is not initialized' });
}
console.log('to', to);
console.log('message', message);
var result = send_message(botClient, to, message);
result.then(function(data) {
if (data.code === 200) {
return res.status(200).json({status: 'success', result: data.result});
} else {
return res.status(500).json({status: 'error', result: data.result});
}
});
});
app.post('/botmon/send-image', (req, res) => {
const { to, name, caption, image_data } = req.body;
console.log('================ /botmon/send-image');
if (!botClient) {
return res.status(500).json({ error: 'Bot is not initialized' });
}
const now = new Date();
const formattedDate = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}`;
const formattedTime = `${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}${String(now.getSeconds()).padStart(2, '0')}`;
const path = 'assets/images/' + name + '-' + formattedDate + formattedTime + '.png';
console.log('to', to);
console.log('name', name);
console.log('caption', caption);
const base64_image = "data:image/png;base64," + image_data
if (base64ToFile(base64_image, path) === false) {
return res.status(500).json({ error: 'Error writing image to file'});
}
var result = send_image(botClient, to, base64_image, name, caption);
result.then(function(data) {
if (data.code === 200) {
return res.status(200).json({status: 'success', result: data.result});
} else {
return res.status(500).json({status: 'error', result: data.result});
}
})
});
// Start the Express server
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}/`);
});

9
config.js

@ -0,0 +1,9 @@ @@ -0,0 +1,9 @@
const session_name = process.env.session_name;
const port = process.env.port;
const browser_args = process.env.browser_args;
// const session_name = 'monitoringSession';
// const port = 6969;
// const browser_args = '--user-agent=Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36';
module.exports = { session_name, port, browser_args }

8162
package-lock.json generated

File diff suppressed because it is too large Load Diff

6
package.json

@ -0,0 +1,6 @@ @@ -0,0 +1,6 @@
{
"dependencies": {
"express": "^4.19.2",
"venom-bot": "^5.1.0"
}
}

BIN
screenshot.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.9 KiB

71
utils.js

@ -0,0 +1,71 @@ @@ -0,0 +1,71 @@
const fs = require('fs');
async function send_message(client, to, message) {
let res;
await client
.sendText(to, message)
.then((result) => {
console.log('success sending message');
res = {result: result, code: 200};
})
.catch((erro) => {
console.error('error while sending message')
res = {result: erro, code: 500};
});
return res
}
async function send_image(client, to, base64_image, name, caption = '') {
let res
await client
.sendImageFromBase64(to, base64_image, name, caption)
.then((result) => {
console.log('success sending image');
res = {result: result, code: 200};
})
.catch((erro) => {
console.error('error while sending image');
res = {result: erro, code: 500};
});
return res;
}
async function get_all_chats(client) {
let res;
await client
.getAllChats()
.then((result) => {
res = {result: result, code: 200};
})
.catch((erro) => {
res = {result: erro, code: 500};
});
return res;
}
function base64ToFile(base64, filePath) {
// Remove the Base64 prefix if it exists
const base64Data = base64.replace(/^data:image\/\w+;base64,/, '');
// Decode the Base64 string
const binaryData = Buffer.from(base64Data, 'base64');
// Write the binary data to a file
fs.writeFile(filePath, binaryData, (err) => {
if (err) {
console.error('Error writing file:', err);
return false
} else {
console.log('File saved successfully:', filePath);
return true
}
});
}
module.exports = { send_message, send_image, get_all_chats, base64ToFile }
Loading…
Cancel
Save