-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.js
444 lines (412 loc) · 13.3 KB
/
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
const {
fetchLatestBaileysVersion,
makeInMemoryStore,
default: Baileys,
useMultiFileAuthState,
jidDecode,
DisconnectReason,
delay,
} = require("@adiwajshing/baileys");
const log = (pino = require("pino"));
const attribute = {};
const fs = require("fs");
const path = require("path");
const { Boom } = require("@hapi/boom");
const { color } = require("./lib");
const { session } = require("./config.json");
const handler = require("./handler");
const WelcomeHandler = require("./lib/welcome");
const utils = require("./utils");
const cron = require("node-cron");
const Spinnies = require("spinnies");
const spinnies = new Spinnies({
spinner: {
interval: 200,
frames: ["∙∙∙", "●∙∙", "∙●∙", "∙∙●", "∙∙∙"],
},
});
const moment = require("moment");
const { self } = require("./config.json");
const { state, saveState } = useMultiFileAuthState(__dirname +`/auth_info_baileys/`)//, log({ level: "silent" }));
attribute.prefix = "#";
// Set country code
moment.tz.setDefault(config.timezone).locale(config.locale);
global.moment = moment;
// page anime search
attribute.page = new Map();
// uptime
attribute.uptime = new Date();
// sesu pdf
attribute.pdf = new Map();
// command
attribute.command = new Map();
// database game
global.addMap = (x) => {
attribute[x] = new Map();
};
// lock cmd
attribute.lockcmd = new Map();
// self
attribute.isSelf = self;
// store
global.store = makeInMemoryStore({ logger: pino().child({ level: "silent", stream: "store" }) });
// Delete database chat
const chatsData = cron.schedule(
"*/10 * * * *", // 10 minutes per delete
() => {
try {
fs.rmSync(path.join(__dirname, "database", "mess.json"));
db.addDatabase("mess", "[]");
console.log(color("[ INFO ]", "aqua"), "Delete Database Chat, Cache Temp");
file = fs.readdirSync("./temp").map((a) => "./temp/" + a);
file.map((a) => fs.unlinkSync(a));
} catch (e) {
console.log(e);
}
},
{ scheduled: true, timezone: config.timezone }
);
const limitData = cron.schedule(
"0 0 * * *", // 00 hours per delete
() => {
try {
limit.splice("reset");
fs.writeFileSync("./database/limit.json", JSON.stringify(limit, null, 2));
console.log(color("[ INFO ]", "aqua"), "Reset Limit all");
} catch (e) {
console.log(e);
}
},
{ scheduled: true, timezone: config.timezone }
);
let data = fs.readFileSync(path.join(__dirname, "doom.flf"), "utf8");
require("figlet").parseFont("doom", data);
require("figlet").text(
"CORTANA MD",
{
font: "doom",
horizontalLayout: "default",
verticalLayout: "default",
width: 80,
whitespaceBreak: true,
},
function (err, data) {
if (err) {
console.log("Something went wrong...");
console.dir(err);
return;
}
console.clear();
console.log(color(data, "cyan"));
}
);
const ReadFitur = () => {
let pathdir = path.join(__dirname, "./command");
let fitur = fs.readdirSync(pathdir);
spinnies.add("spinner-1", { text: "Loading commands..", color: "green" });
fitur.forEach(async (res) => {
const commands = fs.readdirSync(`${pathdir}/${res}`).filter((file) => file.endsWith(".js"));
for (let file of commands) {
const command = require(`${pathdir}/${res}/${file}`);
if (typeof command.run != "function") continue;
const cmdOptions = {
name: "command",
alias: [""],
desc: "",
use: "",
cooldown: 5,
type: "", // default: changelog
category: typeof command.category == "undefined" ? "" : res.toLowerCase(),
wait: false,
isOwner: false,
isAdmin: false,
isQuoted: false,
isGroup: false,
isBotAdmin: false,
query: false,
isPrivate: false,
isLimit: false,
isLimitGame: false,
isSpam: false,
noPrefix: false,
isMedia: {
isQVideo: false,
isQAudio: false,
isQImage: false,
isQSticker: false,
isQDocument: false,
},
isPremium: false,
disable: false,
isUrl: false,
run: () => {},
};
let cmd = utils.parseOptions(cmdOptions, command);
let options = {};
for (var k in cmd)
typeof cmd[k] == "boolean"
? (options[k] = cmd[k])
: k == "query" || k == "isMedia"
? (options[k] = cmd[k])
: "";
let cmdObject = {
name: cmd.name,
alias: cmd.alias,
desc: cmd.desc,
use: cmd.use,
type: cmd.type,
category: cmd.category,
options: options,
run: cmd.run,
};
attribute.command.set(cmd.name, cmdObject);
require("delay")(100);
global.reloadFile(`./command/${res}/${file}`);
}
});
spinnies.succeed("spinner-1", { text: "Commands loaded successfully", color: "yellow" });
};
// cmd
ReadFitur();
const connect = async () => {
let { version, isLatest } = await fetchLatestBaileysVersion();
console.log(color(`Using: ${version}, newer: ${isLatest}`, "yellow"));
const conn = Baileys({
printQRInTerminal: true,
auth: state,
logger: log({ level: "silent" }),
version,
});
// start
chatsData.start();
limitData.start();
// game data
conn.game = conn.game ? conn.game : {};
const 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;
};
const 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}`);
}
};
store.bind(conn.ev);
ikyEvent.on("viewOnceMessage", async (get) => {
await conn.sendMessage(
get.remoteJid,
{ text: `@${get.participant.split("@")[0]} Terdeteksi Mengirim view once...`, withTag: true },
{ quoted: get.message }
);
await conn.sendMessage(get.remoteJid, { forward: get.message }, { quoted: get.message });
});
conn.ev.on("creds.update", saveState);
conn.ev.on("connection.update", async (up) => {
const { lastDisconnect, connection } = up;
if (connection) spinnies.add("spinner-2", { text: "Cortana Md is connecting now... please wait...", color: "cyan" });
if (connection == "connecting")
spinnies.add("spinner-2", { text: "Cortana MD is trying to link to the host WhatsApp now...", color: "cyan" });
if (connection) {
if (connection != "connecting")
spinnies.update("spinner-2", { text: "Connection: " + connection, color: "yellow" });
}
if (connection == "open")
spinnies.succeed("spinner-2", { text: "Cortana MD Successfully connected to whatsapp... Check if it is working", color: "green" });
if (connection === "close") {
let reason = new Boom(lastDisconnect.error).output.statusCode;
if (reason === DisconnectReason.badSession) {
console.log(`Bad Session File, Please Delete ${session} and Scan Again`);
conn.logout();
} else if (reason === DisconnectReason.connectionClosed) {
console.log("Connection closed, reconnecting....");
connect();
} else if (reason === DisconnectReason.connectionLost) {
console.log("Connection Lost from Server, reconnecting...");
connect();
} else if (reason === DisconnectReason.connectionReplaced) {
console.log("Connection Replaced, Another New Session Opened, Please Close Current Session First");
conn.logout();
} else if (reason === DisconnectReason.loggedOut) {
console.log(`Device Logged Out, Please Delete ${session} and Scan Again.`);
conn.logout();
} else if (reason === DisconnectReason.restartRequired) {
console.log("Restart Required, Restarting...");
connect();
} else if (reason === DisconnectReason.timedOut) {
console.log("Connection TimedOut, Reconnecting...");
connect();
} else {
conn.end(`Unknown DisconnectReason: ${reason}|${lastDisconnect.error}`);
}
}
});
//mager
conn.addMessage = (msg, type) => {
if (type == "protocolMessage") return;
let from = msg.key.remoteJid;
return db.modified("mess", { id: msg.key.id, msg });
};
//anticall
conn.ws.on("CB:call", async (json) => {
if (json.content[0].tag == "offer") {
conn.sendMessage(json.content[0].attrs["call-creator"], {
text: `You called the bot! 😡\nYou will have to contact my owner for you to be unblocked! 🥷\n\nOwner Number: \n${config.owner
.map(
(a) =>
`*wa.me/${a.split(`@`)[0]}* | ${
conn.getName(a).includes("+62") ? "No Detect" : conn.getName(a)
}`
)
.join("\n")}`,
});
await require("delay")(8000);
await conn.updateBlockStatus(json.content[0].attrs["call-creator"], "block");
}
});
//contact update
conn.ev.on("contacts.update", (m) => {
for (let kontak of m) {
let jid = decodeJid(kontak.id);
if (store && store.contacts) store.contacts[jid] = { jid, name: kontak.notify };
}
});
// I don't know what's the point hehe
if (!fs.existsSync("./src") || !fs.existsSync("./src/rzky-md.jpg")) {
fs.mkdir("./src", async function (err) {
if (err) {
if (!fs.existsSync("./src/rzky-md.jpg")) {
fs.writeFile("./src/rzky-md.jpg", (await require("axios")(config.thumb)).data, function (err) {
if (err) {
console.log(color("[INFO]", "yellow"), "error writing file", err);
} else {
console.log(color("[INFO]", "yellow"), "writing thumbnail succeeded");
}
});
}
fs.existsSync("./src/rzky-md.jpg")
? console.log(color("[INFO]", "yellow"), "failed to create directory", err)
: "";
} else {
console.log(color("[INFO]", "yellow"), `Success in creating a "src" file`);
fs.writeFile("./src/rzky-md.jpg", (await require("axios")(config.thumb)).data, function (err) {
if (err) {
console.log(color("[INFO]", "yellow"), "error writing file", err);
} else {
console.log(color("[INFO]", "yellow"), "writing thumbnail succeeded");
}
});
}
});
}
// detect Reaction message
conn.ev.on("messages.reaction", async (m) => {
if (m.reaction.key.id.startsWith("BAE5") && m.reaction.key.id.length === 16) return;
let mesg = await store.loadMessage(m.reaction.key.remoteJid, m.key.id, conn);
let frem = m.reaction.key.remoteJid.endsWith("@g.us") ? m.reaction.key.participant : m.reaction.key.remoteJid;
let frum = m.key.remoteJid.endsWith("@g.us") ? m.key.participant : m.key.remoteJid;
await conn.sendMessage(
m.reaction.key.remoteJid,
{
text: `*【 ${m.operation == "add" ? "ADD" : "DELETE"} REACTION 】*\n\n*_Tagged:_* @${
(m.reaction.key.fromMe ? decodeJid(conn.user.id) : decodeJid(frem)).split("@")[0]
}\n*_To:_* ${frum ? `@${frum.split("@")[0]}` : `-`}\n*_Emoji:_* ${
m.operation == "add" ? m.reaction.text : "-"
}`,
withTag: true,
},
{ quoted: mesg }
);
});
// detect group update
conn.ev.on("groups.update", async (json) => {
const res = json[0];
if (res.announce == true) {
conn.sendMessage(res.id, {
text: `「 Group Settings Change 」\n\nGroup settings changed, Only Admins can message as you can see !😂`,
});
} else if (res.announce == false) {
conn.sendMessage(res.id, {
text: `「 Group Settings Change 」\n\nGroup settings changed, Everyone can message now! 🌚`,
});
} else if (res.restrict == true) {
conn.sendMessage(res.id, {
text: `「 Group Settings Change 」\n\nAnyone can edit group info! 🌚`,
});
} else if (res.restrict == false) {
conn.sendMessage(res.id, {
text: `「 Group Settings Change 」\n\nOnly Admins can edit group info! 😌`,
});
} else {
conn.sendMessage(res.id, {
text: `「 Group Settings Change 」\n\nGroup Subject has been changed to *${res.subject}*`,
});
}
});
// Anti delete dek
conn.ev.on("message.delete", async (m) => {
if (!m) m = {};
let data2 = db.cekDatabase("antidelete", "id", m.remoteJid || "");
if (typeof data2 != "object") return;
const dataChat = JSON.parse(fs.readFileSync("./database/mess.json"));
let mess = dataChat.find((a) => a.id == m.id);
let mek = mess.msg;
if (mek.key.id.startsWith("BAE5") && mek.key.id.length === 16) return;
let participant = mek.key.remoteJid.endsWith("@g.us")
? decodeJid(mek.key.participant)
: decodeJid(mek.key.remoteJid);
let froms = mek.key.remoteJid;
await conn.sendMessage(
froms,
{
text:
"Why delete that message? 🙄 @" +
participant.split("@")[0] +
`\n\n*➤ Info*\n*• Participant:* ${participant.split("@")[0]}\n*• Message Deleted:* ${moment(
Date.now()
).format("dddd, DD/MM/YYYY HH:mm:ss")}\n*• Message sent:* ${moment(
mek.messageTimestamp * 1000
).format("dddd, DD/MM/YYYY HH:mm:ss")}\n*• Type:* ${Object.keys(mek.message)[0]}`,
mentions: [participant],
},
{ quoted: mek }
);
await conn.relayMessage(froms, mek.message, { messageId: mek.key.id });
});
// welcome
conn.ev.on("group-participants.update", async (msg) => {
WelcomeHandler(conn, msg);
});
// messages.upsert
conn.ev.on("messages.upsert", async (m) => {
const msg = m.messages[0];
if (msg.key.id.startsWith("BAE5") && msg.key.id.length === 16) return;
const type = msg.message ? Object.keys(msg.message)[0] : "";
let dataCek = db.cekDatabase("antidelete", "id", msg.key.remoteJid);
if (dataCek) conn.addMessage(msg, type);
if (msg && type == "protocolMessage") conn.ev.emit("message.delete", msg.message.protocolMessage.key);
handler(m, conn, attribute);
});
};
connect();
if (config.server)
require("http")
.createServer((__, res) => res.end("Server Running!"))
.listen(8080);
process.on("uncaughtException", function (err) {
console.error(err);
});