Skip to content

Commit

Permalink
Merge branch 'master' of https://github.com/jonalan7/Hydra-bot
Browse files Browse the repository at this point in the history
  • Loading branch information
jonalan7 committed Aug 5, 2022
2 parents f95f70b + 3757ddb commit eba4f40
Show file tree
Hide file tree
Showing 11 changed files with 556 additions and 560 deletions.
3 changes: 2 additions & 1 deletion .release-it.yml
Expand Up @@ -5,10 +5,11 @@ git:

hooks:
after:bump:
- 'npm run build'
- 'npm run changelog:update'

# automatic publish from github workflow
npm:
publish: false
private: true
registry: 'OMITTED'
registry: 'OMITTED'
332 changes: 131 additions & 201 deletions CHANGELOG.md

Large diffs are not rendered by default.

548 changes: 299 additions & 249 deletions README.md

Large diffs are not rendered by default.

98 changes: 14 additions & 84 deletions bot-test/index.js
@@ -1,87 +1,17 @@
const hydraBot = require('../dist');
const mime = require('mime-types');
const fs = require('fs');
(async () => {

// hydraBot.initWs({
// puppeteerOptions: {
// headless: false,
// }
// });


let client;
// start bot service
const ev = await hydraBot.initServer({
session: 'geovane',
puppeteerOptions: {
headless: false,
}
// start Web Service
const WS = await hydraBot.initWs({
port: '8001',
authentication: true, // ask for authentication in routes
printQRInTerminal: true, // The QR CODE will be printed on the terminal if true
updatesLog: true, // Logs info updates automatically in terminal
timeAutoClose: 60000, // If you don't read the QR CODE by default 60 seconds, it will automatically close the client's browser to save memory, if you want to disable it, set 0 or false
puppeteerOptions: {
headless: false, // Start the project with the browser open or not!
args: [], // Additional arguments to pass to the browser instance. adding any parameter you will replace the default args of the project
executablePath: 'useChrome', // The browser that will be used for the project, you can specify a path, if you don't pass any parameters it will open the installed browser.
},
});

// return to current whatsapp interface
ev.on('interfaceChange', (change) => {
console.log("interfaceChange: ", change);
});

// return qrcode parameters
ev.on('qrcode', (qrcode) => {
console.log('qrcode: ', qrcode);
});

// return connection information
ev.on('connection', async (conn) => {

// browser information!
if (conn.statusFind === 'browser') {
console.log('info Browser: ', conn.text);
}

// if (conn.statusFind === 'page') {
// conn.page
// }

// Was connected to whatsapp chat
if (conn.connect) {
// send a text message
client = conn.client;
// await client.sendMessage({
// to: "0000000000@c.us",
// body: "Oi eu sou um bot",
// options: {
// type: 'text',
// }
// }).then((result) => {
// console.log(result);
// }).catch((error) => {
// console.log(error);
// });

}
});

// return receive new messages
ev.on('newMessage', async (newMsg) => {
// when is received
if (!newMsg.result.isSentByMe) {
// message received!
console.log('NewMessageReceived: ', newMsg.result);
// dowload files
if (newMsg.result.isMedia === true || newMsg.result.isMMS === true) {
const buffer = await client.decryptFile(newMsg.result);
// At this point you can do whatever you want with the buffer
// Most likely you want to write it into a file
const fileName = `some-file-name.${mime.extension(newMsg.result.mimetype)}`;
await fs.writeFile(fileName, buffer, (err) => {
console.log(err);
});
}
}
// when is it sent
if (!!newMsg.result.isSentByMe) {
// Message sent
//console.log('NewMessageSent: ', newMsg.result);
}
});

})();
})();

4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
@@ -1,6 +1,6 @@
{
"name": "hydra-bot",
"version": "1.0.28",
"version": "1.0.29-0",
"description": "The most reliable WhatsApp tool for chatbots with advanced features. Hydra bot is an open source project developed by the JavaScript community with the aim of exporting functions from WhatsApp Web to the node js, . The most complete javascript library for Whatsapp, 100% Open Source.",
"main": "dist/index.js",
"types": "dist/index.d.ts",
Expand Down
14 changes: 14 additions & 0 deletions src/webpack/api/layes/retriever.layer.ts
@@ -1,6 +1,7 @@
import { GroupLayer } from './group.layer';
import { Page, Browser } from 'puppeteer';
import { CreateOptions, InterfaceHost, contact } from '../../model/interface';
import { onMode } from '../../model/enum';

export class RetrieverLayer extends GroupLayer {
constructor(
Expand All @@ -27,4 +28,17 @@ export class RetrieverLayer extends GroupLayer {
public async getHost(): Promise<InterfaceHost> {
return await this.page.evaluate(() => API.getHost());
}

/**
* Get screenshot
* @returns base64 image
*/
public async screenshot() {
const base64 = await this.page
.screenshot({
encoding: 'base64',
})
.catch(() => undefined);
return { base64Image: `data:image/png;base64,${base64}` };
}
}
43 changes: 43 additions & 0 deletions src/ws/routers/functions/get.ts
Expand Up @@ -134,4 +134,47 @@ export class InicializeGet {
});
}
}

