Skip to content

Commit

Permalink
Plugins Extra
Browse files Browse the repository at this point in the history
Plugin que Agrega audio y video al detector de palabras con .addaudio 
Plugin que muestra info del sistema con .sysinfo
  • Loading branch information
weskerty authored Oct 27, 2024
1 parent 8633bed commit 90d409f
Show file tree
Hide file tree
Showing 2 changed files with 253 additions and 0 deletions.
142 changes: 142 additions & 0 deletions plugins/SYS.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
// MR. De la Comunidad para la Comunidad. Prohibida su Venta.
// El Software se proporciona bajo los tΓ©rminos de la Licencia MIT, excepto que usted no puede:
// 1. Vender, revender o arrendar el Software.
// 2. Cobrar a otros por el acceso, la distribuciΓ³n o cualquier otro uso comercial del Software.
// 3. Usar el Software como parte de un producto comercial o una oferta de servicio.

import os from 'os';
import { exec } from 'child_process';

function formatUptime(uptime) {
const seconds = Math.floor(uptime % 60);
const minutes = Math.floor((uptime / 60) % 60);
const hours = Math.floor((uptime / 3600) % 24);
return `${hours} horas, ${minutes} minutos, ${seconds} segundos`;
}

function getVersions(callback) {
exec('node -v', (err, nodeVersion) => {
if (err) nodeVersion = 'βœ–οΈ';
exec('npm -v', (err, npmVersion) => {
if (err) npmVersion = 'βœ–οΈ';
exec('ffmpeg -version', (err, ffmpegVersion) => {
if (err) ffmpegVersion = 'βœ–οΈ';
exec('python --version || python3 --version || py --version', (err, pythonVersion) => {
if (err) pythonVersion = 'βœ–οΈ';
exec('pip --version || pip3 --version', (err, pipVersion) => {
if (err) pipVersion = 'βœ–οΈ';
exec('choco -v', (err, chocoVersion) => {
if (err) chocoVersion = 'βœ–οΈ';
callback({ nodeVersion, npmVersion, ffmpegVersion, pythonVersion, pipVersion, chocoVersion });
});
});
});
});
});
});
}

function getStorageInfo(callback) {
if (os.platform() === 'win32') {
exec('wmic logicaldisk get size,freespace,caption', (err, stdout) => {
if (err) return callback('βœ–οΈ');
const lines = stdout.trim().split('\n').slice(1);
const storageInfo = lines.map(line => {
const [drive, free, total] = line.trim().split(/\s+/);
return `πŸ–₯️ ${drive}: ${(total / (1024 ** 3)).toFixed(2)} GB total, ${(free / (1024 ** 3)).toFixed(2)} GB libres`;
}).join('\n');
callback(storageInfo);
});
} else {
exec('df -h --output=source,size,avail,target', (err, stdout) => {
if (err) return callback('βœ–οΈ');
const lines = stdout.trim().split('\n').slice(1);
const storageInfo = lines.map(line => {
const [device, total, free, mount] = line.trim().split(/\s+/);
return `πŸ–₯️ ${mount}: ${total} total, ${free} libres en ${device}`;
}).join('\n');
callback(storageInfo);
});
}
}

function getLinuxInfo(callback) {
exec('cat /etc/os-release', (err, osInfo) => {
if (err) osInfo = 'βœ–οΈ';
callback(osInfo.trim());
});
}

function getBatteryInfo(callback) {
if (os.platform() === 'linux' || os.platform() === 'darwin') {
exec('upower -i $(upower -e | grep BAT)', (err, batteryInfo) => {
if (err) return callback('βœ–οΈ');
callback(batteryInfo);
});
} else if (os.platform() === 'win32') {
exec('WMIC Path Win32_Battery Get EstimatedChargeRemaining', (err, batteryInfo) => {
if (err) return callback('βœ–οΈ');
callback(`πŸ”‹ ${batteryInfo.trim()}%`);
});
} else {
callback('βœ–οΈ');
}
}

