a
This commit is contained in:
1
.gitignore
vendored
1
.gitignore
vendored
@@ -2,3 +2,4 @@ env.js
|
||||
.wwebjs_auth
|
||||
.wwebjs_cache
|
||||
downloads
|
||||
node_modules/
|
||||
12
README.md
12
README.md
@@ -1,2 +1,10 @@
|
||||
# manybot
|
||||
Cool whatsapp bot. Local and free.
|
||||
# ManyBot!
|
||||
|
||||
Criei esse bot para servir um grupo de amigos. Meu foco não é fazer ele funcionar para todo mundo.
|
||||
|
||||
Ele é 100% local e gratuito, sem necessidade de APIs burocraticas. Usufrui da biblioteca `whatsapp-web.js`, que permite bastante coisa mesmo sem a API oficial.
|
||||
|
||||
Algumas funcionalidades desse bot inclui:
|
||||
- Funciona em multiplos chats em apenas uma única sessão
|
||||
- Comandos de jogos e download com yt-dlp
|
||||
-
|
||||
6
deploy.sh
Normal file
6
deploy.sh
Normal file
@@ -0,0 +1,6 @@
|
||||
#!/bin/bash
|
||||
|
||||
|
||||
|
||||
TAG=$(git describe --tags --abbrev=0)
|
||||
npm version $TAG --no-git-tag-version
|
||||
50
get_id.js
50
get_id.js
@@ -1,4 +1,13 @@
|
||||
// main.js
|
||||
// get_id.js
|
||||
|
||||
const arg = process.argv[2]; // argumento passado no node
|
||||
if (!arg) {
|
||||
console.log("Use: node get_id.js grupos|contatos|<nome>");
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
console.log("[PESQUISANDO] Aguarde...");
|
||||
|
||||
import pkg from 'whatsapp-web.js';
|
||||
const { Client, LocalAuth } = pkg;
|
||||
import qrcode from 'qrcode-terminal';
|
||||
@@ -15,22 +24,37 @@ client.on('qr', qr => {
|
||||
qrcode.generate(qr, { small: true });
|
||||
});
|
||||
|
||||
client.on('ready', () => console.log("[BOT] WhatsApp conectado e sessão permanente"));
|
||||
client.on('ready', () => {
|
||||
console.log("[BOT] WhatsApp conectado e sessão permanente");
|
||||
});
|
||||
|
||||
client.on('message_create', async msg => {
|
||||
try {
|
||||
const chat = await msg.getChat(); // pega o chat uma única vez
|
||||
client.on('ready', async () => {
|
||||
const chats = await client.getChats();
|
||||
|
||||
console.log("==================================");
|
||||
console.log(`CHAT NAME : ${chat.name || chat.id.user || "Sem nome"}`);
|
||||
console.log(`CHAT ID : ${chat.id._serialized}`);
|
||||
console.log(`FROM : ${msg.from}`);
|
||||
console.log(`BODY : ${msg.body}`);
|
||||
console.log("==================================\n");
|
||||
let filtered = [];
|
||||
|
||||
} catch (err) {
|
||||
console.error("[ERRO]", err);
|
||||
if (arg.toLowerCase() === "grupos") {
|
||||
filtered = chats.filter(c => c.isGroup);
|
||||
} else if (arg.toLowerCase() === "contatos") {
|
||||
filtered = chats.filter(c => !c.isGroup);
|
||||
} else {
|
||||
const search = arg.toLowerCase();
|
||||
filtered = chats.filter(c => (c.name || c.id.user).toLowerCase().includes(search));
|
||||
}
|
||||
|
||||
if (filtered.length === 0) {
|
||||
console.log("Nenhum chat encontrado com esse filtro.");
|
||||
} else {
|
||||
console.log(`Encontrados ${filtered.length} chats:`);
|
||||
filtered.forEach(c => {
|
||||
console.log("================================");
|
||||
console.log("NAME:", c.name || c.id.user);
|
||||
console.log("ID:", c.id._serialized);
|
||||
console.log("GROUP:", c.isGroup);
|
||||
});
|
||||
}
|
||||
|
||||
process.exit(0); // fecha o script após listar
|
||||
});
|
||||
|
||||
client.initialize();
|
||||
106
main.js
106
main.js
@@ -1,44 +1,54 @@
|
||||
// main_global.js
|
||||
console.log("[CARREGANDO] Aguarde...");
|
||||
|
||||
import pkg from 'whatsapp-web.js';
|
||||
const { Client, LocalAuth, MessageMedia } = pkg;
|
||||
|
||||
import qrcode from 'qrcode-terminal';
|
||||
import fs from 'fs';
|
||||
import { exec } from 'child_process';
|
||||
|
||||
const CHAT_ID_ALVO = process.argv[2];
|
||||
if (!CHAT_ID_ALVO) {
|
||||
console.error("Use: node main.js <ID_DO_CHAT>");
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// Cada chat tem um clientId único e persistente
|
||||
const CLIENT_ID = `chat_${CHAT_ID_ALVO.replace(/[^a-zA-Z0-9_-]/g, "_")}`;
|
||||
const CLIENT_ID = "bot_permanente"; // sessão única global
|
||||
const BOT_PREFIX = "🤖 *ManyBot:* ";
|
||||
|
||||
// lista fixa de chats que queremos interagir
|
||||
import { CHATS_PERMITIDOS } from "./env.js"
|
||||
// parecido com isso:
|
||||
/*
|
||||
export const CHATS_PERMITIDOS = [
|
||||
"123456789101234567@c.us", // pedrinho
|
||||
"987654321012345678@g.us" // escola
|
||||
];
|
||||
*/
|
||||
|
||||
let jogoAtivo = null;
|
||||
|
||||
// criar client único
|
||||
const client = new Client({
|
||||
authStrategy: new LocalAuth({ clientId: CLIENT_ID }),
|
||||
puppeteer: {
|
||||
headless: true,
|
||||
args: ['--no-sandbox', '--disable-setuid-sandbox'],
|
||||
timeout: 60000,
|
||||
}
|
||||
puppeteer: { headless: true }
|
||||
});
|
||||
|
||||
client.on('qr', qr => {
|
||||
console.log(`[${CHAT_ID_ALVO}] QR Code gerado. Escaneie apenas uma vez:`);
|
||||
console.log("[BOT] QR Code gerado. Escaneie apenas uma vez:");
|
||||
qrcode.generate(qr, { small: true });
|
||||
});
|
||||
|
||||
client.on('ready', () => console.log(`[${CHAT_ID_ALVO}] WhatsApp conectado.`));
|
||||
client.on('ready', () => {
|
||||
exec("clear");
|
||||
console.log("[BOT] WhatsApp conectado e sessão permanente");
|
||||
});
|
||||
|
||||
client.on('disconnected', reason => {
|
||||
console.warn(`[${CHAT_ID_ALVO}] Desconectado: ${reason}. Tentando reconectar...`);
|
||||
console.warn(`[BOT] Desconectado: ${reason}. Tentando reconectar...`);
|
||||
setTimeout(() => client.initialize(), 5000);
|
||||
});
|
||||
|
||||
client.on('message_create', async msg => {
|
||||
try {
|
||||
const chat = await msg.getChat();
|
||||
if (chat.id._serialized !== CHAT_ID_ALVO) return;
|
||||
|
||||
// filtra apenas chats permitidos
|
||||
if (!CHATS_PERMITIDOS.includes(chat.id._serialized)) return;
|
||||
|
||||
console.log("==================================");
|
||||
console.log(`CHAT NAME : ${chat.name || chat.id.user || "Sem nome"}`);
|
||||
@@ -55,6 +65,7 @@ client.on('message_create', async msg => {
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
// ---------------- Funções de envio ----------------
|
||||
|
||||
async function enviarVideo(cliente, chatId, caminhoArquivo) {
|
||||
@@ -88,7 +99,6 @@ function iniciarJogo(chat) {
|
||||
jogoAtivo = numeroSecreto;
|
||||
|
||||
console.log(`[JOGO] ${chat.name}: Número escolhido ${numeroSecreto}`);
|
||||
chat.sendMessage(botMsg("Hora do jogo! Tentem adivinhar o número de 1 a 100!"));
|
||||
}
|
||||
|
||||
// ---------------- Download ----------------
|
||||
@@ -101,45 +111,64 @@ let processingQueue = false;
|
||||
// Garantir que a pasta downloads exista
|
||||
if (!fs.existsSync('downloads')) fs.mkdirSync('downloads');
|
||||
|
||||
import { exec } from "child_process";
|
||||
function runYtDlp(cmd1, cmd2) {
|
||||
return new Promise((resolve, reject) => {
|
||||
exec(cmd1, (error, stdout, stderr) => {
|
||||
if (!error) return resolve({ stdout, stderr });
|
||||
|
||||
exec(cmd2, (error2, stdout2, stderr2) => {
|
||||
if (error2) return reject(error2);
|
||||
resolve({ stdout: stdout2, stderr: stderr2 });
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function get_video(url, id) {
|
||||
downloadsAtivos++;
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const cmd = `yt-dlp -t mp4 --print after_move:filepath -o "downloads/${id}.%(ext)s" "${url}"`;
|
||||
return new Promise(async (resolve, reject) => {
|
||||
const cmd1 = `yt-dlp -t mp4 --print after_move:filepath -o "downloads/${id}.%(ext)s" "${url}"`;
|
||||
const cmd2 = `.\yt-dlp.exe -t mp4 --print after_move:filepath -o "downloads/${id}.%(ext)s" "${url}"`;
|
||||
|
||||
exec(cmd, (error, stdout, stderr) => {
|
||||
try {
|
||||
const { stdout, stderr } = await runYtDlp(cmd1, cmd2);
|
||||
downloadsAtivos--;
|
||||
|
||||
if (stderr) console.error(stderr);
|
||||
if (error) return reject(new Error(`yt-dlp falhou: ${error.message}`));
|
||||
|
||||
const filepath = stdout.trim();
|
||||
if (!filepath) return reject(new Error("yt-dlp não retornou filepath"));
|
||||
|
||||
resolve(filepath);
|
||||
});
|
||||
} catch (err) {
|
||||
downloadsAtivos--;
|
||||
reject(new Error(`yt-dlp falhou: ${err.message}`));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function get_audio(url, id) {
|
||||
downloadsAtivos++;
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const cmd = `yt-dlp -t mp3 --print after_move:filepath -o "downloads/${id}.%(ext)s" "${url}"`;
|
||||
return new Promise(async (resolve, reject) => {
|
||||
const cmd1 = `yt-dlp -t mp3 --print after_move:filepath -o "downloads/${id}.%(ext)s" "${url}"`;
|
||||
const cmd2 = `.\yt-dlp.exe -t mp3 --print after_move:filepath -o "downloads/${id}.%(ext)s" "${url}"`;
|
||||
|
||||
exec(cmd, (error, stdout, stderr) => {
|
||||
try {
|
||||
const { stdout, stderr } = await runYtDlp(cmd1, cmd2);
|
||||
downloadsAtivos--;
|
||||
|
||||
if (stderr) console.error(stderr);
|
||||
if (error) return reject(new Error(`yt-dlp falhou: ${error.message}`));
|
||||
|
||||
const filepath = stdout.trim();
|
||||
if (!filepath) return reject(new Error("yt-dlp não retornou filepath"));
|
||||
|
||||
resolve(filepath);
|
||||
});
|
||||
} catch (err) {
|
||||
downloadsAtivos--;
|
||||
reject(new Error(`yt-dlp falhou: ${err.message}`));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -188,7 +217,7 @@ async function processarComando(msg) {
|
||||
if (tokens.length === 1) {
|
||||
chat.sendMessage(botMsg(
|
||||
"- `!many ping` -> testa se estou funcionando\n" +
|
||||
"- `!many jogo` -> jogo de adivinhação\n" +
|
||||
"- `!many adivinhação <começar|parar>` -> jogo de adivinhação\n" +
|
||||
"- `!many video <link>` -> baixo um vídeo da internet para você!\n" +
|
||||
"- `!many audio <link>` -> baixo um audio da internet para você!"
|
||||
));
|
||||
@@ -196,7 +225,20 @@ async function processarComando(msg) {
|
||||
}
|
||||
|
||||
if (tokens[1] === "ping") chat.sendMessage(botMsg("pong 🏓"));
|
||||
if (tokens[1] === "jogo") iniciarJogo(chat);
|
||||
if (tokens[1] === "adivinhação") {
|
||||
if (tokens[2] === undefined) {
|
||||
chat.sendMessage(botMsg("Acho que você se esqueceu de algo! 😅\n" +
|
||||
"🏁 `!many adivinhação começar` -> começa o jogo\n" +
|
||||
"🛑 `!many adivinhação parar` -> para o jogo atual"
|
||||
));
|
||||
} else if (tokens[2] === "começar") {
|
||||
iniciarJogo(chat);
|
||||
chat.sendMessage(botMsg("Hora do jogo! 🏁 Tentem adivinhar o número de 1 a 100 que eu estou pensando!"));
|
||||
} else if (tokens[2] === "parar") {
|
||||
jogoAtivo = null
|
||||
chat.sendMessage(botMsg("O jogo atual foi interrompido 🛑"));
|
||||
}
|
||||
}
|
||||
|
||||
if (tokens[1] === "video" && tokens[2]) {
|
||||
chat.sendMessage(botMsg("⏳ Baixando vídeo, aguarde..."));
|
||||
|
||||
6
package-lock.json
generated
6
package-lock.json
generated
@@ -7,7 +7,8 @@
|
||||
"dependencies": {
|
||||
"qrcode-terminal": "^0.12.0",
|
||||
"whatsapp-web.js": "^1.34.6"
|
||||
}
|
||||
},
|
||||
"version": "1.1.0"
|
||||
},
|
||||
"node_modules/@babel/code-frame": {
|
||||
"version": "7.29.0",
|
||||
@@ -2098,5 +2099,6 @@
|
||||
"url": "https://github.com/sponsors/colinhacks"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"version": "1.1.0"
|
||||
}
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
{
|
||||
"name": "whatsapp-bot",
|
||||
"version": "1.0.0",
|
||||
"version": "1.1.0",
|
||||
"type": "module",
|
||||
"dependencies": {
|
||||
"whatsapp-web.js": "^1.24.0",
|
||||
"qrcode-terminal": "^0.12.0"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
7
teste.js
Normal file
7
teste.js
Normal file
@@ -0,0 +1,7 @@
|
||||
const str = "<22>»⃟⃫⚡️⃥<EFB88F><E283A5><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>☆<EFBFBD>";
|
||||
|
||||
// percorre cada caractere
|
||||
for (const char of str) {
|
||||
const code = char.codePointAt(0); // pega o ponto de código Unicode
|
||||
process.stdout.write(`${char} (U+${code.toString(16).toUpperCase()})\n`);
|
||||
}
|
||||
BIN
yt-dlp.exe
Normal file
BIN
yt-dlp.exe
Normal file
Binary file not shown.
Reference in New Issue
Block a user