static async screenshot(req: Request, res: Response, option: options) {
const $_HEADERS_USER = req.headers?.user;

if (option.authentication) {
const user = await Users.CheckUserLogin(req);
if (user.erro) {
return res.send(user);
}
}
const check = await sessionClient.checkClient($_HEADERS_USER);
if (check) {
const getId = await sessionClient.getSessionId($_HEADERS_USER);
if (typeof getId === 'number') {
const client = await sessionClient.checkObjectSession(
$_HEADERS_USER,
'connect',
getId
);
if (client && InicializeRouters.inicialize) {
const getUser = await sessionClient.getUser($_HEADERS_USER);
getUser.child.send({ type: 'screenshot' });
this.child.on('message', (response: any) => {
if (response.result && response.typeGet === 'screenshot') {
try {
return res.status(200).send(response);
} catch {}
}
});
} else {
return res.send({
erro: true,
text: 'Waiting for connection with whatsapp',
});
}
}
} else {
return res.send({
erro: true,
text: 'Not connected',
});
}
}
}
14 changes: 8 additions & 6 deletions src/ws/routers/functions/post.ts
Expand Up @@ -245,18 +245,21 @@ export class InicializePost extends InicializeGet {
const check = await sessionClient.checkClient($_HEADERS_USER);
if (check) {
const getId = await sessionClient.getSessionId($_HEADERS_USER);

if (typeof getId === 'number') {
const getUser = await sessionClient.getUser($_HEADERS_USER);
getUser.child.send({ type: 'disconnect' });
this.child.on('message', async (response: any) => {
if (
response.result &&
response.typeSend === 'disconnect'
) {
if (response.result && response.typeSend === 'disconnect') {
try {
await sessionClient.deleteSession($_HEADERS_USER);
return res.send(response);
} catch {}
} catch (error) {
return res.send({
erro: true,
text: "Error disconnect, can't delete the session",
});
}
}
});
}
Expand All @@ -267,5 +270,4 @@ export class InicializePost extends InicializeGet {
});
}
}

}
5 changes: 5 additions & 0 deletions src/ws/routers/webpack/get.ts
Expand Up @@ -24,6 +24,11 @@ export const getRouters = (
await InicializeRouters.lastQrcode(req, res, option);
});

// Get screenshot
router.get('/screenshot', async (req: Request, res: Response) => {
await InicializeRouters.screenshot(req, res, option);
});

// Load Files
router.get('/files/:file', async (req: Request, res: Response) => {
const getFile: string = req.params.file;
Expand Down
53 changes: 37 additions & 16 deletions src/ws/services/hydra.ts
Expand Up @@ -57,23 +57,29 @@ async function Webhook(options: any, info: any) {
ev.on(onMode.newMessage, async (msg: any) => {
if (!msg.result.isSentByMe) {
if (msg.result.isMedia === true || msg.result.isMMS === true) {
const buffer = await client.decryptFile(msg.result);
const folder: string = path.join(path.resolve(process.cwd(), 'files'));
if (!fs.existsSync(folder)) {
fs.mkdirSync(folder, {
recursive: true,
try {
const buffer = await client.decryptFile(msg.result);
const folder: string = path.join(
path.resolve(process.cwd(), 'files')
);
if (!fs.existsSync(folder)) {
fs.mkdirSync(folder, {
recursive: true,
});
}
fs.chmodSync(folder, '777');
const fileConcat = `${msg.result.id}.${mime.extension(
msg.result.mimetype
)}`;
fs.writeFile(folder + '/' + fileConcat, buffer, (e) => {
if (e) {
console.log(e);
}
});
Object.assign(msg.result, { fileUrl: fileConcat });
} catch (error) {
console.log(error);
}
fs.chmodSync(folder, '777');
const fileConcat = `${msg.result.id}.${mime.extension(
msg.result.mimetype
)}`;
fs.writeFile(folder + '/' + fileConcat, buffer, (e) => {
if (e) {
console.log(e);
}
});
Object.assign(msg.result, { fileUrl: fileConcat });
}
}
Webhook(objOptions, msg);
Expand Down Expand Up @@ -194,12 +200,27 @@ async function Webhook(options: any, info: any) {
});
}

if (response.type === 'screenshot') {
await client
.screenshot()
.then((result: any) => {
sendParent({ typeGet: 'screenshot', result: true, ...result });
})
.catch((error: any) => {
sendParent({ typeGet: 'screenshot', result: true, ...error });
});
}

if (response.type === 'disconnect') {
try {
client.close();
sendParent({ typeSend: 'disconnect', result: true });
process.exit();
} catch {}
} catch (e) {
console.log(e);
sendParent({ typeSend: 'disconnect', result: true });
process.exit();
}
}
});
})();

0 comments on commit eba4f40

Please sign in to comment.