async function systemInfoPlugin(m, extra) {
try {
const systemInfo = {
platform: os.platform(),
cpuArch: os.arch(),
cpus: os.cpus().length,
totalMemory: (os.totalmem() / (1024 ** 3)).toFixed(2) + ' GB', // Total RAM en GB
freeMemory: (os.freemem() / (1024 ** 3)).toFixed(2) + ' GB', // RAM libre en GB
uptime: formatUptime(os.uptime()), // Tiempo de actividad
osVersion: os.release(), // VersiΓ³n del SO
loadAverage: os.loadavg().map(load => load.toFixed(2)).join(', ') // Carga promedio
};

getVersions((versions) => {
getBatteryInfo((batteryStatus) => {
getStorageInfo((storageInfo) => {
getLinuxInfo((linuxInfo) => {
let infoMessage = `> *πŸ“Š InformaciΓ³n del Sistema*\n\n`;
infoMessage += `- 🌐 *Plataforma*: _${systemInfo.platform}_\n`;
infoMessage += `- πŸ’» *Arquitectura CPU*: ${systemInfo.cpuArch}\n`;
infoMessage += `- 🧠 *Núcleos CPU*: ${systemInfo.cpus}\n`;
infoMessage += `- πŸ—„οΈ *Memoria Total*: ${systemInfo.totalMemory}\n`;
infoMessage += `- πŸ—ƒοΈ *Memoria Libre*: ${systemInfo.freeMemory}\n`;
infoMessage += `- ⏱️ *Tiempo de Actividad*: ${systemInfo.uptime}\n`;
infoMessage += `- πŸ“€ *VersiΓ³n del SO*: ${systemInfo.osVersion}\n`;
infoMessage += `- πŸ“Š *Carga Promedio (1, 5, 15 min)*: ${systemInfo.loadAverage}\n`;
infoMessage += `- πŸ”‹ *Energia*: ${batteryStatus}\n\n`;

infoMessage += `> *πŸ’Ύ Almacenamiento*\n`;
infoMessage += `${storageInfo}\n\n`;

infoMessage += `> *πŸ› οΈ Version Herramientas*\n\n`;
infoMessage += `- β˜• *Node.js*: ${versions.nodeVersion.trim()}\n`;
infoMessage += `- πŸ“¦ *NPM*: ${versions.npmVersion.trim()}\n`;
infoMessage += `- πŸŽ₯ *FFmpeg*: ${versions.ffmpegVersion.split('\n')[0]}\n`; // Solo primera linea
infoMessage += `- 🐍 *Python*: ${versions.pythonVersion.trim()}\n`;
infoMessage += `- πŸ“¦ *PIP*: ${versions.pipVersion.trim()}\n`;
infoMessage += `- 🍫 *Chocolatey*: ${versions.chocoVersion.trim()}\n\n`;

if (os.platform() === 'linux') {
infoMessage += `> *🐧 Distribución Linux*\n${linuxInfo}\n`;
}

extra.conn.sendMessage(m.chat, { text: infoMessage });
});
});
});
});
} catch (error) {
console.error('Falla Plugin sysinfo:', error);
await extra.conn.sendMessage(m.chat, { text: 'ERROR' });
}
}

systemInfoPlugin.command = ['sysinfo', 'host'];

export default systemInfoPlugin;
111 changes: 111 additions & 0 deletions plugins/addAuVid.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
// MR. De la Comunidad para la Comunidad. Prohibida su Venta.
// El Software se proporciona bajo los tΓ©rminos de la Licencia MIT, excepto que usted no puede:
// 1. Vender, revender o arrendar el Software.
// 2. Cobrar a otros por el acceso, la distribuciΓ³n o cualquier otro uso comercial del Software.
// 3. Usar el Software como parte de un producto comercial o una oferta de servicio.

