Skip to content

Commit

Permalink
refact(project): adjusted dispatch commands (#37)
Browse files Browse the repository at this point in the history
* chore(gitignore): removed .ide
* chore(package): update version and upgrade packages
* refact(project): adjusted dispatch commands
  • Loading branch information
caioagiani authored Jun 6, 2021
1 parent aa58aa8 commit 9378e10
Show file tree
Hide file tree
Showing 10 changed files with 60 additions and 73 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,5 @@ src/data/session.json
!src/data/.gitkeep

src/config/integrantes.json

.idea
18 changes: 7 additions & 11 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"name": "whatsapp-web-bot",
"main": "src/index.ts",
"description": "WhatsApp Bot",
"version": "0.5.0",
"version": "0.6.0",
"license": "MIT",
"keywords": [
"whatsapp",
Expand Down Expand Up @@ -48,26 +48,22 @@
"dependencies": {
"@types/node": "^15.0.1",
"axios": "^0.21.1",
"express": "^4.17.1",
"mobizon-node": "^0.3.1",
"node-base64-image": "^2.0.1",
"puppeteer": "^8.0.0",
"qr-image": "^3.2.0",
"qrcode-terminal": "^0.12.0",
"whatsapp-web.js": "^1.12.6"
},
"devDependencies": {
"@types/axios": "0.14.0",
"@types/puppeteer": "5.4.3",
"@typescript-eslint/eslint-plugin": "4.22.1",
"@typescript-eslint/parser": "4.22.1",
"dotenv": "8.2.0",
"eslint": "7.25.0",
"@typescript-eslint/eslint-plugin": "4.26.0",
"@typescript-eslint/parser": "4.26.0",
"dotenv": "10.0.0",
"eslint": "7.28.0",
"eslint-config-prettier": "8.3.0",
"eslint-loader": "4.0.2",
"eslint-plugin-prettier": "3.4.0",
"prettier": "2.2.1",
"prettier": "2.3.1",
"ts-node-dev": "1.1.6",
"typescript": "4.2.4"
"typescript": "4.3.2"
}
}
4 changes: 2 additions & 2 deletions src/app/commands/CepCommand.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ export default class EconomyCommand {

const chat = await msg.getChat();

chat.sendStateTyping();
await chat.sendStateTyping();

try {
const { data }: IResponse = await axios.get<IServerData>(
Expand All @@ -24,7 +24,7 @@ export default class EconomyCommand {
`*CEP*: ${data.cep}\n*Logradouro*: ${data.street}\n*Cidade*: ${data.city}\n*Bairro*: ${data.neighborhood}\n*UF*: ${data.state}`,
);
} catch (error) {
return msg.reply(`CEP não localizado!`);
return msg.reply('CEP não localizado!');
}
}
}
2 changes: 1 addition & 1 deletion src/app/commands/EconomyCommand.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ export default class EconomyCommand {
async execute(msg: Message) {
const chat = await msg.getChat();

chat.sendStateTyping();
await chat.sendStateTyping();

const { data } = await axios.get(
'https://economia.awesomeapi.com.br/all/USD-BRL,BTC-BRL,EUR-BRL',
Expand Down
18 changes: 13 additions & 5 deletions src/app/commands/ProfileCommand.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,24 +13,32 @@ export default class ProfileCommand {

const [contact] = await msg.getMentions();

chat.sendStateTyping();
await chat.sendStateTyping();

if (!chat.isGroup) {
return msg.reply('Comando apenas para grupos!');
}

if (!contact) return msg.reply('Contato não localizado.');

msg.reply('Stalkeando este contato...');
await msg.reply('Stalkeando este contato...');

const url_i = await client.getProfilePicUrl(contact.number);

if (!url_i) return msg.reply('Imagem não foi localizada.');

const image: any = await encode(url_i, { string: true });
const imageProfile = await encode(url_i, { string: true });

const media = new MessageMedia('image/png', image, `${contact.number}.png`);
if (typeof imageProfile === 'string') {
const media = new MessageMedia(
'image/png',
imageProfile,
`${contact.number}.png`,
);

return client.sendMessage(msg.from, media);
return client.sendMessage(msg.from, media);
}

return msg.reply('Erro inesperado');
}
}
8 changes: 4 additions & 4 deletions src/app/commands/QuoteCommand.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,15 @@ export default class QuoteCommand {

const { user: contato } = user.id;

chat.sendStateTyping();
await chat.sendStateTyping();

if (!chat.isGroup) {
return msg.reply('Comando apenas para grupos!');
}

company.map(async (valores) => {
if (valores.numero == contato) {
if (!valores.admin) {
company.map(async ({ numero, admin }) => {
if (numero == contato) {
if (!admin) {
return msg.reply(
'Ops, você não tem permissão para executar este comando!',
);
Expand Down
2 changes: 1 addition & 1 deletion src/app/commands/SmsCommand.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export default class ProfileCommand {

const [contact] = await msg.getMentions();

chat.sendStateTyping();
await chat.sendStateTyping();

if (!chat.isGroup) {
return msg.reply('Comando apenas para grupos!');
Expand Down
28 changes: 23 additions & 5 deletions src/app/commands/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,23 @@
export { default as EconomyCommand } from './EconomyCommand';
export { default as QuoteCommand } from './QuoteCommand';
export { default as CepCommand } from './CepCommand';
export { default as ProfileCommand } from './ProfileCommand';
export { default as SmsCommand } from './SmsCommand';
import { commandDispatcher } from '../utils/CommandDispatcher';

import EconomyCommand from './EconomyCommand';
import QuoteCommand from './QuoteCommand';
import CepCommand from './CepCommand';
import ProfileCommand from './ProfileCommand';
import SmsCommand from './SmsCommand';

export default async (message) => {
const economyCommand = new EconomyCommand();
const quoteCommand = new QuoteCommand();
const cepCommand = new CepCommand(message.body);
const profileCommand = new ProfileCommand(message.body);
const smsCommand = new SmsCommand(message.body);

await commandDispatcher.register('cotacao', economyCommand);
await commandDispatcher.register('mencionar', quoteCommand);
await commandDispatcher.register('cep', cepCommand);
await commandDispatcher.register('perfil', profileCommand);
await commandDispatcher.register('sms', smsCommand);

return commandDispatcher.dispatch(message.body.slice(1), message);
};
25 changes: 2 additions & 23 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,28 +1,7 @@
import { client } from './services/whatsapp';
import {
EconomyCommand,
QuoteCommand,
CepCommand,
ProfileCommand,
SmsCommand,
} from './app/commands';
import { commandDispatcher } from './app/utils/CommandDispatcher';
import type { Message } from 'whatsapp-web.js';
import dispatchCommand from './app/commands';

client.on('message', (message: Message) => {
const economyCommand = new EconomyCommand();
const quoteCommand = new QuoteCommand();
const cepCommand = new CepCommand(message.body);
const profileCommand = new ProfileCommand(message.body);
const smsCommand = new SmsCommand(message.body);

commandDispatcher.register('cotacao', economyCommand);
commandDispatcher.register('mencionar', quoteCommand);
commandDispatcher.register('cep', cepCommand);
commandDispatcher.register('perfil', profileCommand);
commandDispatcher.register('sms', smsCommand);

if (message.body.startsWith('!')) {
commandDispatcher.dispatch(message.body.slice(1), message);
}
if (message.body.startsWith('!')) return dispatchCommand(message);
});
26 changes: 5 additions & 21 deletions src/services/whatsapp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,7 @@ import { generate } from 'qrcode-terminal';
import { existsSync, writeFile, unlink } from 'fs';
import { resolve } from 'path';

interface INotification {
reply: (args: string) => void;
recipientIds: any[];
}

const sessionFile = resolve('src', 'data', 'session.json');

const session = existsSync(sessionFile) ? require(sessionFile) : null;

const client = new Client({
Expand All @@ -31,37 +25,27 @@ client.on('authenticated', (session: any) => {
});

client.on('ready', async () => {
console.log('WhatsApp bot conectado com sucesso!');
console.log('WhatsApp bot successfully connected!');

const { pushname } = client.info;

client.sendMessage(
await client.sendMessage(
'[email protected]',
`[${pushname}] - WhatsApp Online\n\n[x] Star on project: https://github.com/caioagiani/whatsapp-bot`,
`[${client.info.pushname}] - WhatsApp Online\n\n[x] Star project: https://github.com/caioagiani/whatsapp-bot`,
);
});

client.on('auth_failure', () => {
unlink(sessionFile, () => {
console.log('Autenticação falhou, tente novamente.');
console.log('Authentication failed, try again.');
process.exit(1);
});
});

client.on('disconnected', () => {
unlink(sessionFile, () =>
console.log('Sessão WhatsApp perdeu a conexão, tente novamente.'),
console.log('WhatsApp session lost connection, try again.'),
);
});

client.on('group_join', (notification: INotification) => {
notification.reply(`${notification.recipientIds[0]} entrou no grupo.`);
});

client.on('group_leave', (notification: INotification) => {
notification.reply(`${notification.recipientIds[0]} saiu do grupo.`);
});

client.initialize();

export { client, MessageMedia };

0 comments on commit 9378e10

Please sign in to comment.