-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.js
211 lines (189 loc) · 5.85 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
require("dotenv").config();
const Collection = require("./lib/CommandCollections");
const fs = require("fs");
const path = require("node:path");
const chokidar = require("chokidar");
const {
default: makeWASocket,
DisconnectReason,
fetchLatestBaileysVersion,
makeCacheableSignalKeyStore,
proto,
useMultiFileAuthState,
makeInMemoryStore,
} = require("@whiskeysockets/baileys");
const Pino = require("pino");
const NodeCache = require("node-cache");
// external map to store retry counts of messages when decryption/encryption fails
// keep this out of the socket itself, so as to prevent a message decryption/encryption loop across socket restarts
const msgRetryCounterCache = new NodeCache();
// LowDB
var low;
try {
low = require("lowdb");
} catch {
low = require("./lib/lowdb");
}
const { Low, JSONFile } = low;
// Prevent exit if it's closed
process.on("uncaughtException", console.error);
async function start() {
// Client configuration
const { state, saveCreds } = await useMultiFileAuthState("sessions");
const { version } = await fetchLatestBaileysVersion();
// Client store
const store = makeInMemoryStore({ logger: Pino({ level: "silent" }) });
// can be read from a file
store.readFromFile("./client_store.json");
// saves the state to a file every 1minute
setInterval(() => {
store.writeToFile("./client_store.json");
}, 60_000);
// Deploy the client
const bot = makeWASocket({
version,
printQRInTerminal: true,
auth: {
creds: state.creds,
keys: makeCacheableSignalKeyStore(state.keys, Pino({ level: "silent" })),
},
msgRetryCounterCache: msgRetryCounterCache,
getMessage: async (msg) => {
if (store) {
const storedMsg = await store.loadMessage(msg.remoteJid, msg.id);
return storedMsg.message || undefined;
}
return proto.Message.fromObject({});
},
logger: Pino({ level: "silent" }),
syncFullHistory: false,
retryRequestDelayMs: 10,
transactionOpts: {
maxCommitRetries: 10,
delayBetweenTriesMs: 10,
},
maxMsgRetryCount: 15,
appStateMacVerification: {
patch: true,
snapshot: true,
},
});
// Bind the store
store.bind(bot.ev);
bot.store = store;
// Command manager
bot.commands = new Collection();
// Load the commands
const loadCommands = (dir) => {
bot.commands.clear();
const commandsPath = path.join(__dirname, dir);
const commandFolders = fs.readdirSync(commandsPath);
for (const folder of commandFolders) {
const folderPath = path.join(commandsPath, folder);
const commandFiles = fs
.readdirSync(folderPath)
.filter((file) => file.endsWith(".js"));
for (const file of commandFiles) {
const filePath = path.join(folderPath, file);
delete require.cache[require.resolve(filePath)];
try {
const command = require(filePath);
command.category = folder;
bot.commands.set(command.name, command); // Set the main name
if (command.alias && Array.isArray(command.alias)) {
command.alias.forEach((alias) => bot.commands.set(alias, command)); // Set aliases
}
} catch (error) {
console.error(`Failed to load command from: ${filePath}:`, error);
}
}
}
console.log(bot.commands);
console.log(
`All commands has been loaded. Total commands: ${bot.commands.size}`
);
};
loadCommands("commands");
// Watch the commands folder if there's some changes
const watcher = chokidar.watch("./commands", {
ignored: /^\./, // Abaikan file yang diawali dengan titik (.)
persistent: true,
ignoreInitial: true, // Jangan load saat pertama kali dijalankan
});
watcher
.on("add", (filePath) => {
if (filePath.endsWith(".js")) {
console.log(`File ${filePath} has been added, reloading commands...`);
loadCommands("commands");
}
})
.on("change", (filePath) => {
if (filePath.endsWith(".js")) {
console.log(`File ${filePath} has been changed, reloading commands...`);
loadCommands("commands");
}
})
.on("unlink", (filePath) => {
if (filePath.endsWith(".js")) {
console.log(`File ${filePath} has been removed, reloading commands...`);
loadCommands("commands");
}
});
chokidar
.watch("./.env", {
persistent: true,
ignoreInitial: true,
})
.on("change", () => {
console.log("File .env has been changed, reloading configs...");
require("dotenv").config({ override: true });
});
// Database
bot.db = new Low(new JSONFile("./database.json"));
// Try to load database
if (bot.db.data === null) {
await bot.db.read();
bot.db.data = {
users: {},
groups: {},
...(bot.db.data || {}),
};
}
bot.ev.on("connection.update", async (update) => {
const { connection, lastDisconnect } = update;
if (connection === "close") {
console.log("connection closed");
if (
lastDisconnect?.error?.output?.statusCode !== DisconnectReason.loggedOut
) {
await start();
} else {
console.log("Connection closed. You are logged out.");
}
}
console.log("connection update", update);
});
bot.ev.on(
"messages.upsert",
require("./events/CommandHandler").chatUpdate.bind(bot)
);
bot.ev.on("creds.update", async () => {
await saveCreds();
});
return bot;
}
start().then(async (bot) => {
// Save database
if (bot.db.data) {
setInterval(async () => {
try {
await bot.db.write();
} catch {
fs.unlinkSync("./database.json.tmp"); // remove temporary database (sometimes throws this error tho)
}
if (fs.existsSync("./database.json.tmp")) {
fs.unlinkSync("./database.json.tmp"); // remove temporary database file for prevent error writing into database
}
}, 30 * 1000);
}
});