// Aquien sabe que tan eficiente sea agregar tantos... El que encuentre una manera de mejorarlo bienvenido. Buscar la palabra en el directorio creeria es aun peor.

import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const nvGlobalPath = path.join(__dirname, '../plugins/nv-global.js');

const mediaDirPath = path.join(__dirname, '../src/assets/audio');

const moveQuotedMedia = async (m, palabra, mediaType) => {
try {
const mediaBuffer = await m.quoted.download();
const fileExtension = mediaType === 'audio' ? 'mp3' : 'mp4';
const mediaFilePath = path.join(mediaDirPath, `${palabra}.${fileExtension}`);

if (!fs.existsSync(mediaDirPath)) {
await fs.promises.mkdir(mediaDirPath, { recursive: true });
}

await fs.promises.writeFile(mediaFilePath, mediaBuffer);
console.log(`βœ… ${mediaType === 'audio' ? 'Audio' : 'Video'} guardado ${mediaFilePath}`);

return mediaFilePath;
} catch (error) {
console.error(`❌ Error mv ${mediaType}: ${error.message}`);
throw new Error(`Error moviendo ${mediaType}.`);
}
};

const addMediaHandler = async (keyword, mediaFilePath, mediaType) => {
try {
let fileContent = await fs.promises.readFile(nvGlobalPath, 'utf-8');

const closingBlock = `
return !0;
};
export default handler;
`;

if (fileContent.includes(`m.text.match(/(${keyword})/gi)`)) {
throw new Error(`Existe "${keyword}" `);
}

const closingRegex = new RegExp(/^ return !0;\s*};\s*export default handler;$/gm);
fileContent = fileContent.replace(closingRegex, '').trim();

const newIfBlock = `
if (!chat.isBanned && m.text.match(/(${keyword})/gi)) {
if (!db.data.chats[m.chat].audios) return;
if (!db.data.settings[this.user.jid].audios_bot && !m.isGroup) return;
const vn = './src/assets/audio/${keyword}.${mediaType === 'audio' ? 'mp3' : 'mp4'}';
mconn.conn.sendPresenceUpdate('recording', m.chat);
mconn.conn.sendMessage(m.chat, {${mediaType === 'audio' ? 'audio' : 'video'}: {url: vn}, fileName: '${keyword}.${mediaType === 'audio' ? 'mp3' : 'mp4'}', mimetype: '${mediaType === 'audio' ? 'audio/mpeg' : 'video/mp4'}', ${mediaType === 'audio' ? 'ptt: true' : 'ptv: true'}}, {quoted: m});
}
`;

const newFileContent = fileContent + '\n' + newIfBlock + '\n' + closingBlock;

await fs.promises.writeFile(nvGlobalPath, newFileContent, 'utf-8');

console.log(`Agregado "${keyword}" ${mediaType} ${mediaFilePath}`);

} catch (error) {
console.error(`error guardando ${error.message}`);
}
};

const handler = async (m, { text }) => {
if (!text) {
return m.reply('❌ Ej: .addaudio hola');
}

const keyword = text.trim();

try {
let mediaType;

if (m.quoted && m.quoted.mimetype && m.quoted.mimetype.startsWith('audio')) {
mediaType = 'audio';
} else if (m.quoted && m.quoted.mimetype && m.quoted.mimetype.startsWith('video')) {
mediaType = 'video';
} else {
throw new Error('❌ Audio/Video.');
}

const mediaFilePath = await moveQuotedMedia(m, keyword, mediaType);

await addMediaHandler(keyword, mediaFilePath, mediaType);

m.reply(`βœ… ${mediaType === 'audio' ? 'Audio' : 'Video'} "${keyword}" `);
} catch (error) {
m.reply(`❌ Error: ${error.message}`);
}
};

handler.command = /^add(media|audio)$/i;
handler.help = ['addaudio <palabra>'];
handler.tags = ['tools'];
handler.owner = true;

export default handler;

0 comments on commit 90d409f

Please sign in to comment.