-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbot.js
342 lines (302 loc) · 10.8 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
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
import { spawn } from 'node:child_process';
import cron from 'node-cron';
import zulipInit from 'zulip-js';
import grind75_problems from './Grind75.json' assert { type: 'json' };
import { questionOfTheDay } from './queries.js';
let zulipClient;
if (process.env.ZULIP_USERNAME && process.env.ZULIP_API_KEY && process.env.ZULIP_REALM) {
zulipClient = await zulipInit({
username: process.env.ZULIP_USERNAME,
apiKey: process.env.ZULIP_API_KEY,
realm: process.env.ZULIP_REALM,
});
} else {
// Use the zuliprc file for configuration instead of environment variables
zulipClient = await zulipInit({ zuliprc: 'zuliprc' });
}
const baseLeetcodeURL = 'https://leetcode.com';
const timezone = process.env.DLB_TIMEZONE || 'Etc/UTC';
const cronSchedule = process.env.DLB_CRON_SCHEDULE || '0 0 * * *'; // See https://www.npmjs.com/package/node-cron#cron-syntax for more info
const messageReceiver = process.env.DLB_USER_ID ? [parseInt(process.env.DLB_USER_ID, 10)] : 'Daily LeetCode'; // Must be a Zulip user ID or a stream name
const messageType = process.env.DLB_USER_ID ? 'direct' : 'stream';
const messageTopic = process.env.DLB_TOPIC || 'Daily Leetcode Problem';
const slackWebhookURL = process.env.DLB_SLACK_WEBHOOK;
class LeetCodeBot {
static async run () {
cron.schedule(cronSchedule, async () => {
const date = new Date(); // '2022-12-17T10:00:00.000-05:00' <- Use this date string for testing Advent of Code functionality
const humanReadableDateString = date.toLocaleDateString('en-US', { weekday: 'long', day: 'numeric', month: 'short', timeZone: timezone });
console.info(`Getting leetcode problem for ${humanReadableDateString}`);
try {
let response = await fetch('https://leetcode.com/graphql', {
method: 'POST',
headers: {
authority: 'leetcode.com',
referer: 'https://leetdoce.com/problemset/',
'Content-Type': 'application/json',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36',
},
body: `{"query":"${questionOfTheDay}","operationName":"questionOfToday"}`
});
let leetcode_data;
if (response.ok) {
leetcode_data = (await response.json()).activeDailyCodingChallengeQuestion;
} else {
console.group('There was a problem fetching data from the Leetcode API.');
console.error(response.status, response.statusText);
console.groupCollapsed('Response body:')
console.error(await response.text(), '\n');
console.groupEnd();
console.groupEnd();
console.info('Trying alfa-leetcode-api...');
// If we can't get the response from the leetcode API directly, try alfa-leetcode-api.
// https://github.com/alfaArghya/alfa-leetcode-api
response = await fetch('https://alfa-leetcode-api.onrender.com/daily');
if (response.ok) {
leetcode_data = (await response.json());
// Structure the data in the original Leetcode API format
leetcode_data = {
question: {
difficulty: leetcode_data.difficulty,
title: leetcode_data.questionTitle,
},
link: leetcode_data.questionLink.match(/\/problems\/.*/)[0]
}
} else {
console.group('There was a problem fetching data from alfa-leetcode-api.');
console.error(response.status, response.statusText);
console.groupCollapsed('Response body:')
console.error(await response.text(), '\n');
console.groupEnd();
console.groupEnd();
console.group('Getting data from python script...');
leetcode_data = (await run_python()).data?.activeDailyCodingChallengeQuestion;
console.groupEnd();
}
}
// Choose problems from grind75 by selecting a random topic and then random questions for each difficulty from that topic
const topics = Object.keys(grind75_problems).filter((topic) => topic !== '//comment' && topic !== 'premium');
const topic = topics[random(topics.length - 1)];
const problems = Object.entries(grind75_problems[topic]).reduce((acc, [key, problems]) => {
acc[key] = problems[random(problems.length - 1)];
return acc;
}, {});
const messageData = {
date: humanReadableDateString,
problems: {
leetcode_daily: { ...leetcode_data?.question, link: leetcode_data?.link },
grind75: { topic, problems }
}
};
if (leetcode_data === undefined) {
messageData.problems.leetcode_daily = undefined;
}
// Get the problem of the day from Advent of Code if the current date is between Dec 1st and Dec 25th
const currentYear = date.getFullYear();
const dec_1st = new Date(`${currentYear}-12-01T00:00:00.000-05:00`); // Get date for Dec 1st EST
const dec_26th = new Date(`${currentYear}-12-26T00:00:00.000-05:00`); // Get date for Dec 26th EST
if (date >= dec_1st && date < dec_26th) {
const aoc_link = `https://adventofcode.com/${currentYear}/day/${date.getDate()}`; //
const aoc_html = await (await fetch(aoc_link)).text();
const title = aoc_html.match(/<h2>(.*)<\/h2>/)[1].replace(/---/g, '').trim();
messageData.problems.advent_of_code = { title, year: currentYear, link: aoc_link };
}
await this.postMessageToZulip(messageData);
if (slackWebhookURL) {
await this.postMessageToSlack(messageData);
}
} catch (error) {
console.group('Error getting problems:');
console.error(error);
console.groupEnd();
}
}, {
scheduled: true,
timezone
});
console.info(`Daily Leetcode Bot is running and will post to Zulip with the following configuration:
Schedule(cron): ${cronSchedule}
Recipient: ${messageReceiver}
Topic: ${messageTopic}
Timezone: ${timezone}`);
}
static async postMessageToZulip ({ date, problems }) {
let leetcode_message;
if (problems.leetcode_daily) {
leetcode_message = `1. (${problems.leetcode_daily.difficulty}) [${problems.leetcode_daily.title}](${baseLeetcodeURL}${problems.leetcode_daily.link})`
} else {
leetcode_message = `> There was a problem accessing the leetcode API.
> Find the daily problem on the calendar [here](https://leetcode.com/problemset/).`
}
let message = `${date}
\`Daily Question\` at [leetcode.com](https://leetcode.com/problemset/all/)
${leetcode_message}
\`Grind75\` at [techinterviewhandbook.org](https://www.techinterviewhandbook.org/grind75?mode=all&grouping=topics)
Topic is: ${problems.grind75.topic.replaceAll('_', ' ')}
${Object.entries(problems.grind75.problems).reduce((acc, [difficulty, problem]) => `${acc}1. (${difficulty}) [${problem.title}](${problem.link})\n`, '')}
`;
if (problems.advent_of_code) {
const emoji = ['snowflake', 'snowman', 'holiday_tree', 'santa', 'cabin-with-snow', 'gift'][random(5)];
message += `
\`Daily Puzzle\` at [adventofcode.com](https://adventofcode.com/)
:${emoji}:. [${problems.advent_of_code.title}](${problems.advent_of_code.link})
`;
}
console.info(' Posting message to Zulip:', `\n ${message.replaceAll('\n', '\n ')}`);
let params = {
to: messageReceiver,
type: messageType,
topic: messageTopic,
content: message,
};
try {
const response = await zulipClient.messages.send(params);
console.info(` Response: ${JSON.stringify(response, null, 4)}`);
} catch (error) {
console.error('Error posting message to Zulip:', error);
}
}
static async postMessageToSlack ({ date, problems }) {
const payload = {
blocks: [
{
type: "header",
text: {
type: "plain_text",
text: date
}
},
{
type: "context",
elements: [
{
type: "mrkdwn",
text: "`Daily Question` at <https://leetcode.com/problemset/all/|leetcode.com>"
}
]
},
{
type: "rich_text",
elements: [
{
type: "rich_text_list",
style: "ordered",
elements: [
{
type: "rich_text_section",
elements: [
{
type: "text",
text: `${problems.leetcode_daily ? `(${problems.leetcode_daily.difficulty}) ` : 'There was a problem with the Leetcode API.'}`
},
{
type: "link",
url: `${baseLeetcodeURL}${problems.leetcode_daily ? problems.leetcode_daily.link : '/problemset'}`,
text: problems.leetcode_daily ? problems.leetcode_daily.title : 'Find the daily problem on the calendar here',
}
]
}
]
}
]
},
{
type: "context",
elements: [
{
type: "mrkdwn",
text: `\`Grind75\` at <https://www.techinterviewhandbook.org/grind75?mode=all&grouping=topics|techinterviewhandbook.org>
Topic is: ${problems.grind75.topic.replaceAll('_', ' ')}`
}
]
},
{
type: "rich_text",
elements: [
{
type: "rich_text_list",
style: "ordered",
elements: []
}
]
}
]
};
Object.entries(problems.grind75.problems).forEach(([difficulty, problem]) => {
payload.blocks[4].elements[0].elements.push({
type: "rich_text_section",
elements: [{
"type": "text",
"text": `(${difficulty}) `
}, {
"type": "link",
"url": problem.link,
"text": problem.title,
}]
});
});
if (problems.advent_of_code) {
const emoji = ['snowflake', 'snowman', 'christmas_tree', 'santa', 'gift'][random(4)];
payload.blocks.push({
"type": "context",
"elements": [
{
"type": "mrkdwn",
"text": "`Daily Puzzle` at <https://adventofcode.com|adventofcode.com>"
}
]
});
payload.blocks.push({
"type": "section",
"text": {
"type": "mrkdwn",
"text": `:${emoji}:. <${problems.advent_of_code.link}|${problems.advent_of_code.title}>`
}
});
}
console.info(' Posting message to Slack:', `\n ${JSON.stringify(payload)}`);
try {
const response = await fetch(slackWebhookURL, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(payload),
});
const result = await response.text();
console.info(' Response:', result);
} catch (error) {
console.error('Error posting message to Slack:', error);
}
}
}
/**
* Returns a random number from 0 to max
* @type {(max: number) => number}
*/
const random = (max) => Math.floor(Math.random() * (max + 1));
/**
* Returns a JSON object containing the result of the get_daily_question.py script
* @returns { Promise<object> }
*/
async function run_python() {
return new Promise((resolve, reject) => {
let jsonFromPython;
const python = spawn('python', ['./get_daily_question.py']);
python.stdout.on('data', function (data) {
try {
jsonFromPython = JSON.parse(data.toString());
} catch (e) {
console.error(e);
resolve(data.toString());
}
});
python.on('close', (code) => {
console.info(`Python script finished with code ${code}`);
console.info('Data from python script:');
console.info(jsonFromPython);
resolve(jsonFromPython);
});
});
}
LeetCodeBot.run();