Paket Live 2 (khusus Murid Bot Arifi Razzaq Ofc)
arifi
975 x views • 3 years ago
Link Live: š
https://www.youtube.com/live/VOoh0Su8_Ww?feature=share
Bahannya di Bawah: š
//Config Update
"use strict";
const language = require('./database/assets/language.json')['indonesia']
const { Low, JSONFile } = require("./database/lowdb");
const Function = new (require('./lib/function.js'));
const { makeInMemoryStore } = require("@adiwajshing/baileys");
const pluginFilter = (filename) => /\.js$/.test(filename),
const pluginFolder = Function.iky.join(__dirname, "./commands");
class config {
static botname = require('./package.json').name;
static ownername = require('./package.json').author.split('<')[0];
static email = require('./package.json').author.split('<')[1].split('>')[0];
static description = require('./package.json').description;
static homepage = require('./package.json').author.split('(')[1].split(')')[0];
static source = {
instagram: 'https://instagram.com/arifirazzaq2001',
group: 'https://chat.whatsapp.com/HXnDebS5pYB0UA0iB1RmIa'
};
static server = true;
static self = false;
static prefixs = "multi";
static session = "./database/session";
static limit = 50
static owner = ["[email protected]"]; // ganti nomor owner
}
global.game = {}
global.game.akinator = {}
global.conns = {}
global.attr = {
commands: new Map(),
functions: new Map(),
isSelf: config.self
};
global.baileysstore = makeInMemoryStore({
logger: Function.pino().child({
level: "silent",
stream: "store"
}),
});
global.reload = (path) => {
path = `./${path.replace(/\\/g, '/')}`
filename = path.split("/")[3]
if (pluginFilter(filename)) {
let dir = Function.iky.join(pluginFolder, './' + path.split('/')[2] + '/' + path.split('/')[3])
isi = require(path)
if (dir in require.cache) {
delete require.cache[dir];
if (Function.fs.existsSync(dir)) console.info(`re - require plugin '${path}'`);
else {
console.log(`deleted plugin '${path}'`);
return isi.function
? delete attr.functions[filename]
: delete attr.commands[filename];
}
} else console.info(`requiring new plugin '${filename}'`);
let err = Function.syntaxerror(Function.fs.readFileSync(dir), filename);
if (err) console.log(`syntax error while loading '${filename}'\n${err}`);
else
try {
isi.function
? (attr.functions[filename] = require(dir))
: (attr.commands[filename] = require(dir));
} catch (e) {
console.log(e);
} finally {
isi.function
? (attr.functions = Object.fromEntries(
Object.entries(attr.functions).sort(([a], [b]) => a.localeCompare(b))
))
: (attr.commands = Object.fromEntries(
Object.entries(attr.commands).sort(([a], [b]) => a.localeCompare(b))
));
}
}
};
global.db = new Low(new JSONFile("database/json/database.json"));
global.bochil = require('@bochilteam/scraper');
global.cph = require('caliph-api');
global.dhn = require('dhn-api');
global.maker = require('mumaker');
global.rzky = new Function.iky();
global.Api = new (require('./event/system/neoxrApi'))(process.env.API_KEY)
global.creator = config.ownername;
global.owner = config.owner;
global.response = mess;
global.users = JSON.parse(Function.fs.readFileSync('./database/json/user.json'));
global.tool = require("./lib/tools");
global.scrapp = require("./lib/scraper");
global.Func = Function
global.ig = require('./lib/instagram');
global.shp = `ā¢`;
global.reloadFile = (file, options = {}) => {
tool.nocache(file, module => {
console.log(`File "${file}" has updated!\nRestarting!`)
process.send("reset")
})
}
baileysstore.readFromFile(`./database/session/${config.botname.toLowerCase()}_store.json`);
setInterval(() => {
baileysstore.writeToFile(`./database/session/${config.botname.toLowerCase()}_store.json`);
}, 10000);
setInterval(async () => {
const tmpFiles = Function.fs.readdirSync('./temp/bin')
if(tmpFiles.length > 0) {
tmpFiles.map(v => Function.fs.unlinkSync('./temp/bin/' + v))
}
const storeFile = await Func.getFile(`./database/session/${config.botname.toLowerCase()}_store.json`);
let chSize = await Func.sizeLimit(storeFile.size, 2)
if(chSize.oversize) {
Function.fs.writeFileSync(`./database/session/${config.botname.toLowerCase()}_store.json`, Function.stable({
"chats": [],
"contacts": {},
"messages": {}
}))
}
}, 60 * 1000 * 5)
module.exports = config;
let file = require.resolve(__filename);
Function.fs.watchFile(file, () => {
Function.fs.unwatchFile(file);
console.log(file);
delete require.cache[file];
});
//lib/server.js
const express = require("express");
const fs = require("fs");
const os = require("os");
const app = express();
const QR = require("qrcode-terminal");
const qrcod = require("qrcode");
const server = require("http").createServer(app);
const io = require("socket.io")(server);
const PORT = process.env.PORT || 5000;
const util = require("util");
const { toTimer } = require("./tools");
const { sizeFormatter } = require("human-readable");
const formatSize = sizeFormatter({
std: "JEDEC",
decimalPlaces: "2",
keepTrailingZeroes: false,
render: (literal, symbol) => `${literal} ${symbol}B`,
});
module.exports = async (conn) => {
try {
let lastqr = false;
let connected = false;
conn.ev.on("connection.update", async (qr) => {
const { lastDisconnect, connection } = qr;
if (connection == "open") {
connected = true;
io.emit("connected", conn.user);
}
if(connection == 'close'){
connected = true
io.emit('disconnected', {})
}
if (qr.qr == undefined) return;
global.qrcode = await qrcod.toDataURL(qr.qr);
io.emit("qr", qrcode);
});
app.set("json spaces", 2);
app.use(express.static("public"));
app.get(["/infobot"], async (req, res) => {
res.json({
status: "active",
runtime: await toTimer(process.uptime()),
user: conn.user,
server: {
os_release: os.release(),
os_version: os.version(),
},
});
});
app.get(["/"], async (req, res) => {
await res.sendFile("index.html", { root: "./" });
await tool.sleep(3000);
if (connected) await io.emit("connected", conn.user);
else await io.emit("qr", qrcode);
});
server.listen(PORT, () => {
console.log(`Server Running on Port ${PORT}`);
});
} catch {}
};
//Function
const chalk = require("chalk");
const axios = require("axios");
const fetch = require("node-fetch");
const { JSDOM } = require("jsdom");
const FormData = require("form-data");
const fs = require("fs");
const cheerio = require("cheerio");
const { fromBuffer } = require("file-type");
const Jimp = require('jimp')
const { S_WHATSAPP_NET } = require("@adiwajshing/baileys")
function color(text, color) {
return !color ? chalk.green(text) : chalk.keyword(color)(text)
}
function bgcolor(text, bgcolor) {
return !bgcolor ? chalk.green(text) : chalk.bgKeyword(bgcolor)(text)
}
async function uncache(module = '.') {
return new Promise((resolve, reject) => {
try {
delete require.cache[require.resolve(module)]
resolve()
} catch (e) {
reject(e)
}
})
}
async function nocache(module, cb = () => { }) {
console.log(color('Module', 'blue'), color(`'${module}' Currently Refreshed . . .`, 'red'))
fs.watchFile(require.resolve(module), async () => {
await uncache(require.resolve(module))
cb(module)
})
}
exports.nocache = nocache;
exports.uncache = uncache;
exports.color = color;
exports.bgcolor = bgcolor;
exports.resize = async(buffer, ukur1, ukur2) => {
try{
const readbuf = await Jimp.read(buffer);
const buff = await readbuf.resize(ukur1, ukur2).getBufferAsync(Jimp.MIME_JPEG)
return(buff)
}catch(e){
return(String(e))
}
}
exports.monospace = (string) => {
return '```'+string+'```'
}
exports.formatPhone = (number) => {
let formatted = number.replace(/\D/g, '');
if (formatted.startsWith('0')) {
formatted = formatted.substr(1) + S_WHATSAPP_NET;
} else if (formatted.startsWith('62')) {
formatted = formatted.substr(2) + S_WHATSAPP_NET;
}
return number.endsWith(S_WHATSAPP_NET) ? number : '62' + formatted;
}
exports.fetchJson = (url, options) => new Promise(async(resolve, reject) => {
fetch(url, options)
.then(response => response.json())
.then(json => {
// console.log(json)
resolve(json)
})
.catch((err) => {
reject(err)
})
})
exports.color = (text, color) => {
return !color ? chalk.green(text) : chalk.keyword(color)(text);
};
exports.randomobj = (array) => {
return array[Math.floor(Math.random() * array.length)];
};
exports.isUrl = (url) => {
return url.match(
new RegExp(
/https?:\/\/(www\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_+.~#?&/=]*)/,
"gi"
)
);
};
exports.parseMention = async (text) => {
return [...text.matchAll(/@([0-9]{5,16}|0)/g)].map(
(v) => v[1] + "@s.whatsapp.net"
);
};
const kapitalisasiKata = async (str) => {
return str.replace(/\w\S*/g, function (kata) {
const kataBaru = kata.slice(0, 1).toUpperCase() + kata.substr(1);
return kataBaru;
});
};
exports.webp2mp4 = async (source) => {
let form = new FormData();
let isUrl = typeof source === "string" && /https?:\/\//.test(source);
form.append("new-image-url", isUrl ? source : "");
form.append("new-image", isUrl ? "" : source, "image.webp");
let res = await fetch("https://ezgif.com/webp-to-mp4", {
method: "POST",
body: form,
});
let html = await res.text();
let { document } = new JSDOM(html).window;
let form2 = new FormData();
let obj = {};
for (let input of document.querySelectorAll("form input[name]")) {
obj[input.name] = input.value;
form2.append(input.name, input.value);
}
let res2 = await fetch("https://ezgif.com/webp-to-mp4/" + obj.file, {
method: "POST",
body: form2,
});
let html2 = await res2.text();
let { document: document2 } = new JSDOM(html2).window;
return new URL(
document2.querySelector("div#output > p.outfile > video > source").src,
res2.url
).toString();
};
exports.webp2png = async (source) => {
let form = new FormData();
let isUrl = typeof source === "string" && /https?:\/\//.test(source);
form.append("new-image-url", isUrl ? source : "");
form.append("new-image", isUrl ? "" : source, "image.webp");
let res = await fetch('https://s6.ezgif.com/webp-to-png', {
method: 'POST',
body: form,
})
let html = await res.text()
let { document } = new JSDOM(html).window
let form2 = new FormData()
let obj = {}
for (let input of document.querySelectorAll('form input[name]')) {
obj[input.name] = input.value
form2.append(input.name, input.value)
}
let res2 = await fetch('https://ezgif.com/webp-to-png/' + obj.file, {
method: 'POST',
body: form2,
})
let html2 = await res2.text()
let { document: document2 } = new JSDOM(html2).window
return new URL(document2.querySelector('div#output > p.outfile > img').src, res2.url).toString()
};
exports.sleep = async (ms) => {
return new Promise((resolve) => setTimeout(resolve, ms));
};
exports.formatRupiah = async (angka, prefix) => {
var number_string = angka.replace(/[^,\d]/g, "").toString(),
split = number_string.split(","),
sisa = split[0].length % 3,
rupiah = split[0].substr(0, sisa),
ribuan = split[0].substr(sisa).match(/\d{3}/gi);
// tambahkan titik jika yang di input sudah menjadi angka ribuan
if (ribuan) {
const separator = sisa ? "." : "";
rupiah += separator + ribuan.join(".");
}
rupiah = split[1] != undefined ? rupiah + "," + split[1] : rupiah;
return prefix == undefined ? rupiah : rupiah ? "Rp. " + rupiah : "";
};
exports.parseResult = async (title, json, option) => {
if (Array.isArray(json)) {
var txt = `${title ? `_*${title}*_\n\n` : ''}${global.shp}\n`;
for (let i = 0; i < json.length; i++) {
if (option && option.delete) {
for (let j of option.delete) {
delete json[i][j];
}
}
for (let j of Object.entries(json[i])) {
if (j[1] != undefined && j[1] != null && j[1] != "") {
txt += `${global.shp} *${await kapitalisasiKata(
j[0].replace(/_/, " ")
)}* : ${j[1]}\n`;
}
}
if (i + 1 != json.length) txt += `\n${global.shp}\n`;
}
//txt += `\n⬢ _*${config.botname}*_`;
} else {
var txt = title ? `_*${title}*_\n\n` : '';
if (option && option.delete) {
for (let j of option.delete) {
delete json[j];
}
}
for (let i of Object.entries(json)) {
if (i[1] != undefined && i[1] != null && i[1] != "") {
txt += `${global.shp} *${await kapitalisasiKata(
i[0].replace(/_/, " ")
)}* : ${i[1]}\n`;
}
}
//txt += `\n⬢ _*${config.botname}*_`;
}
return txt.trim();
};
exports.toTimer = (seconds) => {
function pad(s) {
return (s < 10 ? "0" : "") + s;
}
var hours = Math.floor(seconds / (60 * 60));
var minutes = Math.floor((seconds % (60 * 60)) / 60);
var seconds = Math.floor(seconds % 60);
//return pad(hours) + ':' + pad(minutes) + ':' + pad(seconds)
return `${pad(hours)} Jam - ${pad(minutes)} Menit - ${pad(seconds)} Detik`;
};
exports.kapitalisasiKata = async (str) => {
return str.replace(/\w\S*/g, function (kata) {
const kataBaru = kata.slice(0, 1).toUpperCase() + kata.substr(1);
return kataBaru;
});
};
exports.tiny = async (link) => {
return new Promise((resolve) => {
axios.get(`https://tinyurl.com/api-create.php?url=${link}`).then((res) => {
resolve(res.data);
});
});
};
exports.getRandom = (ext) => {
return `${Math.floor(Math.random() * 10000)}${ext ? ext : ""}`;
};
exports.ugu = async (buffer) => {
return new Promise((resolve, reject) => {
fromBuffer(buffer).then((cek_file) => {
nama = Date.now()
if(cek_file == undefined) return resolve({status: false})
fs.writeFileSync(`./temp/${nama}.${cek_file.ext}`, buffer);
const bodyForm = new FormData();
bodyForm.append(
"files[]",
fs.createReadStream(`./temp/${nama}.${cek_file.ext}`)
);
//
axios(`https://uguu.se/upload.php`, {
method: "POST",
data: bodyForm,
headers: Object.assign({ "accept": "*/*", "accept-language": "en-US,en;q=0.9,id;q=0.8" }, bodyForm.getHeaders())
}).then(respon => {
const result = {
status: respon.data.success ? 200 : 404,
result: {
nama: respon.data.files[0].name,
url: respon.data.files[0].url,
size: respon.data.files[0].size,
hash: respon.data.files[0].hash
}
};
fs.unlinkSync(`./temp/${nama}.${cek_file.ext}`)
resolve(result);
});
});
});
};
exports.telegraph = async (buffer) => {
const { ext } = await fromBuffer(buffer);
let form = new FormData();
form.append("file", buffer, "tmp." + ext);
let res = await fetch("https://telegra.ph/upload", {
method: "POST",
body: form,
});
let img = await res.json();
if (img.error) throw img.error;
return "https://telegra.ph" + img[0].src;
};
exports.getBuffer = async (url, options) => {
try {
options ? options : {};
const res = await axios({
method: "get",
url,
headers: {
DNT: 1,
"Upgrade-Insecure-Request": 1,
},
...options,
responseType: "arraybuffer",
});
return res.data;
} catch (e) {
throw new Error(e);
}
};
let file = require.resolve(__filename);
fs.watchFile(file, () => {
fs.unwatchFile(file);
console.log(file);
delete require.cache[file];
});
//packaga
{
"name": "hilda-bot",
"version": "3.4.1",
"description": "Last Version Waiting For Update In Youtube Channel Arifi Razzaq OFC.",
"type": "commonjs",
"main": "./index.js",
"scripts": {
"start": "node index.js"
},
"keywords": [
"bot-whatsapp"
],
"author": "Arifi Razzaq <[email protected]> (https://youtube.com/@arifirazzaqofc3405)",
"license": "ISC",
"directories": {
"event": "event",
"commands": "commands"
},
"dependencies": {
"@adiwajshing/baileys": "npm:[email protected]",
"@adiwajshing/keyed-db": "^0.2.4",
"@colors/colors": "1.5.0",
"@neoxr/neoxr-js": "^1.4.8",
"@bochilteam/scraper": "^2.0.0",
"aki-api": "^6.0.8",
"awesome-phonenumber": "^3.0.1",
"axios": "^0.27.2",
"caliph-api": "^0.8.4",
"chalk": "^4.1.2",
"cheerio": "^1.0.0-rc.10",
"child_process": "^1.0.2",
"crypto": "^1.0.1",
"dhn-api": "^1.1.3",
"dotenv": "^16.0.3",
"json-stable-stringify": "^1.0.2",
"rootpath": "^0.1.2",
"cfonts": "~2.10.0",
"encodeurl": "^1.0.2",
"express": "^4.18.1",
"network-speed": "^2.1.1",
"fetch": "^1.1.0",
"file-type": "^16.5.3",
"fluent-ffmpeg": "^2.1.2",
"form-data": "^4.0.0",
"got": "^11.8.3",
"html-entities": "^2.3.3",
"human-readable": "^0.2.1",
"ikyy": "^3.0.4",
"instagram-url-direct": "^1.0.12",
"jimp": "^0.16.1",
"jsdom": "^19.0.0",
"moment-timezone": "^0.5.34",
"mumaker": "^1.0.0",
"music-lyrics": "^2.0.2",
"node-fetch": "^2.0.0",
"node-id3": "^0.2.3",
"node-webpmux": "^3.1.0",
"node-cron": "^3.0.0",
"node-gtts": "^2.0.2",
"pino": "~7.0.5",
"spinnies": "^0.5.1",
"openai": "^3.1.0",
"pino-pretty": "^10.0.0",
"pretty-ms": "^7.0.1",
"qrcode": "^1.5.0",
"qrcode-terminal": "^0.12.0",
"request": "^2.88.2",
"socket.io": "^4.5.2",
"network-speed": "^2.1.1",
"steno": "^1.0.0",
"syntax-error": "^1.4.0",
"yargs": "^17.5.1",
"zs-extract": "^1.4.1"
}
}
//Event Connection
"use strict";
const spinnies = new(require('spinnies'))(), fs = require('fs'), qrcode = require('qrcode-terminal');
async function connection(middlewares, session, conn, result, DisconnectReason) {
try {
const {
connection,
lastDisconnect,
qr
} = result;
if(lastDisconnect == 'undefined' && qr != 'undefined') {
qrcode.generate(qr, {
small: true
});
};
if(connection === 'connecting') {
spinnies.add('start', {
text: 'Connecting . . .'
});
} else if(connection === 'open') {
spinnies.succeed('start', {
text: `Connected, you login as ${conn.user.name || conn.user.verifiedName}`
});
conn.sendMessage("[email protected]", { text: "Bot Telah Online . . ." })
} else if(connection === 'close') {
if(lastDisconnect.error.output.statusCode == DisconnectReason.loggedOut) {
spinnies.fail('start', {
text: `Can't connect to Web Socket`
});
await props.save();
process.exit(0);
} else if(lastDisconnect.error.output.statusCode == DisconnectReason.connectionReplaced) {
spinnies.fail('start', {
text: `Can't connect to Web Socket`
});
await props.save();
process.exit(0);
} else {
middlewares(session).catch(() => middlewares(session));
}
}
} catch (err) {
console.log(console.log(require("util")["format"](err)));
};
};
module.exports = connection;
//serialize
const {
proto,
jidDecode,
downloadContentFromMessage,
getContentType,
getStream,
generateForwardMessageContent,
generateWAMessageFromContent
} = require("@adiwajshing/baileys");
const path = require("path");
const fetch = require("node-fetch");
const Baileys = require("@adiwajshing/baileys");
const { logger } = Baileys.DEFAULT_CONNECTION_CONFIG;
const axios = require("axios");
const fs = require("fs");
const chalk = require("chalk");
const moment = require("moment");
const { fromBuffer } = require("file-type");
const { isUrl } = require("./tools");
const phonenumber = require("awesome-phonenumber");
const { toOpus, toAudio, convert, convert2 } = require("./convert");
const { toPTT, toAudio: toAudio2 } = require("./converter");
const id3 = require('node-id3');
let parseMention = text => [...text.matchAll(/@([0-9]{5,16}|0)/g)].map(v => v[1] + '@s.whatsapp.net');
const cmd = {
1: [
"-fs 1M",
"-vcodec",
"libwebp",
"-vf",
`scale=512:512:flags=lanczos:force_original_aspect_ratio=decrease,format=rgba,pad=512:512:(ow-iw)/2:(oh-ih)/2:color=#00000000,setsar=1`,
],
2: ["-fs 1M", "-vcodec", "libwebp"],
};
const downloadMedia = (message, pathFile) =>
new Promise(async (resolve, reject) => {
let type = Object.keys(message)[0];
let mimeMap = {
imageMessage: "image",
videoMessage: "video",
stickerMessage: "sticker",
documentMessage: "document",
audioMessage: "audio",
};
let mes = message;
if (type == "templateMessage") {
mes = message.templateMessage.hydratedFourRowTemplate;
type = Object.keys(mes)[0];
}
if (type == "buttonsMessage") {
mes = message.buttonsMessage;
type = Object.keys(mes)[0];
}
try {
if (pathFile) {
const stream = await downloadContentFromMessage(mes[type], mimeMap[type]);
let buffer = Buffer.from([]);
for await (const chunk of stream) {
buffer = Buffer.concat([buffer, chunk]);
}
await fs.promises.writeFile(pathFile, buffer);
resolve(pathFile);
} else {
const stream = await downloadContentFromMessage(mes[type], mimeMap[type]);
let buffer = Buffer.from([]);
for await (const chunk of stream) {
buffer = Buffer.concat([buffer, chunk]);
}
resolve(buffer);
}
} catch (e) {
reject(e);
}
});
async function serialize(msg, conn) {
conn.decodeJid = (jid) => {
if (/:\d+@/gi.test(jid)) {
const decode = jidDecode(jid) || {};
return ((decode.user && decode.server && decode.user + "@" + decode.server) || jid).trim();
} else return jid;
};
/**
* getBuffer hehe
* @param {String|Buffer} path
* @param {Boolean} returnFilename
*/
//dari sc rizky
conn.sendMessage = async (jid, content, options = {}) => {
const typeMes = content.image || content.text || content.video || content.document
const cotent = content.caption || content.text || "";
content.withTag
? (content.mentions = [...cotent.matchAll(/@([0-9]{5,16}|0)/g)].map((v) => v[1] + "@s.whatsapp.net"))
: "";
options.adReply
? (content.contextInfo = {
externalAdReply: {
title: config.botname,
sourceUrl: "https://youtube.com/@arifirazzaqofc3405",
mediaType: 1,
mediaUrl: "https://youtube.com/@arifirazzaqofc3405",
renderLargerThumbnail: false,
showAdAttribution: true,
body: "Arifi Razzaq",
thumbnail: await tool.getBuffer(await conn.profilePictureUrl(msg.sender, 'image', 1000).catch(err => "https://i.ibb.co/31vqq8h/depositphotos-9883921-stock-illustration-no-user-profile-picture.jpg")),
thumbnailUrl: await conn.profilePictureUrl(msg.sender, 'image', 1000).catch(err => "https://i.ibb.co/31vqq8h/depositphotos-9883921-stock-illustration-no-user-profile-picture.jpg"),
},
})
: "";
var _a, _b;
const userJid = msg.sender
if (typeof content === 'object' && 'disappearingMessagesInChat' in content && typeof content['disappearingMessagesInChat'] !== 'undefined' && (0, Baileys.isJidGroup)(jid)) {
const { disappearingMessagesInChat } = content;
const value = typeof disappearingMessagesInChat === 'boolean' ?
(disappearingMessagesInChat ? Baileys.WA_DEFAULT_EPHEMERAL : 0) :
disappearingMessagesInChat;
await conn.groupToggleEphemeral(jid, value);
}
else {
const additionalAttributes = {};
const isDeleteMsg = 'delete' in content && !!content.delete;
// required for delete
if (isDeleteMsg) {
// if the chat is a group, and I am not the author, then delete the message as an admin
if ((0, Baileys.isJidGroup)((_a = content.delete) === null || _a === void 0 ? void 0 : _a.remoteJid) && !((_b = content.delete) === null || _b === void 0 ? void 0 : _b.fromMe)) {
additionalAttributes.edit = '8';
}
else {
additionalAttributes.edit = '7';
}
}
const contentMsg = await Baileys.generateWAMessageContent(content, {
logger,
userJid: conn.decodeJid(conn.user.id),
upload: conn.waUploadToServer,
...options,
})
const fromContent = await Baileys.generateWAMessageFromContent(jid, contentMsg, options);
fromContent.key.id = "RAZZAQ" + require("crypto").randomBytes(13).toString("hex").toUpperCase();
await conn.relayMessage(jid, fromContent.message, {
messageId: fromContent.key.id,
additionalAttributes,
})
}
}
const groupQuery = async (jid, type, content) => (conn.query({
tag: 'iq',
attrs: {
type,
xmlns: 'w:g2',
to: jid,
},
content
}));
conn.generateGroupInviteMessage = async (jid, participant) => {
const result = await groupQuery(
jid,
'set',
[{
tag: 'add',
attrs: {},
content: [{ tag: 'participant', attrs: { jid: participant } }]
}]
)
};
conn.groupAdmin = async (jid) => {
let participant = await (await conn.groupMetadata(jid)).participants
let admin = []
for (let i of participant)(i.admin === "admin" || i.admin === "superadmin") ? admin.push(i.id) : ''
return admin
}
conn.copyNForward = async (jid, message, forceForward = false, options = {}) => {
let vtype;
if (options.readViewOnce) {
message.message = message.message && message.message.ephemeralMessage && message.message.ephemeralMessage.message ? message.message.ephemeralMessage.message : message.message || undefined;
vtype = Object.keys(message.message.viewOnceMessage.message)[0];
delete (message.message && message.message.ignore ? message.message.ignore : message.message || undefined);
delete message.message.viewOnceMessage.message[vtype].viewOnce;
message.message = {
...message.message.viewOnceMessage.message,
};
}
let mtype = Object.keys(message.message)[0];
let content = await generateForwardMessageContent(message, forceForward);
let ctype = Object.keys(content)[0];
let context = {};
if (mtype != msg.type) context = message.message[mtype].contextInfo;
content[ctype].contextInfo = {
...context,
...content[ctype].contextInfo,
...(options.contextInfo ?
{
...options.contextInfo,
} :
{}),
};
const waMessage = await generateWAMessageFromContent(jid, content, options ? {
...content[ctype],
...options,
...(options.contextInfo ?
{
contextInfo: {
...content[ctype].contextInfo,
...options.contextInfo,
},
} :
{}),
} :
{}
);
await conn.relayMessage(jid, waMessage.message, {
messageId: waMessage.key.id,
});
return waMessage;
};
conn.getFile = async (PATH, returnAsFilename) => {
let res, filename;
let data = Buffer.isBuffer(PATH) ?
PATH :
/^data:.*?\/.*?;base64,/i.test(PATH) ?
Buffer.from(PATH.split`,`[1], "base64") :
/^https?:\/\//.test(PATH) ?
await (res = await fetch(PATH)).buffer() :
fs.existsSync(PATH) ?
((filename = PATH), fs.readFileSync(PATH)) :
typeof PATH === "string" ?
PATH :
Buffer.alloc(0);
if (!Buffer.isBuffer(data)) throw new TypeError("Result is not a buffer");
let type = (await fromBuffer(data)) || {
mime: "application/octet-stream",
ext: ".bin",
};
if (data && returnAsFilename && !filename)
(filename = path.join(
__dirname,
"../temp/" + new Date() * 1 + "." + type.ext
)),
await fs.promises.writeFile(filename, data);
return {
res,
filename,
...type,
data,
};
};
conn.sendButton = async (jid, text, footer, buttons, opt) => {
return await conn.sendMessage(
jid, {
text: text,
footer: footer,
templateButtons: buttons,
withTag: opt ? (opt.withTag ? true : false) : false,
adReply: opt ? (opt.adReply ? true : false) : false,
}, {
...opt
}
)
}
conn.sendButtonImage = async (jid, image, caption, footer, buttons, opt) => {
if (opt && opt.isLoc) {
return await conn.sendMessage(
jid, {
location: {
degreesLatitude: 0,
degreesLongitude: 0,
jpegThumbnail: await tool.resize(image, 200, 200)
},
caption: caption,
footer: footer,
templateButtons: buttons,
withTag: opt ? (opt.withTag ? true : false) : false,
adReply: opt ? (opt.adReply ? true : false) : false,
}, {
...opt
}
);
}
return await conn.sendMessage(
jid, {
image: image,
caption: caption,
footer: footer,
templateButtons: buttons,
withTag: opt ? (opt.withTag ? true : false) : false,
adReply: opt ? (opt.adReply ? true : false) : false,
}, {
...opt
}
);
};
conn.sendButtonImageV2 = async (
from,
img,
teks,
footer,
display,
buttonid,
opt
) => {
datai = [];
for (let i = 0; i < display.length; i++) {
datai.push({
buttonId: buttonid[i],
buttonText: {
displayText: display[i]
},
type: 1,
});
}
if (opt && opt.isLoc) {
bts = {
location: {
degreesLatidude: 0,
degreesLongitude: 0,
jpegThumbnail: await tool.resize(img, 200, 200)
},
caption: teks,
footer: footer,
buttons: datai,
headerType: "LOCATION",
};
} else {
bts = {
image: img,
caption: teks,
footer: footer,
buttons: datai,
headerType: "IMAGE",
};
}
return await conn.sendMessage(from, bts, {
...opt
});
};
conn.sendButtonVideoV2 = async (
from,
vid,
teks,
footer,
display,
buttonid,
opt
) => {
datai = [];
for (let i = 0; i < display.length; i++) {
datai.push({
buttonId: buttonid[i],
buttonText: {
displayText: display[i]
},
type: 1,
});
}
bts = {
video: vid,
caption: teks,
footer: footer,
buttons: datai,
headerType: "VIDEO",
};
return await conn.sendMessage(from, bts, {
...opt
});
};
conn.sendButtonVideo = async (jid, video, caption, footer, buttons, opt) => {
return await conn.sendMessage(
jid, {
video: video,
gifPlayback: opt ? (opt.gifPlayback ? true : false) : false,
caption: caption,
footer: footer,
templateButtons: buttons,
withTag: opt ? (opt.withTag ? true : false) : false,
adReply: opt ? (opt.adReply ? true : false) : false,
}, {
...opt
}
);
};
conn.getName = (jid, withoutContact = false) => {
id = conn.decodeJid(jid);
withoutContact = conn.withoutContact || withoutContact;
let v;
if (id.endsWith("@g.us"))
return new Promise(async (resolve) => {
v = store.contacts[id] || {};
if (!(v.name || v.subject)) v = conn.groupMetadata(id) || {};
resolve(
v.name ||
v.subject ||
require("awesome-phonenumber")("+" + id.replace("@s.whatsapp.net", "")).getNumber(
"international"
)
);
});
else
v =
id === "[email protected]"
? {
id,
name: "WhatsApp",
}
: id === conn.decodeJid(conn.user.id)
? conn.user
: store.contacts[id] || {};
return (
(withoutContact ? "" : v.name) ||
v.subject ||
v.verifiedName ||
require("awesome-phonenumber")("+" + jid.replace("@s.whatsapp.net", "")).getNumber("international")
);
};
conn.getBuffer = async (url, options) => {
try {
options ? options : {};
const res = await require("axios")({
method: "get",
url,
headers: {
DNT: 1,
"Upgrade-Insecure-Request": 1,
},
...options,
responseType: "arraybuffer",
});
return res.data;
} catch (e) {
console.log(`Error : ${e}`);
}
};
conn.sendContact = async (jid, contact, quoted = false, opts = {}) => {
let list = [];
for (let i of contact) {
num = typeof i == "number" ? i + "@s.whatsapp.net" : i;
num2 = typeof i == "number" ? i : i.split("@")[0];
list.push({
displayName: await conn.getName(num),
vcard: `BEGIN:VCARD\nVERSION:3.0\nFN:${await conn.getName(
num
)}\nFN:${await conn.getName(
num
)}\nitem1.TEL;waid=${num2}:${num2}\nitem1.X-ABLabel:Ponsel\nitem2.EMAIL;type=INTERNET:${config.email
}\nitem2.X-ABLabel:Email\nitem3.URL:${config.instagram
}\nitem3.X-ABLabel:Instagram\nitem4.ADR:;;Indonesia;;;;\nitem4.X-ABLabel:Region\nEND:VCARD`,
});
}
return conn.sendMessage(
jid, {
contacts: {
displayName: `${list.length} Kontak`,
contacts: list,
},
...opts,
}, {
quoted
}
);
};
conn.sendSticker = async (jid, url, quoted, option = {}) => {
let ext;
let buf = url;
if (!Buffer.isBuffer(url)) buf = await conn.getBuffer(url);
if (!Buffer.isBuffer(url)) ext = await fromBuffer(buf);
if (Buffer.isBuffer(url)) ext = await fromBuffer(buf);
url =
ext == "mp4" ?
await convert2(
buf,
ext.ext,
"webp",
cmd[parseInt(option.cmdType ? option.cmdType : 1)]
) :
await convert(
buf,
ext.ext,
"webp",
cmd[parseInt(option.cmdType ? option.cmdType : 1)]
);
let sticker = {
url
};
return conn.sendMessage(jid, {
sticker: url,
...option
}, {
quoted
});
};
conn.logger = {
...conn.logger,
info(...args) {
console.log(
chalk.bold.rgb(
57,
183,
16
)(
`INFO [${chalk.rgb(
255,
255,
255
)(moment(Date.now()).format(" dddd, DD MMMM YYYY HH:mm:ss "))}]`
),
chalk.cyan(...args)
);
},
error(...args) {
console.log(
chalk.bold.rgb(
247,
38,
33
)(
`ERROR [${chalk.rgb(
255,
255,
255
)(moment(Date.now()).format(" dddd, DD MMMM YYYY HH:mm:ss "))}]:`
),
chalk.rgb(255, 38, 0)(...args)
);
},
warn(...args) {
console.log(
chalk.bold.rgb(
239,
225,
3
)(
`WARNING [${chalk.rgb(
255,
255,
255
)(moment(Date.now()).format(" dddd, DD MMMM YYYY HH:mm:ss "))}]:`
),
chalk.keyword("orange")(...args)
);
},
};
conn.sendReact = async (jid, emoticon, keys = {}) => {
let reactionMessage = {
react: {
text: emoticon,
key: keys
}
}
return await conn.sendMessage(jid, reactionMessage)
};
conn.sendGroupV4Invite = async (jid, participant, inviteCode, inviteExpiration, groupName = "unknown subject", jpegThumbnail, caption = "Invitation to join my WhatsApp group", options = {}) => {
let msg = Baileys.proto.Message.fromObject({
groupInviteMessage: Baileys.proto.GroupInviteMessage.fromObject({
inviteCode,
inviteExpiration: inviteExpiration ?
parseInt(inviteExpiration) :
+new Date(new Date() + 3 * 86400000),
groupJid: jid,
groupName: groupName ? groupName : (await conn.groupMetadata(jid)).subject,
jpegThumbnail,
caption,
}),
});
const ms = Baileys.generateWAMessageFromContent(participant, msg, options);
await conn.relayMessage(participant, ms.message, {
messageId: ms.key.id,
});
};
conn.sendImage = async (jid, url, quoted, option = {}) => {
let ext;
let buf = url;
if (!Buffer.isBuffer(url)) buf = await conn.getBuffer(url);
if (!Buffer.isBuffer(url)) ext = await fromBuffer(buf);
if (Buffer.isBuffer(url)) ext = await fromBuffer(buf);
let type = /jpg|png|webp/i.test(ext.ext);
if (!type) return ReferenceError(`Format file invalid`);
url = buf;
return conn.sendMessage(jid, {
image: url,
...option
}, {
quoted
});
};
conn.sendVideo = async (jid, url, quoted, option = {}) => {
let ext;
let buf = url;
if (!Buffer.isBuffer(url)) buf = await conn.getBuffer(url);
if (!Buffer.isBuffer(url)) ext = await fromBuffer(buf);
if (Buffer.isBuffer(url)) ext = await fromBuffer(buf);
let type = /gif|webm|mp4/i.test(ext.ext);
if (!type) return ReferenceError(`Format file invalid`);
url = ext.ext !== "mp4" ? await convert(buf, ext.ext, "mp4", cmd[parseInt(option.cmdType ? option.cmdType : 1)]) : buf;
return conn.sendMessage(jid, { video: url, ...option, mimetype: ext.mimetype }, { quoted });
};
conn.sendAudio = async (jid, url, quoted, ptt = false, option = {}) => {
let ext;
let buf = url;
if (!Buffer.isBuffer(url)) buf = await conn.getBuffer(url);
if (!Buffer.isBuffer(url)) ext = await fromBuffer(buf);
if (Buffer.isBuffer(url)) ext = await fromBuffer(buf);
let type = /mp3|wav|opus|m4a/i.test(ext.ext);
if (!type) return ReferenceError(`Format file invalid`);
url = ext.ext !== "mp3" ? await convert(buf, ext.ext, "mp3", cmd[parseInt(option.cmdType ? option.cmdType : 1)]) : buf;
return conn.sendFile(msg.from, url, Date.now() / 1000 + ext.ext, "", quoted, ptt);
};
conn.sendFileFromUrl = async (from, url, opt, opt1) => {
let mime = "";
let res = await axios.head(url);
mime = res.headers["content-type"];
let type = mime.split("/");
if (mime.includes("image")) type = "image";
else if (mime.includes("video")) type = "video";
else if (mime.split("/")[0] === "audio") type = "audio";
else type = "document";
//else if(mime === "application/pdf") type = 'document'
return await conn.sendMessage(
from, {
[type]: await tool.getBuffer(url),
...opt
}, {
...opt1
}
);
};
conn.sendFile = async (jid, path, filename = "", caption = "", quoted, ptt = false, options = {}) => {
let type = await conn.getFile(path, true);
let { res, data: file, filename: pathFile } = type;
if ((res && res.status !== 200) || file.length <= 65536) {
try {
throw { json: JSON.parse(file.toString()) };
} catch (e) {
if (e.json) throw e.json;
}
}
let opt = { filename };
if (quoted) opt.quoted = quoted;
if (!type) if (options.asDocument) options.asDocument = true;
let mtype = "",
mimetype = type.mime;
let naem = (a) => "./temp/" + Date.now() + "." + a;
if (/webp/.test(type.mime)) mtype = "sticker";
else if (/image/.test(type.mime)) mtype = "image";
else if (/video/.test(type.mime)) mtype = "video";
else if (/audio/.test(type.mime))
(ss = await (ptt ? toPTT : toAudio2)(file, type.ext)),
(skk = await require("file-type").fromBuffer(ss.data)),
(ty = naem(skk.ext)),
require("fs").writeFileSync(ty, ss.data),
(pathFile = ty),
(mtype = "audio"),
(mimetype = "audio/mpeg");
else mtype = "document";
conn.sendMessage(jid, { ...options, caption, ptt, fileName: filename, [mtype]: { url: pathFile }, mimetype, }, { ...opt, ...options, })
.then(() => {
fs.unlinkSync(pathFile);
conn.logger.info("delete file " + pathFile);
});
};
conn.reply = async (jid, text, quoted, options) => {
return conn.sendMessage(jid, {
text: text,
mentions: parseMention(text),
...options
}, {
quoted
})
};
if (msg.key) {
msg.id = msg.key.id;
msg.isSelf = msg.key.fromMe;
msg.from = msg.key.remoteJid;
msg.isGroup = msg.from.endsWith("@g.us");
msg.sender = msg.isGroup ? conn.decodeJid(msg.key.participant) : msg.isSelf ? conn.decodeJid(conn.user.id) : msg.from;
}
if (msg.message) {
msg.type = getContentType(msg.message);
if (msg.type === "ephemeralMessage") {
msg.message = msg.message[msg.type].message;
const tipe = Object.keys(msg.message)[0];
msg.type = tipe;
if (tipe === "viewOnceMessage") {
msg.message = msg.message[msg.type].message;
msg.type = getContentType(msg.message);
}
}
if (msg.type === "viewOnceMessage") {
msg.message = msg.message[msg.type].message;
msg.type = getContentType(msg.message);
}
try {
msg.mentions = msg.message[msg.type].contextInfo ? msg.message[msg.type].contextInfo.mentionedJid || [] : [];
} catch {
msg.mentions = [];
}
try {
const quoted = msg.message[msg.type].contextInfo;
if (quoted.quotedMessage["ephemeralMessage"]) {
const tipe = Object.keys(quoted.quotedMessage.ephemeralMessage.message)[0];
if (tipe === "viewOnceMessage") {
msg.quoted = {
type: "view_once",
stanzaId: quoted.stanzaId,
sender: conn.decodeJid(quoted.participant),
message: quoted.quotedMessage.ephemeralMessage.message.viewOnceMessage.message,
};
} else {
msg.quoted = {
type: "ephemeral",
stanzaId: quoted.stanzaId,
sender: conn.decodeJid(quoted.participant),
message: quoted.quotedMessage.ephemeralMessage.message,
};
}
} else if (quoted.quotedMessage["viewOnceMessage"]) {
msg.quoted = {
type: "view_once",
stanzaId: quoted.stanzaId,
sender: conn.decodeJid(quoted.participant),
message: quoted.quotedMessage.viewOnceMessage.message,
};
} else {
msg.quoted = {
type: "normal",
stanzaId: quoted.stanzaId,
sender: conn.decodeJid(quoted.participant),
message: quoted.quotedMessage,
};
}
msg.quoted.isSelf = msg.quoted.sender === conn.decodeJid(conn.user.id);
msg.quoted.mtype = Object.keys(msg.quoted.message).filter((v) => v.includes("Message") || v.includes("conversation"))[0];
msg.quoted.text =
msg.quoted.message[msg.quoted.mtype].text ||
msg.quoted.message[msg.quoted.mtype].description ||
msg.quoted.message[msg.quoted.mtype].caption ||
(msg.quoted.mtype == "templateButtonReplyMessage" &&
msg.quoted.message[msg.quoted.mtype].selectedDisplayText) ||
msg.quoted.message[msg.quoted.mtype] ||
"";
msg.quoted.key = {
id: msg.quoted.stanzaId,
fromMe: msg.quoted.isSelf,
remoteJid: msg.from,
};
msg.quoted.isBot = (msg.quoted.key.id.startsWith("BAE5") && msg.quoted.key.id.length == 16) || (msg.quoted.key.id.startsWith("3EB0") && msg.quoted.key.id.length == 20) ?
true :
false;
msg.quoted.delete = () => conn.sendMessage(msg.from, { delete: msg.quoted.key });
msg.quoted.download = (pathFile) => downloadMedia(msg.quoted.message, pathFile);
msg.quoted.copyNForward = async (jid = msg.from, forceForward = false, opt) => conn.copyNForward(jid, await msg.getQuotedObj(), forceForward, opt);
msg.quoted.react = async (react) => {
return await conn.sendMessage(msg.from, {
react: {
text: react,
key: msg.quoted.key
},
});
};
} catch (e) {
msg.quoted = null;
}
try {
msg.body =
msg.message.conversation ||
msg.message[msg.type].text ||
msg.message[msg.type].caption ||
(msg.type === "listResponseMessage" &&
msg.message[msg.type].singleSelectReply.selectedRowId) ||
(msg.type === "buttonsResponseMessage" &&
msg.message[msg.type].selectedButtonId &&
msg.message[msg.type].selectedButtonId) ||
(msg.type === "templateButtonReplyMessage" &&
msg.message[msg.type].selectedId) ||
"";
} catch {
msg.body = "";
}
const contentQ = msg.quoted ? JSON.stringify(msg.quoted) : []
msg.attribute = {
isOwner: owner.includes(msg.sender),
isBot: (msg.key.id.startsWith("BAE5") && msg.key.id.length == 16) || (msg.key.id.startsWith("3EB0") && msg.key.id.length == 20) ? true : false,
isVideo: msg.type === "videoMessage",
isImage: msg.type === "imageMessage",
isLocation: msg.type === "locationMessage",
isMedia: msg.type === "imageMessage" || msg.type === "videoMessage",
isQAudio: msg.type === "extendedTextMessage" && contentQ.includes("audioMessage"),
isQVideo: msg.type === "extendedTextMessage" && contentQ.includes("videoMessage"),
isQImage: msg.type === "extendedTextMessage" && contentQ.includes("imageMessage"),
isQDocument: msg.type === "extendedTextMessage" && contentQ.includes("documentMessage"),
isQSticker: msg.type === "extendedTextMessage" && contentQ.includes("stickerMessage"),
isQLocation: msg.type === "extendedTextMessage" && contentQ.includes("locationMessage")
}
msg.user = {
id: msg.sender,
device: msg.attribute.isBot ? 'web' : 'smartphone',
jadibot: conn.id ? true : false
}
msg.getQuotedObj = msg.getQuotedMessage = async () => {
if (!msg.quoted.stanzaId) return false;
let q = await store.loadMessage(msg.from, msg.quoted.stanzaId, conn);
return serialize(q, conn);
};
msg.react = async (react) => {
return await conn.sendMessage(msg.from, {
react: {
text: react,
key: msg.key
},
});
};
msg.copyNForward = (jid = msg.from, forceForward = false, opt) => conn.copyNForward(jid, msg, forceForward, opt);
msg.reply = async (text, opt = {adReply:true}) => {
return await conn.sendMessage(msg.from, {
text: require("util").format(text),
mentions: opt ?
opt.withTag ?
[...text.matchAll(/@([0-9]{5,16}|0)/g)].map(
(v) => v[1] + "@s.whatsapp.net"
) :
[] :
[],
...opt,
}, {
...opt,
quoted: msg
}
);
};
msg.download = (pathFile) => downloadMedia(msg.message, pathFile);
}
return msg;
}
module.exports = {
serialize,
downloadMedia
};
let file = require.resolve(__filename);
fs.watchFile(file, () => {
fs.unwatchFile(file);
console.log("Update 'serialize.js'");
delete require.cache[file];
});
//hit
const { Low, JSONFile } = require("./lowdb");
const hit = new Low(new JSONFile("database/json/hit.json"));
async function showhit(cmd) {
await hit.read();
return cmd == "" || cmd == undefined ? hit.data : hit.data[cmd];
}
async function addhit(cmd, success) {
const before = await showhit(cmd);
await hit.read();
if (before == undefined) {
hit.data[cmd] = {
cmd: cmd,
timestamp: Date.now(),
total: 1,
success: 0,
failed: 0,
};
if (success) hit.data[cmd].success++;
else hit.data[cmd].failed++;
await hit.write();
} else {
hit.data[cmd].timestamp = Date.now();
hit.data[cmd].total++;
if (success) hit.data[cmd].success++;
else hit.data[cmd].failed++;
await hit.write();
}
}
module.exports = { addhit, showhit };
// database.js
const { Low, JSONFile } = require("./lowdb");
async function showdb(database, data) {
const db = new Low(new JSONFile(`database/json/${database}.json`));
await db.read();
return db.data[data];
}
module.exports = { showdb };
// converter
const fs = require("fs");
const path = require("path");
const { spawn } = require("child_process");
function ffmpeg(buffer, args = [], ext = "", ext2 = "") {
return new Promise(async (resolve, reject) => {
try {
let tmp = path.join(__dirname, "../temp", +new Date() + "." + ext);
let out = tmp + "." + ext2;
await fs.promises.writeFile(tmp, buffer);
spawn("ffmpeg", ["-y", "-i", tmp, ...args, out])
.on("error", reject)
.on("close", async (code) => {
try {
await fs.promises.unlink(tmp);
if (code !== 0) return reject(code);
resolve(await fs.promises.readFile(out));
await fs.promises.unlink(out);
} catch (e) {
reject(e);
}
});
} catch (e) {
reject(e);
}
});
}
/**
* Convert Audio to Playable WhatsApp Audio
* @param {Buffer} buffer Audio Buffer
* @param {String} ext File Extension
*/
function toPTT(buffer, ext) {
return ffmpeg(
buffer,
["-vn", "-c:a", "libopus", "-b:a", "128k", "-vbr", "on"],
ext,
"ogg"
);
}
/**
* Convert Audio to Playable WhatsApp PTT
* @param {Buffer} buffer Audio Buffer
* @param {String} ext File Extension
*/
function toAudio(buffer, ext) {
return ffmpeg(
buffer,
[
"-vn",
"-c:a",
"libopus",
"-b:a",
"128k",
"-vbr",
"on",
"-compression_level",
"10",
],
ext,
"opus"
);
}
/**
* Convert Audio to Playable WhatsApp Video
* @param {Buffer} buffer Video Buffer
* @param {String} ext File Extension
*/
function toVideo(buffer, ext) {
return ffmpeg(
buffer,
[
"-c:v",
"libx264",
"-c:a",
"aac",
"-ab",
"128k",
"-ar",
"44100",
"-crf",
"32",
"-preset",
"slow",
],
ext,
"mp4"
);
}
module.exports = {
toAudio,
toPTT,
toVideo,
ffmpeg,
};
//convert
const ffmpeg = require("fluent-ffmpeg");
const fs = require("fs");
const path = require("path");
const run = require("child_process").exec;
const Exif = require("./exif");
const ex = new Exif();
function convert(file, ext1, ext2, options = []) {
return new Promise(async (resolve, reject) => {
let temp = path.join(__dirname, "../temp", Date.now() + "." + ext1),
out = temp + "." + ext2;
await fs.promises.writeFile(temp, file);
ffmpeg(temp)
.on("start", (cmd) => {
console.log(cmd);
})
.on("error", (e) => {
fs.unlinkSync(temp);
reject(e);
})
.on("end", async() => {
console.log("Finish");
/*setTimeout(() => {
fs.unlinkSync(temp);
fs.unlinkSync(out);
}, 2000);*/
const ret = await fs.readFileSync(out)
fs.unlinkSync(temp);
fs.unlinkSync(out);
resolve(ret);
})
.addOutputOptions(options)
.toFormat(ext2)
.save(out);
});
}
function convert2(file, ext1, ext2, options = []) {
return new Promise(async (resolve, reject) => {
let temp = path.join(__dirname, "../temp", Date.now() + "." + ext1),
out = temp + "." + ext2;
await fs.promises.writeFile(temp, file);
ffmpeg(temp)
.on("start", (cmd) => {
console.log(cmd);
})
.on("error", (e) => {
fs.unlinkSync(temp);
reject(e);
})
.on("end", () => {
console.log("Finish");
setTimeout(() => {
fs.unlinkSync(temp);
fs.unlinkSync(out);
}, 2000);
resolve(fs.readFileSync(out));
})
.addOutputOptions(options)
.seekInput("00:00")
.setDuration("00:05")
.toFormat(ext2)
.save(out);
});
}
async function WAVideo(file, ext1) {
return convert(file, ext1, "mp4", [
"-c:a aac",
"-c:v libx264",
"-b:a 128K",
"-ar 44100",
"-crf 28",
"-preset slow",
]);
}
async function WAAudio(file, ext1) {
return convert(file, ext1, "mp3", ["-vn", "-b:a 192K", "-ar 44100", "-ac 2"]);
}
async function WAOpus(file, ext1) {
return convert(file, ext1, "opus", [
"-vn",
"-c:a libopus",
"-b:a 128K",
"-vbr on",
"-compression_level 10",
]);
}
async function sticker(file, opts) {
if (typeof opts.cmdType === "undefined") opts.cmdType = "1";
const cmd = {
1: [
"-fs 1M",
"-vcodec",
"libwebp",
"-vf",
`scale=512:512:flags=lanczos:force_original_aspect_ratio=decrease,format=rgba,pad=512:512:(ow-iw)/2:(oh-ih)/2:color=#00000000,setsar=1`,
],
2: ["-fs 1M", "-vcodec", "libwebp"],
};
if (opts.withPackInfo) {
if (!opts.packInfo)
throw Error("'packInfo' must be filled when using 'withPackInfo'");
let ext =
opts.isImage !== undefined || false
? "jpg"
: opts.isVideo !== undefined || false
? "mp4"
: null;
return stickerWithExif(file, ext, opts.packInfo, cmd[parseInt(opts.cmdType)]);
}
if (opts.isImage) {
return convert(file, "jpg", "webp", cmd[parseInt(opts.cmdType)]);
}
if (opts.isSticker) {
return convert(file, "webp", "webp", cmd[parseInt(opts.cmdType)]);
}
if (opts.isVideo) {
return convert2(file, "mp4", "webp", cmd[parseInt(opts.cmdType)]);
}
}
function stickerWithExif(file, ext, packInfo, cmd) {
return new Promise(async (res, rej) => {
let { packname, author } = packInfo;
const filename = Date.now();
const stickerBuffer =
ext === "jpg"
? await convert(file, ext, "webp", cmd)
: await convert2(file, ext, "webp", cmd);
ex.create(
packname !== undefined || "" ? packname : "Original",
author !== undefined || "" ? author : "Rzky-Bot",
filename
);
await fs.promises.writeFile(`./temp/${filename}.webp`, stickerBuffer);
run(`webpmux -set exif ./temp/${filename}.exif ./temp/${filename}.webp -o ./temp/${filename}.webp`, async (err) => {
//exec(`webpmux -set exif ./media/sticker/data.exif ./${rand2} -o ./${rand2}`,
if (err)
rej(err) &&
(await Promise.all([
fs.unlink(`./temp/${filename}.webp`),
fs.unlink(`./temp/${filename}.exif`),
]));
setTimeout(() => {
fs.unlinkSync(`./temp/${filename}.exif`);
fs.unlinkSync(`./temp/${filename}.webp`);
}, 2000);
res(fs.readFileSync(`./temp/${filename}.webp`));
}
);
});
}
module.exports = {
toVideo: WAVideo,
toAudio: WAAudio,
toOpus: WAOpus,
sticker,
convert,
convert2,
};
//exif
/* Originally created by cwke
* Reuploaded by Waxaranai
* Recoded by SlavyanDesu
*
* GitHub is an open-source community, so why are you so triggered when someone shared some simple code?
*/
const fs = require("fs");
const packID =
"com.snowcorp.stickerly.android.stickercontentprovider b5e7275f-f1de-4137-961f-57becfad34f2";
const playstore = "";
const itunes = "";
/**
* @class Exif
*/
module.exports = class Exif {
constructor() {}
/**
* Create an EXIF file.
* @param {String} packname
* @param {String} authorname
* @param {String} filename
*/
/*create(packname, authorname, filename) {
if (!filename) filename = "data";
const json = {
"sticker-pack-id": packID,
"sticker-pack-name": packname,
"sticker-pack-publisher": authorname,
"android-app-store-link": playstore,
"ios-app-store-link": itunes,
emojis: ["š"],
};
let len = new TextEncoder().encode(JSON.stringify(json)).length;
const f = Buffer.from([
0x49, 0x49, 0x2a, 0x00, 0x08, 0x00, 0x00, 0x00, 0x01, 0x00, 0x41, 0x57, 0x07,
0x00,
]);
const code = [0x00, 0x00, 0x16, 0x00, 0x00, 0x00];
if (len > 256) {
len = len - 256;
code.unshift(0x01);
} else {
code.unshift(0x00);
}
const fff = Buffer.from(code);
const ffff = Buffer.from(JSON.stringify(json));
if (len < 16) {
len = len.toString(16);
len = "0" + len;
} else {
len = len.toString(16);
}
const ff = Buffer.from(len, "hex");
const buffer = Buffer.concat([f, ff, fff, ffff]);
fs.writeFile(`./temp/${filename}.exif`, buffer, (err) => {
if (err) return console.error(err);
console.log("Success!");
});
}
*/
create(packname, authorname, filename) {
if (!filename) filename = "data";
const json = {
"sticker-pack-id": packID,
"sticker-pack-name": packname,
"sticker-pack-publisher": authorname,
"android-app-store-link": playstore,
"ios-app-store-link": itunes,
emojis: ["š"],
};
const data = JSON.stringify(json)
const exif = Buffer.concat([
Buffer.from([
0x49, 0x49, 0x2a, 0x00, 0x08, 0x00, 0x00, 0x00, 0x01, 0x00, 0x41, 0x57, 0x07, 0x00, 0x00, 0x00, 0x00,
0x00, 0x16, 0x00, 0x00, 0x00
]),
Buffer.from(data, 'utf-8')
])
exif.writeUIntLE(new TextEncoder().encode(data).length, 14, 4)
fs.writeFile(`./temp/${filename}.exif`, exif, (err) => {
if (err) return console.error(err);
console.log("Success!");
});
}
};