[repo] desacoplamento e maior coesão
This commit is contained in:
4
.gitignore
vendored
4
.gitignore
vendored
@@ -1,7 +1,7 @@
|
||||
env.js
|
||||
env
|
||||
.wwebjs_auth
|
||||
.wwebjs_cache
|
||||
downloads
|
||||
node_modules/
|
||||
src/node_modules/
|
||||
cookies.txt
|
||||
bin/
|
||||
44
deploy.sh
44
deploy.sh
@@ -1,4 +1,44 @@
|
||||
#!/bin/bash
|
||||
|
||||
TAG=$(git describe --tags --abbrev=0)
|
||||
npm version $TAG --no-git-tag-version
|
||||
# development tool
|
||||
# ./deploy <commit> <branch> <version (if branch=master)>
|
||||
|
||||
COMMIT_MSG="$1"
|
||||
BRANCH="$2"
|
||||
VERSION="$3"
|
||||
|
||||
if [ -z "$COMMIT_MSG" ] || [ -z "$BRANCH" ]; then
|
||||
echo "Uso: ./deploy <commit> <branch> [version if branch=master]"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "Rewriting config.js"
|
||||
cat > "src/config.js" << 'EOF'
|
||||
export const CLIENT_ID = "bot_permanente";
|
||||
export const BOT_PREFIX = "🤖 *ManyBot:* ";
|
||||
export const CHATS = [
|
||||
// coloque os chats que quer aqui
|
||||
];
|
||||
EOF
|
||||
|
||||
# mudar para a branch
|
||||
git checkout $BRANCH || { echo "Error ao change to $BRANCH"; exit 1; }
|
||||
|
||||
# adicionar alterações e commit
|
||||
git add .
|
||||
git commit -m "$COMMIT_MSG"
|
||||
|
||||
# push
|
||||
git push origin $BRANCH
|
||||
|
||||
# se for master, atualizar versão
|
||||
if [ "$BRANCH" == "master" ] && [ -n "$VERSION" ]; then
|
||||
echo "Updating version to $VERSION"
|
||||
git tag $VERSION
|
||||
npm version $VERSION --no-git-tag-version
|
||||
git add package.json
|
||||
git commit -m "Bump version to $VERSION"
|
||||
git push origin $VERSION
|
||||
fi
|
||||
|
||||
echo "Deploy completed."
|
||||
380
main.js
380
main.js
@@ -1,380 +0,0 @@
|
||||
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, spawn } from 'child_process';
|
||||
import sharp from 'sharp';
|
||||
import os from 'os';
|
||||
import path from "path";
|
||||
|
||||
console.log(os.platform());
|
||||
|
||||
import { CHATS } from "./env.js";
|
||||
|
||||
const CLIENT_ID = "bot_permanente";
|
||||
const BOT_PREFIX = "🤖 *ManyBot:* ";
|
||||
|
||||
let jogoAtivo = null;
|
||||
|
||||
if (!fs.existsSync("downloads")) fs.mkdirSync("downloads");
|
||||
|
||||
const client = new Client({
|
||||
authStrategy: new LocalAuth({ clientId: CLIENT_ID }),
|
||||
puppeteer: { headless: true }
|
||||
});
|
||||
|
||||
function botMsg(texto) {
|
||||
return `${BOT_PREFIX}\n${texto}`;
|
||||
}
|
||||
|
||||
function getChatId(chat) {
|
||||
return chat.id._serialized;
|
||||
}
|
||||
|
||||
// ---------------- Eventos ----------------
|
||||
|
||||
client.on("qr", qr => {
|
||||
console.log("[BOT] Escaneie o QR Code");
|
||||
qrcode.generate(qr, { small: true });
|
||||
});
|
||||
|
||||
client.on("ready", () => {
|
||||
exec("clear");
|
||||
console.log("[BOT] WhatsApp conectado.");
|
||||
});
|
||||
|
||||
client.on("disconnected", reason => {
|
||||
console.warn("[BOT] Reconectando:", reason);
|
||||
setTimeout(() => client.initialize(), 5000);
|
||||
});
|
||||
|
||||
client.on("message_create", async msg => {
|
||||
try {
|
||||
const chat = await msg.getChat();
|
||||
const chatId = getChatId(chat);
|
||||
|
||||
if (!CHATS.includes(chatId)) return;
|
||||
|
||||
console.log("==================================");
|
||||
console.log(`CHAT NAME : ${chat.name || chat.id.user}`);
|
||||
console.log(`CHAT ID : ${chatId}`);
|
||||
console.log(`FROM : ${msg.from}`);
|
||||
console.log(`BODY : ${msg.body}`);
|
||||
console.log("==================================\n");
|
||||
|
||||
await processarComando(msg, chat, chatId);
|
||||
await processarJogo(msg, chat);
|
||||
|
||||
} catch (err) {
|
||||
console.error("[ERRO]", err);
|
||||
}
|
||||
});
|
||||
|
||||
// ---------------- Download ----------------
|
||||
|
||||
let downloadQueue = [];
|
||||
let processingQueue = false;
|
||||
|
||||
function run(cmd, args) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const proc = spawn(cmd, args);
|
||||
|
||||
let stdout = "";
|
||||
|
||||
proc.stdout.on("data", data => {
|
||||
const text = data.toString();
|
||||
stdout += text;
|
||||
console.log("[cmd]", text);
|
||||
});
|
||||
|
||||
proc.stderr.on("data", data => {
|
||||
console.error("[cmd ERR]", data.toString());
|
||||
});
|
||||
|
||||
proc.on("close", code => {
|
||||
if (code !== 0) reject(new Error("Processo saiu com código " + code));
|
||||
else resolve(stdout);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
const so = os.platform();
|
||||
|
||||
async function get_video(url, id) {
|
||||
let cmd = "";
|
||||
const cmd_lin = "./bin/yt-dlp";
|
||||
const cmd_win = ".\\bin\\yt-dlp.exe";
|
||||
|
||||
switch (so) {
|
||||
case "win32":
|
||||
cmd = cmd_win;
|
||||
break;
|
||||
case "linux":
|
||||
cmd = cmd_lin;
|
||||
break;
|
||||
}
|
||||
|
||||
const args = [
|
||||
'--extractor-args', 'youtube:player_client=android', // mantém seu client preferido
|
||||
'-f', 'bv+ba/best', // tentar vídeo+áudio; fallback para best
|
||||
'--print', 'after_move:filepath',
|
||||
'--output', `downloads/${id}.%(ext)s`,
|
||||
|
||||
// autenticacao (use cookies exportado com yt-dlp ou --cookies-from-browser)
|
||||
'--cookies', 'cookies.txt', // arquivo de cookies (gerar antes)
|
||||
// cabeçalhos para reduzir 403
|
||||
'--add-header', 'User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64)',
|
||||
'--add-header', 'Referer:https://www.youtube.com/',
|
||||
// tolerância de rede
|
||||
'--retries', '4',
|
||||
'--fragment-retries', '5',
|
||||
'--socket-timeout', '15',
|
||||
'--sleep-interval', '1', '--max-sleep-interval', '4',
|
||||
// permitir formatos que podem ser marcados como "unplayable" (útil em alguns casos)
|
||||
'--allow-unplayable-formats',
|
||||
// testes / debug: use -v quando precisar diagnosticar
|
||||
// url
|
||||
url
|
||||
];
|
||||
|
||||
const stdout = await run(cmd, args);
|
||||
const filepath = stdout.trim();
|
||||
if (!filepath) throw new Error("yt-dlp não retornou caminho");
|
||||
|
||||
return filepath;
|
||||
}
|
||||
|
||||
async function get_audio(url, id) {
|
||||
const video = await get_video(url, id);
|
||||
const output = `downloads/${id}.mp3`;
|
||||
|
||||
let cmd = "";
|
||||
const cmd_lin = "./bin/ffmpeg";
|
||||
const cmd_win = ".\\bin\\ffmpeg.exe";
|
||||
|
||||
switch (so) {
|
||||
case "win32":
|
||||
cmd = cmd_win;
|
||||
break;
|
||||
case "linux":
|
||||
cmd = cmd_lin;
|
||||
break;
|
||||
}
|
||||
|
||||
const args = [
|
||||
'-i', video,
|
||||
'-vn', '-acodec',
|
||||
'libmp3lame', '-q:a', '2',
|
||||
output
|
||||
];
|
||||
|
||||
await run(cmd, args);
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
function empty_folder(folder) {
|
||||
fs.readdirSync(folder).forEach(file => {
|
||||
const filePath = path.join(folder, file);
|
||||
if (fs.lstatSync(filePath).isFile()) {
|
||||
fs.unlinkSync(filePath);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async function enviarVideo(chatId, path) {
|
||||
const file = fs.readFileSync(path);
|
||||
const media = new MessageMedia(
|
||||
"video/mp4",
|
||||
file.toString("base64"),
|
||||
path.split("/").pop()
|
||||
);
|
||||
await client.sendMessage(chatId, media);
|
||||
fs.unlinkSync(path);
|
||||
empty_folder("./downloads");
|
||||
}
|
||||
|
||||
async function enviarAudio(chatId, path) {
|
||||
const file = fs.readFileSync(path);
|
||||
const media = new MessageMedia(
|
||||
"audio/mpeg",
|
||||
file.toString("base64"),
|
||||
path.split("/").pop()
|
||||
);
|
||||
await client.sendMessage(chatId, media);
|
||||
fs.unlinkSync(path);
|
||||
empty_folder("./downloads");
|
||||
}
|
||||
|
||||
function enqueueDownload(type, url, msg, chatId) {
|
||||
downloadQueue.push({ type, url, msg, chatId });
|
||||
if (!processingQueue) processQueue();
|
||||
}
|
||||
|
||||
async function processQueue() {
|
||||
processingQueue = true;
|
||||
while (downloadQueue.length) {
|
||||
const job = downloadQueue.shift();
|
||||
try {
|
||||
let path;
|
||||
if (job.type === "video")
|
||||
path = await get_video(job.url, job.msg.id._serialized);
|
||||
else
|
||||
path = await get_audio(job.url, job.msg.id._serialized);
|
||||
|
||||
if (job.type === "video")
|
||||
await enviarVideo(job.chatId, path);
|
||||
else
|
||||
await enviarAudio(job.chatId, path);
|
||||
|
||||
} catch (err) {
|
||||
await client.sendMessage(
|
||||
job.chatId,
|
||||
botMsg(`❌ Erro ao baixar ${job.type}\n\`${err.message}\``)
|
||||
);
|
||||
}
|
||||
}
|
||||
processingQueue = false;
|
||||
}
|
||||
|
||||
// ---------------- Figurinha ----------------
|
||||
|
||||
async function gerarSticker(msg) {
|
||||
if (!msg.hasMedia) {
|
||||
await msg.reply(botMsg("Envie uma imagem junto com o comando: `!figurinha`."));
|
||||
return;
|
||||
}
|
||||
|
||||
const media = await msg.downloadMedia();
|
||||
const ext = media.mimetype.split("/")[1];
|
||||
|
||||
const input = `downloads/${msg.id._serialized}.${ext}`;
|
||||
const output = `downloads/${msg.id._serialized}.webp`;
|
||||
|
||||
fs.writeFileSync(input, Buffer.from(media.data, "base64"));
|
||||
|
||||
await sharp(input)
|
||||
.resize(512, 512, { fit: "contain", background: { r:0,g:0,b:0,alpha:0 } })
|
||||
.webp()
|
||||
.toFile(output);
|
||||
|
||||
const data = fs.readFileSync(output);
|
||||
const sticker = new MessageMedia("image/webp", data.toString("base64"), "sticker.webp");
|
||||
const chat = await msg.getChat();
|
||||
|
||||
await client.sendMessage(chat.id._serialized, sticker, { sendMediaAsSticker: true });
|
||||
|
||||
fs.unlinkSync(input);
|
||||
fs.unlinkSync(output);
|
||||
}
|
||||
|
||||
// ---------------- Comandos ----------------
|
||||
|
||||
async function processarComando(msg, chat, chatId) {
|
||||
const tokens = msg.body.trim().split(/\s+/);
|
||||
try {
|
||||
switch(tokens[0]) {
|
||||
case "!many":
|
||||
await chat.sendMessage(botMsg(
|
||||
"Comandos:\n\n"+
|
||||
"`!ping`\n"+
|
||||
"`!video <link>`\n"+
|
||||
"`!audio <link>`\n"+
|
||||
"`!figurinha`\n"+
|
||||
"`!adivinhação começar|parar`\n"+
|
||||
"`!info <comando>`"
|
||||
));
|
||||
break;
|
||||
|
||||
case "!ping":
|
||||
await msg.reply(botMsg("pong 🏓"));
|
||||
break;
|
||||
|
||||
case "!video":
|
||||
if (!tokens[1]) return;
|
||||
await msg.reply(botMsg("⏳ Baixando vídeo..."));
|
||||
enqueueDownload("video", tokens[1], msg, chatId);
|
||||
break;
|
||||
|
||||
case "!audio":
|
||||
if (!tokens[1]) return;
|
||||
await msg.reply(botMsg("⏳ Baixando áudio..."));
|
||||
enqueueDownload("audio", tokens[1], msg, chatId);
|
||||
break;
|
||||
|
||||
case "!figurinha":
|
||||
await gerarSticker(msg);
|
||||
break;
|
||||
|
||||
case "!adivinhação":
|
||||
if (!tokens[1]) {
|
||||
await chat.sendMessage(botMsg("`!adivinhação começar`\n`!adivinhação parar`"));
|
||||
return;
|
||||
}
|
||||
if (tokens[1] === "começar") {
|
||||
jogoAtivo = Math.floor(Math.random()*100)+1;
|
||||
await chat.sendMessage(botMsg("Adivinhe o número de 1 a 100!"));
|
||||
}
|
||||
if (tokens[1] === "parar") {
|
||||
jogoAtivo = null;
|
||||
await chat.sendMessage(botMsg("Jogo encerrado."));
|
||||
}
|
||||
break;
|
||||
|
||||
case "A":
|
||||
case "a":
|
||||
if (!tokens[1]) await msg.reply(botMsg("B!"));
|
||||
break;
|
||||
|
||||
case "!info":
|
||||
if (!tokens[1]) {
|
||||
await chat.sendMessage(botMsg("Use:\n`!info <comando>`"));
|
||||
return;
|
||||
}
|
||||
switch(tokens[1]) {
|
||||
case "ping":
|
||||
await chat.sendMessage(botMsg("> `!ping`\nResponde pong."));
|
||||
break;
|
||||
case "video":
|
||||
await chat.sendMessage(botMsg("> `!video <link>`\nBaixa vídeo da internet."));
|
||||
break;
|
||||
case "audio":
|
||||
await chat.sendMessage(botMsg("> `!audio <link>`\nBaixa áudio da internet."));
|
||||
break;
|
||||
case "figurinha":
|
||||
await chat.sendMessage(botMsg("`!figurinha`\nTransforma imagem/GIF em sticker."));
|
||||
break;
|
||||
default:
|
||||
await chat.sendMessage(botMsg(`❌ Comando '${tokens[1]}' não encontrado.`));
|
||||
}
|
||||
break;
|
||||
}
|
||||
} catch(err) {
|
||||
console.error(err);
|
||||
await chat.sendMessage(botMsg("Erro:\n`"+err.message+"`"));
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------- Jogo ----------------
|
||||
|
||||
async function processarJogo(msg, chat) {
|
||||
if (!jogoAtivo) return;
|
||||
|
||||
const tentativa = msg.body.trim();
|
||||
if (!/^\d+$/.test(tentativa)) return;
|
||||
|
||||
const num = parseInt(tentativa);
|
||||
if (num === jogoAtivo) {
|
||||
await msg.reply(botMsg(`Acertou! Número: ${jogoAtivo}`));
|
||||
jogoAtivo = null;
|
||||
} else if (num > jogoAtivo) {
|
||||
await chat.sendMessage(botMsg("Menor."));
|
||||
} else {
|
||||
await chat.sendMessage(botMsg("Maior."));
|
||||
}
|
||||
}
|
||||
|
||||
client.initialize();
|
||||
4
package-lock.json
generated
4
package-lock.json
generated
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "whatsapp-bot",
|
||||
"version": "1.1.0",
|
||||
"version": "2.0.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "whatsapp-bot",
|
||||
"version": "1.1.0",
|
||||
"version": "2.0.0",
|
||||
"dependencies": {
|
||||
"qrcode-terminal": "^0.12.0",
|
||||
"sharp": "^0.34.5",
|
||||
|
||||
64
setup
Normal file
64
setup
Normal file
@@ -0,0 +1,64 @@
|
||||
import { exec } from "child_process";
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
import https from "https";
|
||||
import http from "http";
|
||||
|
||||
// Função para rodar comandos de shell
|
||||
function runCmd(cmd) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const p = exec(cmd, (err, stdout, stderr) => {
|
||||
if (err) return reject(err);
|
||||
resolve({ stdout, stderr });
|
||||
});
|
||||
p.stdout.pipe(process.stdout);
|
||||
p.stderr.pipe(process.stderr);
|
||||
});
|
||||
}
|
||||
|
||||
// Função para baixar arquivo
|
||||
function downloadFile(url, dest) {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (fs.existsSync(dest)) {
|
||||
console.log(`${dest} já existe, pulando download.`);
|
||||
return resolve();
|
||||
}
|
||||
|
||||
console.log(`Baixando ${url} → ${dest}`);
|
||||
const file = fs.createWriteStream(dest);
|
||||
const client = url.startsWith("https") ? https : http;
|
||||
|
||||
client.get(url, (res) => {
|
||||
if (res.statusCode >= 400) return reject(new Error(`Erro ao baixar ${url}: ${res.statusCode}`));
|
||||
res.pipe(file);
|
||||
file.on("finish", () => file.close(resolve));
|
||||
}).on("error", (err) => {
|
||||
fs.unlink(dest, () => reject(err));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function main() {
|
||||
// setup do npm
|
||||
await runCmd("npm ci");
|
||||
|
||||
// cria pasta para binários
|
||||
const binDir = path.resolve("bin");
|
||||
if (!fs.existsSync(binDir)) fs.mkdirSync(binDir, { recursive: true });
|
||||
|
||||
// downloads
|
||||
const files = [
|
||||
["https://github.com/synt-xerror/manybot/releases/download/dependencies/yt-dlp.exe", "yt-dlp.exe"],
|
||||
["https://github.com/synt-xerror/manybot/releases/download/dependencies/yt-dlp.exe", "yt-dlp"],
|
||||
["https://github.com/synt-xerror/manybot/releases/download/dependencies/yt-dlp.exe", "ffmpeg.exe"],
|
||||
["https://github.com/synt-xerror/manybot/releases/download/dependencies/yt-dlp.exe", "ffmpeg"]
|
||||
];
|
||||
|
||||
for (const [url, name] of files) {
|
||||
await downloadFile(url, path.join(binDir, name));
|
||||
}
|
||||
|
||||
console.log("Setup concluído.");
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
28
src/client/whatsappClient.js
Normal file
28
src/client/whatsappClient.js
Normal file
@@ -0,0 +1,28 @@
|
||||
import pkg from "whatsapp-web.js";
|
||||
import qrcode from "qrcode-terminal";
|
||||
import { exec } from "child_process";
|
||||
import { CLIENT_ID } from "../config.js";
|
||||
|
||||
export const { Client, LocalAuth, MessageMedia } = pkg;
|
||||
|
||||
export const client = new Client({
|
||||
authStrategy: new LocalAuth({ clientId: CLIENT_ID }),
|
||||
puppeteer: { headless: true }
|
||||
});
|
||||
|
||||
client.on("qr", qr => {
|
||||
console.log("[BOT] Escaneie o QR Code");
|
||||
qrcode.generate(qr, { small: true });
|
||||
});
|
||||
|
||||
client.on("ready", () => {
|
||||
exec("clear");
|
||||
console.log("[BOT] WhatsApp conectado.");
|
||||
});
|
||||
|
||||
client.on("disconnected", reason => {
|
||||
console.warn("[BOT] Reconectando:", reason);
|
||||
setTimeout(() => client.initialize(), 5000);
|
||||
});
|
||||
|
||||
export default client;
|
||||
33
src/commands/figurinha.js
Normal file
33
src/commands/figurinha.js
Normal file
@@ -0,0 +1,33 @@
|
||||
import pkg from "whatsapp-web.js";
|
||||
const { MessageMedia } = pkg;
|
||||
import sharp from "sharp";
|
||||
import fs from "fs";
|
||||
import { botMsg } from "../utils/botMsg.js";
|
||||
import { client } from "../client/whatsappClient.js"
|
||||
|
||||
export async function gerarSticker(msg) {
|
||||
if (!msg.hasMedia) {
|
||||
await msg.reply(botMsg("Envie uma imagem junto com o comando: `!figurinha`."));
|
||||
return;
|
||||
}
|
||||
|
||||
const media = await msg.downloadMedia();
|
||||
const ext = media.mimetype.split("/")[1];
|
||||
const input = `downloads/${msg.id._serialized}.${ext}`;
|
||||
const output = `downloads/${msg.id._serialized}.webp`;
|
||||
|
||||
fs.writeFileSync(input, Buffer.from(media.data, "base64"));
|
||||
|
||||
await sharp(input)
|
||||
.resize(512, 512, { fit: "contain", background: { r:0,g:0,b:0,alpha:0 } })
|
||||
.webp()
|
||||
.toFile(output);
|
||||
|
||||
const data = fs.readFileSync(output);
|
||||
const sticker = new MessageMedia("image/webp", data.toString("base64"), "sticker.webp");
|
||||
const chat = await msg.getChat();
|
||||
await client.sendMessage(chat.id._serialized, sticker, { sendMediaAsSticker: true });
|
||||
|
||||
fs.unlinkSync(input);
|
||||
fs.unlinkSync(output);
|
||||
}
|
||||
71
src/commands/index.js
Normal file
71
src/commands/index.js
Normal file
@@ -0,0 +1,71 @@
|
||||
import { enqueueDownload } from "../download/queue.js";
|
||||
import { gerarSticker } from "./figurinha.js";
|
||||
import { botMsg } from "../utils/botMsg.js";
|
||||
import { iniciarJogo, pararJogo, processarJogo } from "../games/adivinhacao.js";
|
||||
import { processarInfo } from "./info.js";
|
||||
|
||||
export async function processarComando(msg, chat, chatId) {
|
||||
const tokens = msg.body.trim().split(/\s+/);
|
||||
try {
|
||||
switch(tokens[0]) {
|
||||
case "!many":
|
||||
await chat.sendMessage(botMsg(
|
||||
"Comandos:\n\n"+
|
||||
"- `!ping`\n"+
|
||||
"- `!video <link>`\n"+
|
||||
"- `!audio <link>`\n"+
|
||||
"- `!figurinha`\n"+
|
||||
"- `!adivinhação começar|parar`\n"+
|
||||
"- `!info <comando>`"
|
||||
));
|
||||
break;
|
||||
|
||||
case "!ping":
|
||||
await msg.reply(botMsg("pong 🏓"));
|
||||
break;
|
||||
|
||||
case "!video":
|
||||
if (!tokens[1]) return;
|
||||
await msg.reply(botMsg("⏳ Baixando vídeo..."));
|
||||
enqueueDownload("video", tokens[1], msg, chatId);
|
||||
break;
|
||||
|
||||
case "!audio":
|
||||
if (!tokens[1]) return;
|
||||
await msg.reply(botMsg("⏳ Baixando áudio..."));
|
||||
enqueueDownload("audio", tokens[1], msg, chatId);
|
||||
break;
|
||||
|
||||
case "!figurinha":
|
||||
await gerarSticker(msg);
|
||||
break;
|
||||
|
||||
case "!adivinhação":
|
||||
if (!tokens[1]) {
|
||||
await chat.sendMessage(botMsg("`!adivinhação começar`\n`!adivinhação parar`"));
|
||||
return;
|
||||
}
|
||||
if (tokens[1] === "começar") {
|
||||
iniciarJogo();
|
||||
await chat.sendMessage(botMsg("Jogo iniciado! Tente adivinhar o número de 1 a 100."));
|
||||
}
|
||||
if (tokens[1] === "parar") {
|
||||
pararJogo();
|
||||
await chat.sendMessage(botMsg("Jogo parado."));
|
||||
}
|
||||
break;
|
||||
|
||||
case "!info":
|
||||
if (!tokens[1]) {
|
||||
await chat.sendMessage(botMsg("Use:\n`!info <comando>`"));
|
||||
return;
|
||||
} else {
|
||||
processarInfo(tokens[1], chat);
|
||||
}
|
||||
break;
|
||||
}
|
||||
} catch(err) {
|
||||
console.error(err);
|
||||
await chat.sendMessage(botMsg("Erro:\n`"+err.message+"`"));
|
||||
}
|
||||
}
|
||||
20
src/commands/info.js
Normal file
20
src/commands/info.js
Normal file
@@ -0,0 +1,20 @@
|
||||
import { botMsg } from "../utils/botMsg.js";
|
||||
|
||||
export async function processarInfo(cmd, chat) {
|
||||
switch(cmd) {
|
||||
case "ping":
|
||||
await chat.sendMessage(botMsg("> `!ping`\nResponde pong."));
|
||||
break;
|
||||
case "video":
|
||||
await chat.sendMessage(botMsg("> `!video <link>`\nBaixa vídeo da internet."));
|
||||
break;
|
||||
case "audio":
|
||||
await chat.sendMessage(botMsg("> `!audio <link>`\nBaixa áudio da internet."));
|
||||
break;
|
||||
case "figurinha":
|
||||
await chat.sendMessage(botMsg("`!figurinha`\nTransforma imagem/GIF em sticker."));
|
||||
break;
|
||||
default:
|
||||
await chat.sendMessage(botMsg(`❌ Comando '${tokens[1]}' não encontrado.`));
|
||||
}
|
||||
}
|
||||
24
src/download/audio.js
Normal file
24
src/download/audio.js
Normal file
@@ -0,0 +1,24 @@
|
||||
import { get_video } from "./video.js";
|
||||
import { spawn } from "child_process";
|
||||
import os from "os";
|
||||
|
||||
const so = os.platform();
|
||||
|
||||
export async function get_audio(url, id) {
|
||||
const video = await get_video(url, id);
|
||||
const output = `downloads/${id}.mp3`;
|
||||
const cmd = so === "win32" ? ".\\bin\\ffmpeg.exe" : "./bin/ffmpeg";
|
||||
const args = ['-i', video, '-vn', '-acodec', 'libmp3lame', '-q:a', '2', output];
|
||||
|
||||
await runCmd(cmd, args);
|
||||
return output;
|
||||
}
|
||||
|
||||
async function runCmd(cmd, args) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const proc = spawn(cmd, args);
|
||||
proc.stdout.on("data", data => console.log("[cmd]", data.toString()));
|
||||
proc.stderr.on("data", data => console.error("[cmd ERR]", data.toString()));
|
||||
proc.on("close", code => code === 0 ? resolve() : reject(new Error("Processo saiu com código "+code)));
|
||||
});
|
||||
}
|
||||
42
src/download/queue.js
Normal file
42
src/download/queue.js
Normal file
@@ -0,0 +1,42 @@
|
||||
import { get_video } from "./video.js";
|
||||
import { get_audio } from "./audio.js";
|
||||
import pkg from "whatsapp-web.js";
|
||||
const { MessageMedia } = pkg;
|
||||
import fs from "fs";
|
||||
import { botMsg } from "../utils/botMsg.js";
|
||||
import { emptyFolder } from "../utils/file.js";
|
||||
import client from "../client/whatsappClient.js";
|
||||
|
||||
let downloadQueue = [];
|
||||
let processingQueue = false;
|
||||
|
||||
export function enqueueDownload(type, url, msg, chatId) {
|
||||
downloadQueue.push({ type, url, msg, chatId });
|
||||
if (!processingQueue) processQueue();
|
||||
}
|
||||
|
||||
async function processQueue() {
|
||||
processingQueue = true;
|
||||
while (downloadQueue.length) {
|
||||
const job = downloadQueue.shift();
|
||||
try {
|
||||
let path;
|
||||
if (job.type === "video") path = await get_video(job.url, job.msg.id._serialized);
|
||||
else path = await get_audio(job.url, job.msg.id._serialized);
|
||||
|
||||
const file = fs.readFileSync(path);
|
||||
const media = new MessageMedia(
|
||||
job.type === "video" ? "video/mp4" : "audio/mpeg",
|
||||
file.toString("base64"),
|
||||
path.split("/").pop()
|
||||
);
|
||||
await client.sendMessage(job.chatId, media);
|
||||
fs.unlinkSync(path);
|
||||
emptyFolder("downloads");
|
||||
|
||||
} catch (err) {
|
||||
await client.sendMessage(job.chatId, botMsg(`❌ Erro ao baixar ${job.type}\n\`${err.message}\``));
|
||||
}
|
||||
}
|
||||
processingQueue = false;
|
||||
}
|
||||
36
src/download/video.js
Normal file
36
src/download/video.js
Normal file
@@ -0,0 +1,36 @@
|
||||
import { spawn } from "child_process";
|
||||
import os from "os";
|
||||
|
||||
const so = os.platform();
|
||||
|
||||
export async function get_video(url, id) {
|
||||
const cmd = so === "win32" ? ".\\bin\\yt-dlp.exe" : "./bin/yt-dlp";
|
||||
const args = [
|
||||
'--extractor-args', 'youtube:player_client=android',
|
||||
'-f', 'bv+ba/best',
|
||||
'--print', 'after_move:filepath',
|
||||
'--output', `downloads/${id}.%(ext)s`,
|
||||
'--cookies', 'cookies.txt',
|
||||
'--add-header', 'User-Agent:Mozilla/5.0',
|
||||
'--add-header', 'Referer:https://www.youtube.com/',
|
||||
'--retries', '4',
|
||||
'--fragment-retries', '5',
|
||||
'--socket-timeout', '15',
|
||||
'--sleep-interval', '1', '--max-sleep-interval', '4',
|
||||
'--allow-unplayable-formats',
|
||||
url
|
||||
];
|
||||
|
||||
return await runCmd(cmd, args);
|
||||
}
|
||||
|
||||
async function runCmd(cmd, args) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const proc = spawn(cmd, args);
|
||||
let stdout = "";
|
||||
|
||||
proc.stdout.on("data", data => stdout += data.toString());
|
||||
proc.stderr.on("data", data => console.error("[cmd ERR]", data.toString()));
|
||||
proc.on("close", code => code === 0 ? resolve(stdout.trim()) : reject(new Error("Processo saiu com código "+code)));
|
||||
});
|
||||
}
|
||||
29
src/games/adivinhacao.js
Normal file
29
src/games/adivinhacao.js
Normal file
@@ -0,0 +1,29 @@
|
||||
import { botMsg } from "../utils/botMsg.js";
|
||||
|
||||
let jogoAtivo = null;
|
||||
|
||||
export function iniciarJogo() {
|
||||
jogoAtivo = Math.floor(Math.random()*100)+1;
|
||||
return jogoAtivo;
|
||||
}
|
||||
|
||||
export function pararJogo() {
|
||||
jogoAtivo = null;
|
||||
}
|
||||
|
||||
export async function processarJogo(msg, chat) {
|
||||
if (!jogoAtivo) return;
|
||||
|
||||
const tentativa = msg.body.trim();
|
||||
if (!/^\d+$/.test(tentativa)) return;
|
||||
|
||||
const num = parseInt(tentativa);
|
||||
if (num === jogoAtivo) {
|
||||
await msg.reply(botMsg(`Acertou! Número: ${jogoAtivo}`));
|
||||
pararJogo();
|
||||
} else if (num > jogoAtivo) {
|
||||
await chat.sendMessage(botMsg("Menor."));
|
||||
} else {
|
||||
await chat.sendMessage(botMsg("Maior."));
|
||||
}
|
||||
}
|
||||
29
src/main.js
Normal file
29
src/main.js
Normal file
@@ -0,0 +1,29 @@
|
||||
console.log("Iniciando...");
|
||||
|
||||
import client from "./client/whatsappClient.js";
|
||||
import { CHATS } from "./config.js";
|
||||
import { processarComando } from "./commands/index.js";
|
||||
import { processarJogo } from "./games/adivinhacao.js";
|
||||
import { getChatId } from "./utils/getChatId.js";
|
||||
|
||||
client.on("message_create", async msg => {
|
||||
try {
|
||||
const chat = await msg.getChat();
|
||||
const chatId = getChatId(chat);
|
||||
if (!CHATS.includes(chatId)) return;
|
||||
|
||||
console.log("==================================");
|
||||
console.log(`CHAT NAME : ${chat.name || chat.id.user}`);
|
||||
console.log(`CHAT ID : ${chatId}`);
|
||||
console.log(`FROM : ${msg.from}`);
|
||||
console.log(`BODY : ${msg.body}`);
|
||||
console.log("==================================\n");
|
||||
|
||||
await processarComando(msg, chat, chatId);
|
||||
await processarJogo(msg, chat);
|
||||
} catch(err) {
|
||||
console.error("[ERRO]", err);
|
||||
}
|
||||
});
|
||||
|
||||
client.initialize();
|
||||
5
src/utils/botMsg.js
Normal file
5
src/utils/botMsg.js
Normal file
@@ -0,0 +1,5 @@
|
||||
import { BOT_PREFIX } from "../config.js";
|
||||
|
||||
export function botMsg(texto) {
|
||||
return `${BOT_PREFIX}\n${texto}`;
|
||||
}
|
||||
9
src/utils/file.js
Normal file
9
src/utils/file.js
Normal file
@@ -0,0 +1,9 @@
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
|
||||
export function emptyFolder(folder) {
|
||||
fs.readdirSync(folder).forEach(file => {
|
||||
const filePath = path.join(folder, file);
|
||||
if (fs.lstatSync(filePath).isFile()) fs.unlinkSync(filePath);
|
||||
});
|
||||
}
|
||||
3
src/utils/getChatId.js
Normal file
3
src/utils/getChatId.js
Normal file
@@ -0,0 +1,3 @@
|
||||
export function getChatId(chat) {
|
||||
return chat.id._serialized;
|
||||
}
|
||||
7
teste.js
7
teste.js
@@ -1,7 +0,0 @@
|
||||
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`);
|
||||
}
|
||||
Reference in New Issue
Block a user