a
This commit is contained in:
1
.gitignore
vendored
1
.gitignore
vendored
@@ -2,3 +2,4 @@ env.js
|
|||||||
.wwebjs_auth
|
.wwebjs_auth
|
||||||
.wwebjs_cache
|
.wwebjs_cache
|
||||||
downloads
|
downloads
|
||||||
|
node_modules/
|
||||||
12
README.md
12
README.md
@@ -1,2 +1,10 @@
|
|||||||
# manybot
|
# ManyBot!
|
||||||
Cool whatsapp bot. Local and free.
|
|
||||||
|
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';
|
import pkg from 'whatsapp-web.js';
|
||||||
const { Client, LocalAuth } = pkg;
|
const { Client, LocalAuth } = pkg;
|
||||||
import qrcode from 'qrcode-terminal';
|
import qrcode from 'qrcode-terminal';
|
||||||
@@ -15,22 +24,37 @@ client.on('qr', qr => {
|
|||||||
qrcode.generate(qr, { small: true });
|
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 => {
|
client.on('ready', async () => {
|
||||||
try {
|
const chats = await client.getChats();
|
||||||
const chat = await msg.getChat(); // pega o chat uma única vez
|
|
||||||
|
|
||||||
console.log("==================================");
|
let filtered = [];
|
||||||
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");
|
|
||||||
|
|
||||||
} catch (err) {
|
if (arg.toLowerCase() === "grupos") {
|
||||||
console.error("[ERRO]", err);
|
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();
|
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';
|
import pkg from 'whatsapp-web.js';
|
||||||
const { Client, LocalAuth, MessageMedia } = pkg;
|
const { Client, LocalAuth, MessageMedia } = pkg;
|
||||||
|
|
||||||
import qrcode from 'qrcode-terminal';
|
import qrcode from 'qrcode-terminal';
|
||||||
import fs from 'fs';
|
import fs from 'fs';
|
||||||
|
import { exec } from 'child_process';
|
||||||
|
|
||||||
const CHAT_ID_ALVO = process.argv[2];
|
const CLIENT_ID = "bot_permanente"; // sessão única global
|
||||||
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 BOT_PREFIX = "🤖 *ManyBot:* ";
|
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({
|
const client = new Client({
|
||||||
authStrategy: new LocalAuth({ clientId: CLIENT_ID }),
|
authStrategy: new LocalAuth({ clientId: CLIENT_ID }),
|
||||||
puppeteer: {
|
puppeteer: { headless: true }
|
||||||
headless: true,
|
|
||||||
args: ['--no-sandbox', '--disable-setuid-sandbox'],
|
|
||||||
timeout: 60000,
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
|
|
||||||
client.on('qr', qr => {
|
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 });
|
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 => {
|
client.on('disconnected', reason => {
|
||||||
console.warn(`[${CHAT_ID_ALVO}] Desconectado: ${reason}. Tentando reconectar...`);
|
console.warn(`[BOT] Desconectado: ${reason}. Tentando reconectar...`);
|
||||||
setTimeout(() => client.initialize(), 5000);
|
setTimeout(() => client.initialize(), 5000);
|
||||||
});
|
});
|
||||||
|
|
||||||
client.on('message_create', async msg => {
|
client.on('message_create', async msg => {
|
||||||
try {
|
try {
|
||||||
const chat = await msg.getChat();
|
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("==================================");
|
||||||
console.log(`CHAT NAME : ${chat.name || chat.id.user || "Sem nome"}`);
|
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 ----------------
|
// ---------------- Funções de envio ----------------
|
||||||
|
|
||||||
async function enviarVideo(cliente, chatId, caminhoArquivo) {
|
async function enviarVideo(cliente, chatId, caminhoArquivo) {
|
||||||
@@ -88,7 +99,6 @@ function iniciarJogo(chat) {
|
|||||||
jogoAtivo = numeroSecreto;
|
jogoAtivo = numeroSecreto;
|
||||||
|
|
||||||
console.log(`[JOGO] ${chat.name}: Número escolhido ${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 ----------------
|
// ---------------- Download ----------------
|
||||||
@@ -101,45 +111,64 @@ let processingQueue = false;
|
|||||||
// Garantir que a pasta downloads exista
|
// Garantir que a pasta downloads exista
|
||||||
if (!fs.existsSync('downloads')) fs.mkdirSync('downloads');
|
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) {
|
function get_video(url, id) {
|
||||||
downloadsAtivos++;
|
downloadsAtivos++;
|
||||||
|
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise(async (resolve, reject) => {
|
||||||
const cmd = `yt-dlp -t mp4 --print after_move:filepath -o "downloads/${id}.%(ext)s" "${url}"`;
|
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--;
|
downloadsAtivos--;
|
||||||
|
|
||||||
if (stderr) console.error(stderr);
|
if (stderr) console.error(stderr);
|
||||||
if (error) return reject(new Error(`yt-dlp falhou: ${error.message}`));
|
|
||||||
|
|
||||||
const filepath = stdout.trim();
|
const filepath = stdout.trim();
|
||||||
if (!filepath) return reject(new Error("yt-dlp não retornou filepath"));
|
if (!filepath) return reject(new Error("yt-dlp não retornou filepath"));
|
||||||
|
|
||||||
resolve(filepath);
|
resolve(filepath);
|
||||||
});
|
} catch (err) {
|
||||||
|
downloadsAtivos--;
|
||||||
|
reject(new Error(`yt-dlp falhou: ${err.message}`));
|
||||||
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
function get_audio(url, id) {
|
function get_audio(url, id) {
|
||||||
downloadsAtivos++;
|
downloadsAtivos++;
|
||||||
|
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise(async (resolve, reject) => {
|
||||||
const cmd = `yt-dlp -t mp3 --print after_move:filepath -o "downloads/${id}.%(ext)s" "${url}"`;
|
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--;
|
downloadsAtivos--;
|
||||||
|
|
||||||
if (stderr) console.error(stderr);
|
if (stderr) console.error(stderr);
|
||||||
if (error) return reject(new Error(`yt-dlp falhou: ${error.message}`));
|
|
||||||
|
|
||||||
const filepath = stdout.trim();
|
const filepath = stdout.trim();
|
||||||
if (!filepath) return reject(new Error("yt-dlp não retornou filepath"));
|
if (!filepath) return reject(new Error("yt-dlp não retornou filepath"));
|
||||||
|
|
||||||
resolve(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) {
|
if (tokens.length === 1) {
|
||||||
chat.sendMessage(botMsg(
|
chat.sendMessage(botMsg(
|
||||||
"- `!many ping` -> testa se estou funcionando\n" +
|
"- `!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 video <link>` -> baixo um vídeo da internet para você!\n" +
|
||||||
"- `!many audio <link>` -> baixo um audio da internet para você!"
|
"- `!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] === "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]) {
|
if (tokens[1] === "video" && tokens[2]) {
|
||||||
chat.sendMessage(botMsg("⏳ Baixando vídeo, aguarde..."));
|
chat.sendMessage(botMsg("⏳ Baixando vídeo, aguarde..."));
|
||||||
|
|||||||
6
package-lock.json
generated
6
package-lock.json
generated
@@ -7,7 +7,8 @@
|
|||||||
"dependencies": {
|
"dependencies": {
|
||||||
"qrcode-terminal": "^0.12.0",
|
"qrcode-terminal": "^0.12.0",
|
||||||
"whatsapp-web.js": "^1.34.6"
|
"whatsapp-web.js": "^1.34.6"
|
||||||
}
|
},
|
||||||
|
"version": "1.1.0"
|
||||||
},
|
},
|
||||||
"node_modules/@babel/code-frame": {
|
"node_modules/@babel/code-frame": {
|
||||||
"version": "7.29.0",
|
"version": "7.29.0",
|
||||||
@@ -2098,5 +2099,6 @@
|
|||||||
"url": "https://github.com/sponsors/colinhacks"
|
"url": "https://github.com/sponsors/colinhacks"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
},
|
||||||
|
"version": "1.1.0"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "whatsapp-bot",
|
"name": "whatsapp-bot",
|
||||||
"version": "1.0.0",
|
"version": "1.1.0",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"whatsapp-web.js": "^1.24.0",
|
"whatsapp-web.js": "^1.24.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