From 9378e101ebe68ce16e670fbbdb34b0a71ceeeede Mon Sep 17 00:00:00 2001 From: Caio Henrique Agiani Date: Sun, 6 Jun 2021 16:22:28 -0300 Subject: [PATCH] refact(project): adjusted dispatch commands (#37) * chore(gitignore): removed .ide * chore(package): update version and upgrade packages * refact(project): adjusted dispatch commands --- .gitignore | 2 ++ package.json | 18 +++++++----------- src/app/commands/CepCommand.ts | 4 ++-- src/app/commands/EconomyCommand.ts | 2 +- src/app/commands/ProfileCommand.ts | 18 +++++++++++++----- src/app/commands/QuoteCommand.ts | 8 ++++---- src/app/commands/SmsCommand.ts | 2 +- src/app/commands/index.ts | 28 +++++++++++++++++++++++----- src/index.ts | 25 ++----------------------- src/services/whatsapp.ts | 26 +++++--------------------- 10 files changed, 60 insertions(+), 73 deletions(-) diff --git a/.gitignore b/.gitignore index 09dec44..ba7fc40 100644 --- a/.gitignore +++ b/.gitignore @@ -12,3 +12,5 @@ src/data/session.json !src/data/.gitkeep src/config/integrantes.json + +.idea diff --git a/package.json b/package.json index 571655c..f4cc376 100644 --- a/package.json +++ b/package.json @@ -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", @@ -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" } } diff --git a/src/app/commands/CepCommand.ts b/src/app/commands/CepCommand.ts index 59e389b..f854ca5 100644 --- a/src/app/commands/CepCommand.ts +++ b/src/app/commands/CepCommand.ts @@ -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( @@ -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!'); } } } diff --git a/src/app/commands/EconomyCommand.ts b/src/app/commands/EconomyCommand.ts index c72e632..acf4b10 100644 --- a/src/app/commands/EconomyCommand.ts +++ b/src/app/commands/EconomyCommand.ts @@ -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', diff --git a/src/app/commands/ProfileCommand.ts b/src/app/commands/ProfileCommand.ts index b340543..e2658cc 100644 --- a/src/app/commands/ProfileCommand.ts +++ b/src/app/commands/ProfileCommand.ts @@ -13,7 +13,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!'); @@ -21,16 +21,24 @@ export default class ProfileCommand { 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'); } } diff --git a/src/app/commands/QuoteCommand.ts b/src/app/commands/QuoteCommand.ts index 859d741..0ff0ade 100644 --- a/src/app/commands/QuoteCommand.ts +++ b/src/app/commands/QuoteCommand.ts @@ -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!', ); diff --git a/src/app/commands/SmsCommand.ts b/src/app/commands/SmsCommand.ts index 6f15f6a..887f981 100644 --- a/src/app/commands/SmsCommand.ts +++ b/src/app/commands/SmsCommand.ts @@ -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!'); diff --git a/src/app/commands/index.ts b/src/app/commands/index.ts index 777e29b..cd1e317 100644 --- a/src/app/commands/index.ts +++ b/src/app/commands/index.ts @@ -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); +}; diff --git a/src/index.ts b/src/index.ts index fb9cd70..100eb34 100644 --- a/src/index.ts +++ b/src/index.ts @@ -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); }); diff --git a/src/services/whatsapp.ts b/src/services/whatsapp.ts index a3f9940..de3f4e2 100644 --- a/src/services/whatsapp.ts +++ b/src/services/whatsapp.ts @@ -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({ @@ -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( '5511963928063@c.us', - `[${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 };