-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathindex.js
212 lines (191 loc) · 6.36 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
/*
* Information
* Creator / Developer: Dani Ramdani (Dani Techno.) - FullStack Engineer
* Contact creator / developer: 0882 9633 9447 (WhatsApp), [email protected] (Email)
*/
/* Thanks
* Dani Techno. - FullStack Engineer (Creator / Developer)
* daniapi.my.id / api.danitechno.com (API provider)
* @danitech/scraper (Scraper provider)
* @whiskeysockets/baileys (Library "Baileys" provider)
* @adiwajshing/keyed-db
* @hapi/boom
* pino
* qrcode-terminal
* chalk
* mongoose
* node-cron
* nodemon
*/
const config = require('./config/mainConfig.js');
const smsg = require('./utils/smsgUtils.js');
const {
default: connectToWhatsApp,
useMultiFileAuthState,
makeInMemoryStore,
jidDecode,
proto,
getContentType,
delay,
DisconnectReason
} = require("@whiskeysockets/baileys");
const {
Boom
} = require('@hapi/boom');
const pino = require('pino');
const qrCodeTerminal = require('qrcode-terminal');
const chalk = require('chalk');
const fs = require('fs');
const mongoose = require('mongoose');
const cron = require('node-cron');
let db = mongoose.connection;
const userSchema = new mongoose.Schema({
username: String,
phoneNumber: String,
accountType: String,
dailyLimit: Number,
isPremium: Boolean,
});
const User = mongoose.model('User', userSchema);
try {
const store = makeInMemoryStore({
logger: pino().child({
level: 'silent',
stream: 'store'
})
});
async function startServer() {
mongoose.connect(config.mongodb_uri, {
useNewUrlParser: true,
useUnifiedTopology: true
});
process.on('unhandledRejection', (error) => console.error(error.message));
const {
state,
saveCreds
} = await useMultiFileAuthState(`./${config.session_folder_name}`);
const sock = connectToWhatsApp({
logger: pino({
level: 'silent'
}),
printQRInTerminal: true,
browser: ["WhatsApp Bot", "Chrome", "1.0.0"],
auth: state
});
store.bind(sock.ev);
sock.ev.on('creds.update', await saveCreds);
sock.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");
sock.logout();
} else if (reason === DisconnectReason.connectionClosed || reason === DisconnectReason.connectionLost) {
console.log("Connection closed or lost, reconnecting...");
startServer();
} else if (reason === DisconnectReason.connectionReplaced) {
console.log("Connection Replaced, Another New Session Opened, Please Close Current Session First");
sock.logout();
} else if (reason === DisconnectReason.loggedOut) {
console.log("Device Logged Out, Please Scan Again And Run.");
sock.logout();
} else if (reason === DisconnectReason.restartRequired || reason === DisconnectReason.timedOut) {
console.log("Restart Required, Restarting...");
startServer();
} else if (reason === DisconnectReason.Multidevicemismatch) {
console.log("Multi device mismatch, please scan again");
sock.logout();
} else {
sock.end(`Unknown DisconnectReason: ${reason}|${connection}`);
}
} else if (connection === "open") {
console.log(chalk.bold(chalk.cyan.blue('• User Info')));
console.log(chalk.cyan(`- Name : ${sock.user.name}`));
console.log(chalk.cyan(`- Number : ${sock.user.id.split(':')[0]}`));
console.log(chalk.cyan(`- Status : Connected`));
db.once('connected', () => {
console.log(chalk.greenBright('Connected to MongoDB'));
});
cron.schedule(config.cron_jobs.time, async () => {
try {
await User.updateMany({
accountType: 'Free'
}, {
dailyLimit: config.daily_limit.free
});
console.log('Limit harian telah direset untuk pengguna tipe "Free".');
} catch (error) {
console.error('Gagal mereset limit harian:', error.message);
}
}, {
timezone: config.cron_jobs.timezone
});
}
});
sock.ev.on('messages.upsert', async (chatUpdate) => {
try {
const 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 (!sock.public && !mek.key.fromMe && chatUpdate.type === 'notify') return;
if (mek.key.id.startsWith('BAE5') && mek.key.id.length === 16) return;
const m = smsg(sock, mek, store);
require('./includes/client.js')({
client: sock,
messages: m,
db: User
});
} catch (error) {
console.error(error.message);
}
});
sock.ev.on('contacts.update', (update) => {
for (let contact of update) {
let id = sock.decodeJid(contact.id)
if (store && store.contacts) store.contacts[id] = {
id,
name: contact.notify
}
}
});
sock.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;
};
sock.public = config.public_mode;
sock.serializeM = (m) => smsg(sock, m, store);
sock.sendText = (jid, text, quoted = '', options) => {
return sock.sendMessage(jid, {
text: text,
...options,
/*contextInfo: {
mentionedJid: [...text.matchAll(/@([0-9]{5,16}|0)/g)].map(v => v[1] + '@s.whatsapp.net'),
externalAdReply: {
title: config.bot.name,
body: config.owner.name[0],
mediaType: 1,
thumbnailUrl: 'https://telegra.ph/file/371343e9b6274c45aab2d.jpg',
sourceUrl: 'https://instagram.com/jbrjbraza',
renderLargerThumbnail: false,
showAdAttribution: true
}
}*/
}, {
quoted,
...options
})
}
return sock;
};
startServer();
} catch (error) {
console.error(error.messages)
};