forked from devlup-labs/discord-article-bot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
344 lines (317 loc) · 10.6 KB
/
app.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
const Discord = require("discord.js");
var fs = require("fs");
var _ = require("lodash");
var cronstrue = require("cronstrue");
const schedule = require("node-schedule");
var articles = fs.readFileSync("articles.json");
const dotenv = require('dotenv').config();
const { scheduleJob } = require("node-schedule");
// parsing articles.json
articles = JSON.parse(articles);
// creating client
const client = new Discord.Client({
intents: [Discord.Intents.FLAGS.GUILDS, Discord.Intents.FLAGS.GUILD_MESSAGES],
});
// categories
categories = [
"WILDCARD",
"LIVING BETTER",
"BUSINESS TECH",
"HISTORY CULTURE",
"SCIENCE NATURE",
];
categoryNames = [
"1. Wildcard",
"2. Living Better",
"2. Business & Tech",
"3. History & Culture",
"4. Science & Nature",
];
const prefix = dotenv.parsed.PREFIX;
// command message
var command =
"1. **For getting a random article**:" + "```" + prefix + "get article[category]``` " +
"\n" +
"ex: " + "`" + prefix + "get article wildcard`, this will fetch a random article form wildcard category" +
"\n" +
"\n" +
"Tip: " + "`" + prefix + "get article`, this will give you the list of categories available" +
"\n" +
"\n" +
"Tip: " + "`" + prefix + "get article time`, this will give you the time at which you get the daily article" +
"\n" +
"\n" +
"2. **For setting time of daily message**:" +
"\n" +
"\n" +
"> 1. for days(in integers from 0-6): " + "```" + prefix + "set article days[startDay][endDay]```" +
"\n" +
"ex: " + "`" + prefix + "set article days 0 6`, this will set the days as SUN-SAT" +
"\n" +
"\n" +
"> 2. for time(in 24hr format): " + "```" + prefix + "set article time[hour]: [mins]```" +
"\n" +
"ex: " + "`" + prefix + "set article time 14: 20`, this will give the daily article at 2:20 pm";
// embed command message
const exampleEmbed = new Discord.MessageEmbed()
.setColor("#FF3F3F")
.setTitle("readsomethinggreat")
.setURL("https://www.readsomethinggreat.com/")
.setAuthor(
"Buy me a coffee",
"https://i.imgur.com/vugPtoT.png",
"https://www.buymeacoffee.com/rahulgopathi"
)
.setDescription(
"A bot that gives a random article from readsomethinggreat.com"
)
.setThumbnail("https://i.imgur.com/vugPtoT.png")
.addFields(
{
name: "Categories",
value:
"Wildcard, Living Better, Business & Tech, History & Culture, Science & Nature",
},
{ name: "\u200B", value: "\u200B" },
{
name: "Commands",
value: command,
inline: true,
}
)
.setTimestamp()
.setFooter("Happy Reading", "https://i.imgur.com/vugPtoT.png");
const rule = new schedule.RecurrenceRule();
rule.dayOfWeek = [0, new schedule.Range(0, 6)];
rule.hour = 10;
rule.minute = 00;
var startDay = 0;
var endDay = 6;
const ruleForBMC = new schedule.RecurrenceRule();
ruleForBMC.dayOfWeek = [0, new schedule.Range(dotenv.parsed.daysofWeek_BMCLink)];
ruleForBMC.hour = dotenv.parsed.hour_BMCLink;
ruleForBMC.minute = dotenv.parsed.minute_BMCLink;
ruleForBMC.second = dotenv.parsed.second_BMCLink;
//creating a empty cron expression
var cronExpression = `${rule.minute} ${rule.hour} * * ${startDay}-${endDay} `;
var dailyUpdatesChannel = null;
// fetching random article
function fetchRandomArticle(category) {
var numberofArticles = articles[category].length;
var randomArticlePosition = Math.floor(Math.random() * numberofArticles);
article = articles[category][randomArticlePosition];
if (category == "WILDCARD") {
try {
articleLink = article["Link to Article"][0];
} catch (error) {
console.log(error);
dailyUpdatesChannel.send("An error occured, could you please try again");
}
} else {
try {
articleLink = article["Link to Article"];
} catch (error) {
console.log(error);
dailyUpdatesChannel.send("An error occured, could you please try again");
}
}
articles[category].splice(randomArticlePosition, 1);
console.log("Generated random article succesfully");
return articleLink;
}
//bmc link schedule
function BMCLinkScheduler() {
const job = schedule.scheduleJob(ruleForBMC, function () {
client.guilds.cache.each((guild) => {
try {
const channel =
guild.channels.cache.find(
(channel) => channel.name === "readsomethinggreat"
) || guild.channel.cache.first();
if (channel) {
channel.send("**Buy me a Coffee link**- " + dotenv.parsed.BMC_Link);
console.log("link send");
} else {
console.log("link not send");
}
} catch (err) {
console.log('error is there');
}
});
});
}
// resetting schedule after changing timings
function resetScheduler() {
console.log(rule);
const job = schedule.scheduleJob(rule, function () {
articleLink = fetchRandomArticle("WILDCARD");
client.guilds.cache.each((guild) => {
try {
const channel =
guild.channels.cache.find(
(channel) => channel.name === "readsomethinggreat"
) || guild.channels.cache.first();
if (channel) {
channel.send(articleLink);
console.log("sent the daily article to channels");
} else {
console.log("The server " + guild.name + " has no channels.");
}
} catch (err) {
console.log("Could not send message to " + guild.name + ".");
}
});
cronExpression = `${rule.minute} ${rule.hour} * * ${startDay}-${endDay} `;
});
}
//Playing Message
client.on("ready", async () => {
console.log(
`${client.user.username} is online on ${client.guilds.cache.size} servers!`
);
client.user.setActivity("Article", { type: "PLAYING" });
resetScheduler();
BMCLinkScheduler();
});
// handling on message events
client.on("message", (msg) => {
cronExpression = `${rule.minute} ${rule.hour} * * ${startDay}-${endDay} `;
if (msg.author.bot) return;
if (msg.content === "get help" || msg.content === "get article") {
msg.channel.send("Are you trying to call me?")
.then((text) => {
text.channel.send("My prefix is " + "`" + prefix + "`" + "\n" + "Ex - " + "`*get help`")
})
}
if (msg.content === prefix + "get help") {
msg.channel.send({ embeds: [exampleEmbed] })
}
if (
msg.content.startsWith(prefix + "get article") ||
msg.content.startsWith(prefix + "Get article")
) {
msgRecievied = msg.content.split(" ");
if (msgRecievied.length == 2) {
msg.channel.send(
"```" +
`Here are the article categories to read upon:\n${categoryNames.join(
"\n"
)}` +
"```"
);
} else {
if (msgRecievied.length == 3) {
category = _.upperCase(msgRecievied[2]);
} else {
category = msgRecievied.slice(2);
category = _.upperCase(category.join(" "));
}
if (categories.includes(category)) {
msg.channel.send(fetchRandomArticle(category))
.then((embed) => {
embed.react('⬆'),
embed.react("⬇️")
})
.catch((err) => {
console.log(err);
msg.channel.send("```coudn't fetch the article at the moment :( ```");
});
} else {
if (msgRecievied[2] == "time") {
msg.channel.send(
"The daily article will be coming " +
cronstrue.toString(cronExpression)
);
} else {
msg.channel.send(
"```The specified category doesn't exists. The available categories are:\n" +
`${categoryNames.join("\n")}` +
"```"
);
}
}
}
}
if (msg.content.startsWith(prefix + "set article ")) {
correctTimeProvided = false;
displayDailyArticleTime = true; //if true send daily article time expression
setTimeCommand = msg.content.split(" ");
if (setTimeCommand[2] == "days") {
try {
if (
setTimeCommand.length === 5 &&
setTimeCommand[3] != "" &&
setTimeCommand[4] != ""
) {
if (setTimeCommand[3] < 7 && setTimeCommand[4] < 7 && setTimeCommand[3] >= 0 && setTimeCommand[4] >= 0) {
startDay = setTimeCommand[3];
endDay = setTimeCommand[4];
rule.dayOfWeek = [0, new schedule.Range(startDay, endDay)];
correctTimeProvided = true;
} else {
msg.channel.send(
"```Please sepecify Days from 0 to 6.\nEx: " + prefix + "set article days 0 6```"
);
displayDailyArticleTime = false;
}
} else if (setTimeCommand.length != 5) {
msg.channel.send(
"```Please sepecify time after the command.\nEx: " + prefix + "set article days 0 6```"
);
displayDailyArticleTime = false;
}
} catch (error) {
console.log(error);
msg.channel.send(
"```Please specify days in [startDay] [endDay] format ```"
);
}
} else if (setTimeCommand[2] == "time") {
try {
var time = setTimeCommand[3].split(":");
if (time.length !== 2 || time[0] == "" || time[1] == "") {
msg.channel.send(
"```Please specify time in [hours]:[minutes] format where hours are in 24 hour format```"
);
displayDailyArticleTime = false;
} else if (time[0] > 23 || time[1] > 59 || time[0] < 0 || time[1] < 0) {
msg.channel.send("```Hour should be less than 24 & Minute should be less than 60```");
displayDailyArticleTime = false;
} else if (time[0] < 23 || time[1] < 59 || time[0] >= 0 || time[1] >= 0) {
rule.hour = time[0];
rule.minute = time[1];
correctTimeProvided = true;
}
}
catch (error) {
console.log(error);
msg.channel.send(
"```Please sepecify time after the command.\nEx: " + prefix + "set article time hour 14:20```"
);
displayDailyArticleTime = false;
}
} else {
msg.channel.send(
"```wrong command :( please type [" + prefix + "get help] for the commands```"
);
displayDailyArticleTime = false;
}
var updatedcronExpression = `${rule.minute} ${rule.hour} * * ${startDay}-${endDay}`;
if (correctTimeProvided == true && displayDailyArticleTime == true) {
msg.channel.send(
"From now the daily article will be coming " +
cronstrue.toString(updatedcronExpression)
);
cronExpression = updatedcronExpression;
} else if (displayDailyArticleTime) {
msg.channel.send(
"```The daily article time is already " +
cronstrue.toString(updatedcronExpression) +
"```"
);
}
resetScheduler();
}
});
//Token need in token.json
client.login(dotenv.parsed.TOKEN);