- đ Anti pirata: deletar mensagem hacker
- đ Remover links nĂŁo autorizados
- đ Listar grupos e capturar todos que entram usando banco de dados
- đ Mensagem de saudação e menção de usuĂĄrio
- đ Controle de grupos em massa com comandos via webhook (post)
- đŁïž Controle de grupos em massa com comandos via chat
- INSTALAR NODE E GIT
- INSTALAR A API
a. criar pasta
b. criar arquivos
c. npm install
d. iniciar a api
e. ler o qrcode
index.html
WPP API by Pedrinho da NASA
package.json
{"name":"bot-zdg","version":"1.0.0","description":"bot-zdg: based on Whatsapp API","main":"app.js","scripts":{"start":"node .\botzdg_typebot_stop.js","start:dev":"nodemon app.js","test":"echo \"Error: no test specified\" && exit 1"},"keywords":["whatsapp-api","node.js"],"author":"Pedro","license":"MIT","dependencies":{"axios":"^1.5.0","express":"^4.17.1","express-fileupload":"^1.2.0","express-validator":"^6.9.2","http":"0.0.1-security","mysql2":"^3.6.3","qrcode":"^1.4.4","qrcode-terminal":"^0.12.0","socket.io":"2.3.0","whatsapp-web.js":"^1.23.0"},"devDependencies":{"nodemon":"^2.0.19"}}
botzdg_grupos_maratona_aula5.js
// BACKEND DA API
// BIBLIOTECAS UTILIZADAS PARA COMPOSIĂĂO DA API
const { Client, LocalAuth, MessageMedia } = require('whatsapp-web.js');
const express = require('express');
const socketIO = require('socket.io');
const qrcode = require('qrcode');
const http = require('http');
const fileUpload = require('express-fileupload');
const { body, validationResult } = require('express-validator');
const app = express();
const server = http.createServer(app);
const io = socketIO(server);
// PORTA ONDE O SERVIĂO SERĂ INICIADO
const port = 8001;
const idClient = 'bot-zdg-maratona-grupos';
// NUMEROS AUTORIZADOS
const permissaoBot = ["5511123465789@c.us","5530123456@c.us"];
// SERVIĂO EXPRESS
app.use(express.json());
app.use(express.urlencoded({
extended: true
}));
app.use(fileUpload({
debug: true
}));
app.use("/", express.static(__dirname + "/"))
app.get('/', (req, res) => {
res.sendFile('index.html', {
root: __dirname
});
});
// PARĂMETROS DO CLIENT DO WPP
const client = new Client({
authStrategy: new LocalAuth({ clientId: idClient }),
puppeteer: { headless: true,
// CAMINHO DO CHROME PARA WINDOWS (REMOVER O COMENTĂRIO ABAIXO)
// executablePath: 'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe',
//===================================================================================
// CAMINHO DO CHROME PARA MAC (REMOVER O COMENTĂRIO ABAIXO)
//executablePath: '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
//===================================================================================
// CAMINHO DO CHROME PARA LINUX (REMOVER O COMENTĂRIO ABAIXO)
//executablePath: '/usr/bin/google-chrome-stable',
//===================================================================================
args: [
'--no-sandbox',
'--disable-setuid-sandbox',
'--disable-dev-shm-usage',
'--disable-accelerated-2d-canvas',
'--no-first-run',
'--no-zygote',
'--single-process', // <- this one doesn't works in Windows
'--disable-gpu'
] }
});
// INITIALIZE DO CLIENT DO WPP
client.initialize();
// EVENTOS DE CONEXĂO EXPORTADOS PARA O INDEX.HTML VIA SOCKET
io.on('connection', function(socket) {
socket.emit('message', '© BOT-ZDG - Iniciado');
socket.emit('qr', './icon.svg');
client.on('qr', (qr) => {
console.log('QR RECEIVED', qr);
qrcode.toDataURL(qr, (err, url) => {
socket.emit('qr', url);
socket.emit('message', '© BOT-ZDG QRCode recebido, aponte a cùmera seu celular!');
});
});
client.on('ready', async () => {
socket.emit('ready', '© BOT-ZDG Dispositivo pronto!');
socket.emit('message', '© BOT-ZDG Dispositivo pronto!');
socket.emit('qr', './check.svg')
console.log('© BOT-ZDG Dispositivo pronto');
const groups = await client.getChats()
for (const group of groups){
if(group.id.server.includes('g.us')){
socket.emit('message', 'Nome: ' + group.name + ' - ID: ' + group.id._serialized.split('@')[0]);
console.log('Nome: ' + group.name + ' - ID: ' + group.id._serialized.split('@')[0])
}
}
});
client.on('authenticated', () => {
socket.emit('authenticated', '© BOT-ZDG Autenticado!');
socket.emit('message', '© BOT-ZDG Autenticado!');
console.log('© BOT-ZDG Autenticado');
});
client.on('auth_failure', function() {
socket.emit('message', '© BOT-ZDG Falha na autenticação, reiniciando...');
console.error('© BOT-ZDG Falha na autenticação');
});
client.on('change_state', state => {
console.log('© BOT-ZDG Status de conexão: ', state );
});
client.on('disconnected', (reason) => {
socket.emit('message', '© BOT-ZDG Cliente desconectado!');
console.log('© BOT-ZDG Cliente desconectado', reason);
client.initialize();
});
});
// EVENTO DE ESCUTA DE MENSAGENS RECEBIDAS PELA API
client.on('message', async msg => {
if (msg.body === null) return;
// COMANDO BOT
if (msg.body.startsWith('!gr ')) {
// CRIAR GRUPO
try {
if (!permissaoBot.includes(msg.author || msg.from)) return msg.reply("VocĂȘ nĂŁo pode enviar esse comando.");
let number = msg.body.split('-')[1].replace(/\D/g,'');
let message = msg.body.split('-')[0].replace('!gr ','');
number = number.includes('@c.us') ? number : `${number}@c.us`;
try {
client.createGroup(message, [number]);
console.log('Grupo criado: ' + message);
} catch(e){
console.log('Erro ao criar grupo: ' + e);
}
} catch(e){
console.log('Erro ao criar grupo: ' + e);
}
}
else if (msg.body.startsWith('!zdg ')) {
// MENSAGEM DIRETA PARA CADA USUARIO DOS GRUPOS ONDE O BOT Ă ADMIN
try {
if (!permissaoBot.includes(msg.author || msg.from)) return msg.reply("VocĂȘ nĂŁo pode enviar esse comando.");
let newMsgZDG = msg.body.slice(5);
client.getChats().then(chats => {
const groups = chats.filter(chat => chat.isGroup);
if (groups.length == 0) {
msg.reply('VocĂȘ nĂŁo tem grupos.');
}
else {
groups.forEach((group, i) => {
const participants = group.participants;
participants.forEach((participant, j) => {
if (participant.id.server === 'c.us') {
const user = `${participant.id.user}@c.us`;
setTimeout(function() {
try {
client.sendMessage(user, newMsgZDG);
} catch(e){
console.log('Erro ao enviar mensagem em massa: ' + e);
}
}, 1000 + Math.floor(Math.random() * 4000) * (i + 1) + j * 500);
}
});
});
}
});
} catch(e){
console.log('Erro ao enviar mensagem em massa: ' + e);
}
}
else if (msg.body.startsWith('!enviarpara ')) {
// MENSAGEM DIRETA PARA O TELEFONE
if (!permissaoBot.includes(msg.author || msg.from)) return msg.reply("VocĂȘ nĂŁo pode enviar esse comando.");
let number = msg.body.split('-')[1].replace(/\D/g,'');
let message = msg.body.split('-')[0].replace('!enviarpara ','');
number = number.includes('@c.us') ? number : `${number}@c.us`;
let chat = await msg.getChat();
try{
chat.sendSeen();
client.sendMessage(number, message);
} catch(e){
console.log('Erro ao enviar mensagem individual: ' + e);
}
}
else if (msg.body.startsWith('!assunto ')) {
// MUDAR TITULO DO GRUPO
if (!permissaoBot.includes(msg.author || msg.from)) return msg.reply("VocĂȘ nĂŁo pode enviar esse comando.");
let newSubject = msg.body.slice(9);
client.getChats().then(chats => {
const groups = chats.filter(chat => chat.isGroup);
if (groups.length == 0) {
msg.reply('VocĂȘ nĂŁo tem grupos.');
}
else {
groups.forEach((group, i) => {
setTimeout(function() {
try{
group.setSubject(newSubject);
console.log('Assunto alterado para o grupo: ' + group.name);
} catch(e){
console.log('Erro ao alterar assunto do grupo: ' + group.name);
}
},1000 + Math.floor(Math.random() * 4000) * (i+1) )
});
}
});
}
else if (msg.body.startsWith('!descricao ')) {
// MUDAR DESCRICAO DO GRUPO
if (!permissaoBot.includes(msg.author || msg.from)) return msg.reply("VocĂȘ nĂŁo pode enviar esse comando.");
let newDescription = msg.body.slice(11);
client.getChats().then(chats => {
const groups = chats.filter(chat => chat.isGroup);
if (groups.length == 0) {
msg.reply('VocĂȘ nĂŁo tem grupos.');
}
else {
groups.forEach((group, i) => {
setTimeout(function() {
try{
group.setDescription(newDescription);
console.log('Descrição alterada para o grupo: ' + group.name);
} catch(e){
console.log('Erro ao alterar descrição do grupo: ' + group.name);
}
},1000 + Math.floor(Math.random() * 4000) * (i+1) )
});
}
});
}
else if (msg.body.startsWith('!ban ')) {
// BAN USUARIO PIRATA
if (!permissaoBot.includes(msg.author || msg.from)) return msg.reply("VocĂȘ nĂŁo pode enviar esse comando.");
let usuarioPirata = msg.body.slice(5);
client.getChats().then(chats => {
const groups = chats.filter(chat => chat.isGroup);
if (groups.length == 0) {
msg.reply('VocĂȘ nĂŁo tem grupos.');
}
else {
groups.forEach((group, i) => {
setTimeout(async function() {
try {
await group.removeParticipants([usuarioPirata + `@c.us`]);
console.log('Participante ' + usuarioPirata + ' banido do grupo: ' + group.name);
} catch(e){
console.log('Participante nĂŁo faz parte do grupo: ' + group.name);
}
},1000 + Math.floor(Math.random() * 4000) * (i+1) )
});
}
});
}
else if (msg.body.startsWith('!fechargrupo')) {
// FECHAR TODOS OS GRUPOS QUE O BOT Ă ADMIN;
if (!permissaoBot.includes(msg.author || msg.from)) return msg.reply("VocĂȘ nĂŁo pode enviar esse comando.");
client.getChats().then(chats => {
const groups = chats.filter(chat => chat.isGroup);
if (groups.length == 0) {
msg.reply('VocĂȘ nĂŁo tem grupos.');
}
else {
groups.forEach((group, i) => {
setTimeout(function() {
try {
group.setMessagesAdminsOnly(true);
console.log('Grupo fechado: ' + group.name);
} catch(e){
console.log('Erro ao fechar grupo: ' + group.name);
}
},1000 + Math.floor(Math.random() * 4000) * (i+1) )
});
}
});
}
else if (msg.body.startsWith('!abrirgrupo')) {
//ABRIR TODOS OS GRUPOS QUE O BOT Ă ADMIN;
if (!permissaoBot.includes(msg.author || msg.from)) return msg.reply("VocĂȘ nĂŁo pode enviar esse comando.");
client.getChats().then(chats => {
const groups = chats.filter(chat => chat.isGroup);
if (groups.length == 0) {
msg.reply('You have no group yet.');
}
else {
groups.forEach((group, i) => {
setTimeout(function() {
try {
group.setMessagesAdminsOnly(false);
console.log('Grupo aberto: ' + group.name);
} catch(e){
console.log('Erro ao abrir grupo: ' + group.name);
}
},1000 + Math.floor(Math.random() * 4000) * (i+1) )
});
}
});
}
});
// INITIALIZE DO SERVIĂO
server.listen(port, function() {
console.log('© Comunidade ZDG - Aplicativo rodando na porta *: ' + port);
});