-
Notifications
You must be signed in to change notification settings - Fork 218
/
index.js
390 lines (361 loc) · 13.2 KB
/
index.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
/**
* Source Code By Reza
* Don't Forget Smile
* Thank You :)
*/
require("./setting/config")
const {
default: EzaConnect,
useMultiFileAuthState,
DisconnectReason,
fetchLatestBaileysVersion,
makeInMemoryStore,
jidDecode,
proto,
getContentType,
Browsers,
} = require("@adiwajshing/baileys");
const pino = require("pino");
const { Boom } = require("@hapi/boom");
const fs = require("fs");
const axios = require("axios");
const chalk = require("chalk");
const figlet = require("figlet");
const _ = require("lodash");
const PhoneNumber = require("awesome-phonenumber");
const store = makeInMemoryStore({ logger: pino().child({ level: "silent", stream: "store" }) });
const color = (text, color) => {
return !color ? chalk.green(text) : chalk.keyword(color)(text);
};
function smsg(conn, m, store) {
if (!m) return m;
let M = proto.WebMessageInfo;
if (m.key) {
m.id = m.key.id;
m.isBaileys = m.id.startsWith("BAE5") && m.id.length === 16;
m.chat = m.key.remoteJid;
m.fromMe = m.key.fromMe;
m.isGroup = m.chat.endsWith("@g.us");
m.sender = conn.decodeJid((m.fromMe && conn.user.id) || m.participant || m.key.participant || m.chat || "");
if (m.isGroup) m.participant = conn.decodeJid(m.key.participant) || "";
}
if (m.message) {
m.mtype = getContentType(m.message);
m.msg = m.mtype == "viewOnceMessage" ? m.message[m.mtype].message[getContentType(m.message[m.mtype].message)] : m.message[m.mtype];
m.body =
m.message.conversation ||
m.msg.caption ||
m.msg.text ||
(m.mtype == "listResponseMessage" && m.msg.singleSelectReply.selectedRowId) ||
(m.mtype == "buttonsResponseMessage" && m.msg.selectedButtonId) ||
(m.mtype == "viewOnceMessage" && m.msg.caption) ||
m.text;
let quoted = (m.quoted = m.msg.contextInfo ? m.msg.contextInfo.quotedMessage : null);
m.mentionedJid = m.msg.contextInfo ? m.msg.contextInfo.mentionedJid : [];
if (m.quoted) {
let type = getContentType(quoted);
m.quoted = m.quoted[type];
if (["productMessage"].includes(type)) {
type = getContentType(m.quoted);
m.quoted = m.quoted[type];
}
if (typeof m.quoted === "string")
m.quoted = {
text: m.quoted,
};
m.quoted.mtype = type;
m.quoted.id = m.msg.contextInfo.stanzaId;
m.quoted.chat = m.msg.contextInfo.remoteJid || m.chat;
m.quoted.isBaileys = m.quoted.id ? m.quoted.id.startsWith("BAE5") && m.quoted.id.length === 16 : false;
m.quoted.sender = conn.decodeJid(m.msg.contextInfo.participant);
m.quoted.fromMe = m.quoted.sender === conn.decodeJid(conn.user.id);
m.quoted.text = m.quoted.text || m.quoted.caption || m.quoted.conversation || m.quoted.contentText || m.quoted.selectedDisplayText || m.quoted.title || "";
m.quoted.mentionedJid = m.msg.contextInfo ? m.msg.contextInfo.mentionedJid : [];
m.getQuotedObj = m.getQuotedMessage = async () => {
if (!m.quoted.id) return false;
let q = await store.loadMessage(m.chat, m.quoted.id, conn);
return exports.smsg(conn, q, store);
};
let vM = (m.quoted.fakeObj = M.fromObject({
key: {
remoteJid: m.quoted.chat,
fromMe: m.quoted.fromMe,
id: m.quoted.id,
},
message: quoted,
...(m.isGroup ? { participant: m.quoted.sender } : {}),
}));
/**
*
* @returns
*/
m.quoted.delete = () => conn.sendMessage(m.quoted.chat, { delete: vM.key });
/**
*
* @param {*} jid
* @param {*} forceForward
* @param {*} options
* @returns
*/
m.quoted.copyNForward = (jid, forceForward = false, options = {}) => conn.copyNForward(jid, vM, forceForward, options);
/**
*
* @returns
*/
m.quoted.download = () => conn.downloadMediaMessage(m.quoted);
}
}
if (m.msg.url) m.download = () => conn.downloadMediaMessage(m.msg);
m.text = m.msg.text || m.msg.caption || m.message.conversation || m.msg.contentText || m.msg.selectedDisplayText || m.msg.title || "";
/**
* Reply to this message
* @param {String|Object} text
* @param {String|false} chatId
* @param {Object} options
*/
m.reply = (text, chatId = m.chat, options = {}) => (Buffer.isBuffer(text) ? conn.sendMedia(chatId, text, "file", "", m, { ...options }) : conn.sendText(chatId, text, m, { ...options }));
/**
* Copy this message
*/
m.copy = () => exports.smsg(conn, M.fromObject(M.toObject(m)));
/**
*
* @param {*} jid
* @param {*} forceForward
* @param {*} options
* @returns
*/
m.copyNForward = (jid = m.chat, forceForward = false, options = {}) => conn.copyNForward(jid, m, forceForward, options);
return m;
}
async function startEza() {
const { state, saveCreds } = await useMultiFileAuthState(`./${sessionName ? sessionName : "session"}`);
const { version, isLatest } = await fetchLatestBaileysVersion();
console.log(`using WA v${version.join(".")}, isLatest: ${isLatest}`);
console.log(
color(
figlet.textSync("Push-Kontak", {
font: "Standard",
horizontalLayout: "default",
vertivalLayout: "default",
whitespaceBreak: false,
}),
"cyan"
)
);
const client = EzaConnect({
logger: pino({ level: "silent" }),
printQRInTerminal: true,
browser: Browsers.macOS('Desktop'),
patchMessageBeforeSending: (message) => {
const requiresPatch = !!(
message.buttonsMessage
|| message.templateMessage
|| message.listMessage
);
if (requiresPatch) {
message = {
viewOnceMessage: {
message: {
messageContextInfo: {
deviceListMetadataVersion: 2,
deviceListMetadata: {},
},
...message,
},
},
};
}
return message;
},
auth: state,
});
store.bind(client.ev);
client.ev.on("messages.upsert", async (chatUpdate) => {
//console.log(JSON.stringify(chatUpdate, undefined, 2))
try {
mek = chatUpdate.messages[0];
if (!mek.message) return;
mek.message = Object.keys(mek.message)[0] === "ephemeralMessage" ? mek.message.ephemeralMessage.message : mek.message;
if (mek.key && mek.key.remoteJid === "status@broadcast") return;
if (!client.public && !mek.key.fromMe && chatUpdate.type === "notify") return;
if (mek.key.id.startsWith("BAE5") && mek.key.id.length === 16) return;
m = smsg(client, mek, store);
require("./setting/mechaine")(client, m, chatUpdate, store);
} catch (err) {
console.log(err);
}
});
// Handle error
const unhandledRejections = new Map();
process.on("unhandledRejection", (reason, promise) => {
unhandledRejections.set(promise, reason);
console.log("Unhandled Rejection at:", promise, "reason:", reason);
});
process.on("rejectionHandled", (promise) => {
unhandledRejections.delete(promise);
});
process.on("Something went wrong", function (err) {
console.log("Caught exception: ", err);
});
// Setting
client.decodeJid = (jid) => {
if (!jid) return jid;
if (/:\d+@/gi.test(jid)) {
let decode = jidDecode(jid) || {};
return (decode.user && decode.server && decode.user + "@" + decode.server) || jid;
} else return jid;
};
client.ev.on("contacts.update", (update) => {
for (let contact of update) {
let id = client.decodeJid(contact.id);
if (store && store.contacts) store.contacts[id] = { id, name: contact.notify };
}
});
client.getName = (jid, withoutContact = false) => {
id = client.decodeJid(jid);
withoutContact = client.withoutContact || withoutContact;
let v;
if (id.endsWith("@g.us"))
return new Promise(async (resolve) => {
v = store.contacts[id] || {};
if (!(v.name || v.subject)) v = client.groupMetadata(id) || {};
resolve(v.name || v.subject || PhoneNumber("+" + id.replace("@s.whatsapp.net", "")).getNumber("international"));
});
else
v =
id === "0@s.whatsapp.net"
? {
id,
name: "WhatsApp",
}
: id === client.decodeJid(client.user.id)
? client.user
: store.contacts[id] || {};
return (withoutContact ? "" : v.name) || v.subject || v.verifiedName || PhoneNumber("+" + jid.replace("@s.whatsapp.net", "")).getNumber("international");
};
client.setStatus = (status) => {
client.query({
tag: "iq",
attrs: {
to: "@s.whatsapp.net",
type: "set",
xmlns: "status",
},
content: [
{
tag: "status",
attrs: {},
content: Buffer.from(status, "utf-8"),
},
],
});
return status;
};
client.public = true;
client.serializeM = (m) => smsg(client, m, store);
client.ev.on("connection.update", async (update) => {
const { connection, lastDisconnect } = update;
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`);
process.exit();
} else if (reason === DisconnectReason.connectionClosed) {
console.log("Connection closed, reconnecting....");
startEza();
} else if (reason === DisconnectReason.connectionLost) {
console.log("Connection Lost from Server, reconnecting...");
startEza();
} else if (reason === DisconnectReason.connectionReplaced) {
console.log("Connection Replaced, Another New Session Opened, Please Restart Bot");
process.exit();
} else if (reason === DisconnectReason.loggedOut) {
console.log(`Device Logged Out, Please Delete Folder Session ${sessionName} and Scan Again.`);
process.exit();
} else if (reason === DisconnectReason.restartRequired) {
console.log("Restart Required, Restarting...");
startEza();
} else if (reason === DisconnectReason.timedOut) {
console.log("Connection TimedOut, Reconnecting...");
startEza();
} else {
console.log(`Unknown DisconnectReason: ${reason}|${connection}`);
startEza();
}
} else if (connection === "open") {
const botNumber = await client.decodeJid(client.user.id);
console.log(color("Created By RezaDevv", "green"));
console.log(color("Don't Forget Smile :)", "yellow"));
console.log(color("Type .pushkontak for kontak in group"));
client.sendMessage(`${owner}@s.whatsapp.net`, { text: `*── 「 DETAIL CONFIGURASI 」 ──*\n\n*_Owner:_* _${owner}_\n*_Author:_* _${author}_\n*_Session:_* _${sessionName}_\n*_Version:_* _${versionbot}_\n\n*_${botNumber}_*` });
}
// console.log('Connected...', update)
});
client.ev.on("creds.update", saveCreds);
const 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 (err) {
return err;
}
};
client.sendImage = async (jid, path, caption = "", quoted = "", options) => {
let buffer = Buffer.isBuffer(path)
? path
: /^data:.*?\/.*?;base64,/i.test(path)
? Buffer.from(path.split`,`[1], "base64")
: /^https?:\/\//.test(path)
? await await getBuffer(path)
: fs.existsSync(path)
? fs.readFileSync(path)
: Buffer.alloc(0);
return await client.sendMessage(jid, { image: buffer, caption: caption, ...options }, { quoted });
};
client.sendText = (jid, text, quoted = "", options) => client.sendMessage(jid, { text: text, ...options }, { quoted });
client.cMod = (jid, copy, text = "", sender = client.user.id, options = {}) => {
//let copy = message.toJSON()
let mtype = Object.keys(copy.message)[0];
let isEphemeral = mtype === "ephemeralMessage";
if (isEphemeral) {
mtype = Object.keys(copy.message.ephemeralMessage.message)[0];
}
let msg = isEphemeral ? copy.message.ephemeralMessage.message : copy.message;
let content = msg[mtype];
if (typeof content === "string") msg[mtype] = text || content;
else if (content.caption) content.caption = text || content.caption;
else if (content.text) content.text = text || content.text;
if (typeof content !== "string")
msg[mtype] = {
...content,
...options,
};
if (copy.key.participant) sender = copy.key.participant = sender || copy.key.participant;
else if (copy.key.participant) sender = copy.key.participant = sender || copy.key.participant;
if (copy.key.remoteJid.includes("@s.whatsapp.net")) sender = sender || copy.key.remoteJid;
else if (copy.key.remoteJid.includes("@broadcast")) sender = sender || copy.key.remoteJid;
copy.key.remoteJid = jid;
copy.key.fromMe = sender === client.user.id;
return proto.WebMessageInfo.fromObject(copy);
};
return client;
}
startEza();
let file = require.resolve(__filename);
fs.watchFile(file, () => {
fs.unwatchFile(file);
console.log(chalk.redBright(`Update ${__filename}`));
delete require.cache[file];
require(file);
});