forked from jinx-vi-0/DDoL
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbot.js
166 lines (144 loc) · 7.11 KB
/
bot.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
import { Client, GatewayIntentBits, Partials,EmbedBuilder } from 'discord.js';
import { LeetCode } from 'leetcode-query';
import cron from 'node-cron';
import keepAlive from './keep_alive.js';
import axios from 'axios';
import dotenv from 'dotenv';
dotenv.config();
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent
],
partials: [
Partials.Channel
]
});
async function fetchLeetCodeProblems() {
try {
const response = await axios.get('https://leetcode.com/api/problems/all/');
leetcodeProblems = response.data.stat_status_pairs.filter(problem => !problem.paid_only);
} catch (error) {
console.error('Error fetching LeetCode problems:', error);
}
}
const lc = new LeetCode();
let leetcodeProblems = []
client.once('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
cron.schedule('0 6 * * *', async () => {
try {
const daily = await lc.daily();
const channel = client.channels.cache.get(process.env.CHANNEL_ID);
if (channel) {
const questionLink = `https://leetcode.com${daily.link}`;
const response = `@everyone **LeetCode Daily Challenge ${daily.date}:**\n**${daily.question.title}** : ${questionLink}`;
channel.send(response);
} else {
console.error('Channel not found');
}
} catch (error) {
console.error('Error fetching LeetCode daily challenge:', error);
}
}, {
scheduled: true,
timezone: "Asia/Kolkata"
});
});
client.on('messageCreate', async (message) => {
if (message.author.bot) return;
const args = message.content.split(' ');
const command = args[0].toLowerCase();
if (command === ';potd') {
try {
const daily = await lc.daily();
const questionLink = `https://leetcode.com${daily.link}`;
const embed = new EmbedBuilder()
.setTitle(`LeetCode Daily Challenge - ${daily.date}`)
.setURL(questionLink)
.setDescription(`**${daily.question.title}**`)
.setColor(0xD1006C)
.addFields(
{ name: 'Difficulty', value: daily.question.difficulty, inline: true },
{ name: 'Link', value: `[Click here](${questionLink})`, inline: true }
)
.setFooter({ text: 'Good luck solving today\'s problem!' });
message.channel.send({ embeds: [embed] });
} catch (error) {
console.error('Error fetching LeetCode daily challenge:', error);
message.channel.send('Sorry, I could not fetch the LeetCode daily challenge question.');
}
} else if (command === ';random') {
try {
let difficulty = args[1] ? args[1].toLowerCase() : null;
const difficultyLevel = { 'easy': 1, 'medium': 2, 'hard': 3 };
const difficultyColors = { 'easy': 0x00FF00, 'medium': 0xFFFF00, 'hard': 0xFF0000 }; // Green, Yellow, Red
if (leetcodeProblems.length === 0) {
await fetchLeetCodeProblems();
}
let filteredProblems = leetcodeProblems;
if (difficulty && difficultyLevel[difficulty]) {
filteredProblems = leetcodeProblems.filter(problem => problem.difficulty.level === difficultyLevel[difficulty]);
}
if (filteredProblems.length === 0) {
message.channel.send(`Sorry, I couldn't find any LeetCode problems with the specified difficulty level: ${difficulty}`);
return;
}
const randomIndex = Math.floor(Math.random() * filteredProblems.length);
const problem = filteredProblems[randomIndex].stat;
const questionLink = `https://leetcode.com/problems/${problem.question__title_slug}/`;
const embedColor = difficulty ? difficultyColors[difficulty] : 0x7289DA; // Default is Discord's blue
const embed = new EmbedBuilder()
.setTitle(`${problem.question__title}`)
.setURL(questionLink)
.setColor(embedColor)
.addFields(
{ name: 'Difficulty', value: difficulty ? difficulty.charAt(0).toUpperCase() + difficulty.slice(1) : 'N/A', inline: true },
{ name: 'Link', value: `[Solve Problem](${questionLink})`, inline: true },
{ name: 'Acceptance Rate', value: `${problem.total_acs} / ${problem.total_submitted} (${(problem.total_acs / problem.total_submitted * 100).toFixed(2)}%)`, inline: true }
)
.setFooter({ text: 'Good luck!' });
message.channel.send({ embeds: [embed] });
} catch (error) {
console.error('Error fetching random LeetCode question:', error);
message.channel.send('Sorry, I could not fetch a random LeetCode question.');
}
}else if (command === ';user' && args.length === 2) {
const username = args[1];
try {
const contestInfo = await lc.user_contest_info(username);
const responseMessage = `username : **${username}**\nContest : ${contestInfo.userContestRanking.attendedContestsCount}\nRating : ${Math.round(contestInfo.userContestRanking.rating)}\nTop : ${contestInfo.userContestRanking.topPercentage}%\nBadge : ${contestInfo.userContestRanking.badge ? contestInfo.userContestRanking.badge : 'No badge'}`;
message.channel.send(responseMessage);
} catch (error) {
console.error('Error fetching user info:', error);
message.channel.send('Sorry, I could not fetch the user info.');
}
} else if (command === ';streak' && args.length === 2) {
const username = args[1];
try {
const streakInfo = await lc.user(username);
let streakMessage;
if (streakInfo.consecutiveDays > 0) {
streakMessage = `**${username}** has solved a problem for ${streakInfo.consecutiveDays} consecutive days! Keep it up!`;
} else {
streakMessage = `**${username}** does not have a streak yet. Start solving problems to build your streak!`;
}
message.channel.send(streakMessage);
} catch (error) {
console.error('Error fetching streak info:', error);
message.channel.send('Sorry, I could not fetch the streak info.');
}
}
else if (command === ';help') {
const helpMessage = `**Available Commands:**\n
\`;potd\` - Shows the LeetCode Daily Challenge\n
\`;random\` - Shows a random LeetCode problem\n
\`;user <username>\` - Shows user Info\n
\`;streak <username>\` - Shows user Streak Info
\`;help\` - Shows help message`;
message.channel.send(helpMessage);
}
});
keepAlive();
client.login(process.env.TOKEN);