-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
361 lines (287 loc) Β· 10.5 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
// touching this file is not advised
import { Client, CustomStatus } from "discord.js-selfbot-v13";
import config from "./config.js";
import cheerio from "cheerio";
import fetch from "node-fetch";
import express from 'express'
import db2 from "old-wio.db";
import schedule from "node-schedule";
import { DateTime } from "luxon";
const client = new Client({
syncStatus: false,
checkUpdate: false,
});
const app = express()
app.get('/', function (req, res) {
res.send('Hello World')
})
app.listen(3000)
const r = new CustomStatus()
.setState(config.customStatus.message || 'duck. fuck.')
.setEmoji(config.customStatus.emoji || 'π¦')
import { QuickDB, JSONDriver } from "quick.db";
const jsonDriver = new JSONDriver();
const db = new QuickDB({ filePath: "./quickdb.json", driver: jsonDriver });
db2.backup("backup.json");
client.on("ready", async () => {
client.user.setActivity(r);
console.log(`\x1b[96m${client.user.username}\x1b[39m is ready!`);
});
const harukeID = "852848188942581764";
const crosses = [];
const checkmarks = [];
process.env.TZ = config.timezone;
var paused;
paused = false
// prettier-ignore
const job = schedule.scheduleJob(getRandomTime(), async function () {
await postMessage();
await job.reschedule(getRandomTime());
console.log(
`π | Next run at \x1b[1;93m${formatDate(
job.pendingInvocations[0].fireDate.toLocaleString(DateTime.DATETIME_MED)
)}\x1b[0;39m`
)
});
console.log(
`π | Next run at \x1b[1;93m${formatDate(
job.pendingInvocations[0].fireDate.toLocaleString(DateTime.DATETIME_MED)
)}\x1b[0;39m`
);
function formatDate(date) {
const inputDate = new Date(date);
function addLeadingZero(number) {
return number < 10 ? `0${number}` : number;
}
const hours = addLeadingZero(inputDate.getHours());
const minutes = addLeadingZero(inputDate.getMinutes());
const seconds = addLeadingZero(inputDate.getSeconds());
const dayOfWeek = inputDate.toLocaleString("en-us", { weekday: "short" });
const day = inputDate.getDate();
const month = inputDate.toLocaleString("en-us", { month: "short" });
const formattedDate = `${hours}:${minutes}:${seconds}, ${dayOfWeek}, ${day} ${month}`;
return formattedDate;
}
async function postMessage() {
if (paused) return;
var factsToPost = await db2.fetchAll();
const user = await client.users.fetch(config.userID);
var values = Object.values(factsToPost);
const keys = Object.keys(factsToPost);
const channel = await client.channels.fetch(config.fotdChannel);
const lastMessage = await channel.messages.fetch({ limit: 1 });
const lastMsg = lastMessage.first().content;
const numberMatch = lastMsg.match(/\*\*#Fact (\d+)\*\*/);
if (numberMatch && numberMatch[1]) {
var extractedNumber = parseInt(numberMatch[1]);
}
if (values.length > 0) {
const firstValue = values[0];
var sentMsg = await channel.send(
`\*\*#Fact ${extractedNumber + 1}\*\* - ${firstValue}`
);
await db.set(keys[0], values[0]);
await db2.delete(keys[0]);
var factsToPost = await db2.fetchAll();
var values = Object.values(factsToPost);
}
if (values.length <= config.warnAt && values.length != 0) {
user.send(`\`β οΈ\` \`|\` Only \`${values.length}\` fact(s) left!`);
}
if (!values.length) {
console.log("β | No Fact found in the db! Sending a random fact.");
var randomFact = await getUniqueFact(randomIntFromInterval(1, 3047));
const key = removeSpecialChars(randomFact);
var sentMsg = await channel.send(
`\*\*#Fact ${extractedNumber + 1}\*\* - ${randomFact}`
);
await db.set(key, randomFact);
user.send(
`\`β\` \`|\` No fact found in the database! Sent \`${randomFact}\``
);
}
if (config.autoCrosspost && sentMsg?.crosspostable) {
await sentMsg.crosspost();
}
return;
}
async function clearFacts() {
if (checkmarks.length != config.factCount) return;
for await (const checkmark of checkmarks) {
console.log(`π― | Added \x1b[36m${checkmark}\x1b[39m to database`);
db2.set(removeSpecialChars(checkmark), checkmark);
}
checkmarks.splice(0, checkmarks.length);
crosses.splice(0, crosses.length);
}
client.on("messageCreate", async (message) => {
if (message.author.id != config.userID) return;
if (message.content.toLowerCase() === `${config.prefix}start`) {
await getUserFacts(message.author, message.channel);
}
if (message.content.toLowerCase().startsWith(`${config.prefix}customfact`)) {
const str = message.content.replace(`${config.prefix}customfact `, "");
const strKey = removeSpecialChars(str);
await db2.set(strKey, str);
console.log(`π― | \x1b[36m${str}\x1b[0;39m set to db`);
message.channel.send(`\`β
\` \`|\` \`${str}\` set to the database!`);
}
if (message.content.toLowerCase() === `${config.prefix}list`) {
var arr = []
const factsToPost = await db2.fetchAll();
const keys = Object.keys(factsToPost);
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
const value = factsToPost[key];
arr.push(value)
}
const frmtArr = formatArray(arr)
message.channel.send(frmtArr)
}
if (message.content.toLowerCase() === `${config.prefix}forcepost`) {
if (paused) {
message.channel.send(`\`π\` \`|\` Turn off \`paused\` to force post!`)
} else {
await postMessage();
message.channel.send(`\`β
\` \`|\` Successfully posted a fact!`)
}
}
if (message.content.toLowerCase() === `${config.prefix}pause`) {
if (!paused) {
paused = true
message.channel.send(`\`β οΈ\` \`|\` Facts are now \`paused\` till this command is ran again.`)
} else {
paused = false
message.channel.send(`\`β
\` \`|\` Facts are now \`resumed\`. `)
}
}
});
async function getUserFacts(user, channel) {
if (checkmarks.length === config.factCount) {
await clearFacts();
return;
}
var randomFact = async function () {
var randomfct = await getUniqueFact(randomIntFromInterval(1, 3047));
return randomfct;
};
const factMessage = await channel.send(await randomFact());
const filter = (reaction, user) =>
user.id === config.userID || user.id === harukeID;
const collector = factMessage.createReactionCollector({
filter,
time: 600000,
});
collector.on("collect", async (reaction, user) => {
if (reaction.emoji.name === "β
") {
checkmarks.push(factMessage.content);
reaction.users.remove(user);
console.log("β
: ", "\x1b[32m", factMessage.content, "\x1b[39m");
} else if (reaction.emoji.name === "β") {
crosses.push(factMessage.content);
console.log("β :", " \x1b[31m", factMessage.content, "\x1b[39m");
reaction.users.remove(user);
}
if (checkmarks.length !== config.factCount) {
const randomFact = await getUniqueFact(randomIntFromInterval(1, 3047));
await factMessage.edit(randomFact);
} else {
await factMessage.delete();
await channel.send(truncate(formatArrays(checkmarks, crosses), 2000));
await clearFacts();
return;
}
});
factMessage?.react("β
")?.then(() => factMessage?.react("β"));
}
function getRandomTime() {
var tmrw = new Date();
tmrw.setDate(tmrw.getDate() + 1)
const day = tmrw.getDate();
const seconds = Math.floor(Math.random() * 60);
const hours = Math.floor(
Math.random() * (config.time.max - config.time.min + 1) + config.time.min
);
const minutes = Math.floor(Math.random() * 60);
return `${seconds} ${minutes} ${hours} ${day} * *`;
}
function truncate(str, n) {
return str.length > n ? str.slice(0, n - 8) + "...\n```" : str;
}
function formatArrays(selectedArray, removedArray) {
const formatArray = (array, color) => {
return array.map((item) => {
return `[2;37m-[0m ${color}${item}[0m`;
});
};
const formattedSelected = formatArray(selectedArray, "[2;34m");
const formattedRemoved = formatArray(removedArray, "[2;31m");
const selected = `[2;37mSelected :[0m\n\n${formattedSelected.join("\n")}`;
const removed = `[2;37mRemoved :[0m\n\n${formattedRemoved.join("\n")}`;
return `\`\`\`ansi\n${selected}\n\n${removed}\`\`\``;
}
function formatArray(array) {
let num = 1;
const formArray = (array, color) => {
return array.map((item, index) => {
if (index === 0) {
const formattedItem = `[2;37m${num}.[0m ${color}${item}[0m - [2;31m${formatDate(
job.pendingInvocations[0].fireDate.toLocaleString(DateTime.DATETIME_MED)
)}[0m`;
num++;
return formattedItem;
} else {
const formattedItem = `[2;37m${num}.[0m ${color}${item}[0m`;
num++;
return formattedItem;
}
});
};
const formatted = formArray(array, "[2;34m");
const fr = paused
? `[2;37m[PAUSED] to be sent :[0m\n\n${formatted.join("\n")}`
: `[2;37mTo be sent :[0m\n\n${formatted.join("\n")}`;
return `\`\`\`ansi\n${fr}\`\`\``;
}
function randomIntFromInterval(min, max) {
let int = Math.floor(Math.random() * (max - min + 1) + min);
return int.toString();
}
function removeSpecialChars(string) {
const specialCharacters = /['βββββ"!@#$%^&*()_+{}\[\]:;<>,.?~\\|/-]/g;
const text = string.replace(specialCharacters, " ");
return text;
}
async function getUniqueFact(number) {
let fact = await getFactOfTheDayParagraph(number);
let factCheck = removeSpecialChars(fact);
if (!(await db.get(factCheck))) {
return fact;
} else {
console.log("π :", " \x1b[90m", fact, "\x1b[39m");
return await getUniqueFact(randomIntFromInterval(1, 3047));
}
}
async function getFactOfTheDayParagraph(number) {
try {
const response = await fetch(
`https://www.beagreatteacher.com/daily-fun-fact/page/${number}/`
);
const htmlContent = await response.text();
const $ = cheerio.load(htmlContent);
const factTitle = $('h2:contains("Random Fact of the Day:")');
if (factTitle.length > 0) {
const nextParagraph = factTitle.next("p");
if (nextParagraph.length > 0) {
return nextParagraph.text().trim();
} else {
return "No next paragraph found.";
}
} else {
return "No 'Random Fact of the Day:' found.";
}
} catch (error) {
console.log(error);
}
}
client.login(config.token);