-
Notifications
You must be signed in to change notification settings - Fork 18
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
434 leetcode for codey #455
Merged
Merged
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
aa0f631
initial commit
mcpenguin b4201bc
added lc random command
mcpenguin ab3cad2
intermediate
mcpenguin 81a0b58
added tags and difficulty filter
mcpenguin b7c6d29
fixed some stuff
mcpenguin 7863275
lint
mcpenguin ba1ed8a
addressed comments
mcpenguin 721c39b
fixed lc id
mcpenguin File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
99 changes: 99 additions & 0 deletions
99
src/commandDetails/leetcode/leetcodeRandomCommandDetails.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,99 @@ | ||
import { container } from '@sapphire/framework'; | ||
import { Message, TextBasedChannel } from 'discord.js'; | ||
import { | ||
CodeyCommandDetails, | ||
CodeyCommandOptionType, | ||
SapphireAfterReplyType, | ||
SapphireMessageExecuteType, | ||
SapphireMessageResponseWithMetadata, | ||
} from '../../codeyCommand'; | ||
import { CodeyUserError } from '../../codeyUserError'; | ||
import { | ||
getMessageForLeetcodeProblem, | ||
getLeetcodeProblemDataFromId, | ||
createInitialValuesForTags, | ||
getListOfLeetcodeProblemIds, | ||
LeetcodeDifficulty, | ||
TOTAL_NUMBER_OF_PROBLEMS, | ||
} from '../../components/leetcode'; | ||
import { getRandomIntFrom1 } from '../../utils/num'; | ||
|
||
const leetcodeRandomExecuteCommand: SapphireMessageExecuteType = async ( | ||
_client, | ||
messageFromUser, | ||
args, | ||
): Promise<SapphireMessageResponseWithMetadata> => { | ||
const difficulty = <LeetcodeDifficulty | undefined>args['difficulty']; | ||
const tag = <string | undefined>args['tag']; | ||
|
||
return new SapphireMessageResponseWithMetadata('The problem will be loaded shortly...', { | ||
difficulty, | ||
tag, | ||
messageFromUser, | ||
}); | ||
}; | ||
|
||
const leetcodeRandomAfterMessageReply: SapphireAfterReplyType = async ( | ||
result, | ||
_sentMessage, | ||
): Promise<unknown> => { | ||
// The API might take more than 3 seconds to complete | ||
// Which is more than the timeout for slash commands | ||
// So we just send a separate message to the channel which the command was called from. | ||
|
||
const difficulty = <LeetcodeDifficulty | undefined>result.metadata['difficulty']; | ||
const tag = <string | undefined>result.metadata['tag']; | ||
const message = <Message<boolean>>result.metadata['messageFromUser']; | ||
const channel = <TextBasedChannel>message.channel; | ||
|
||
let problemId; | ||
if (typeof difficulty === 'undefined' && typeof tag === 'undefined') { | ||
problemId = getRandomIntFrom1(TOTAL_NUMBER_OF_PROBLEMS); | ||
} else { | ||
const problemIds = await getListOfLeetcodeProblemIds(difficulty, tag); | ||
const index = getRandomIntFrom1(problemIds.length) - 1; | ||
if (problemIds.length === 0) { | ||
throw new CodeyUserError(message, 'There are no problems with the specified filters.'); | ||
} | ||
problemId = problemIds[index]; | ||
} | ||
const problemData = await getLeetcodeProblemDataFromId(problemId); | ||
const content = getMessageForLeetcodeProblem(problemData).slice(0, 2000); | ||
|
||
await channel?.send(content); | ||
return; | ||
}; | ||
|
||
export const leetcodeRandomCommandDetails: CodeyCommandDetails = { | ||
name: 'random', | ||
aliases: ['r'], | ||
description: 'Get a random LeetCode problem.', | ||
detailedDescription: `**Examples:** | ||
\`${container.botPrefix}leetcode\`\n | ||
\`${container.botPrefix}leetcode random\``, | ||
|
||
isCommandResponseEphemeral: false, | ||
executeCommand: leetcodeRandomExecuteCommand, | ||
afterMessageReply: leetcodeRandomAfterMessageReply, | ||
options: [ | ||
{ | ||
name: 'difficulty', | ||
description: 'The difficulty of the problem.', | ||
type: CodeyCommandOptionType.STRING, | ||
required: false, | ||
choices: [ | ||
{ name: 'Easy', value: 'easy' }, | ||
{ name: 'Medium', value: 'medium' }, | ||
{ name: 'Hard', value: 'hard' }, | ||
], | ||
}, | ||
{ | ||
name: 'tag', | ||
description: 'The type of problem.', | ||
type: CodeyCommandOptionType.STRING, | ||
required: false, | ||
choices: createInitialValuesForTags(), | ||
}, | ||
], | ||
subcommandDetails: {}, | ||
}; |
46 changes: 46 additions & 0 deletions
46
src/commandDetails/leetcode/leetcodeSpecificCommandDetails.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
import { container } from '@sapphire/framework'; | ||
import { | ||
CodeyCommandDetails, | ||
CodeyCommandOptionType, | ||
SapphireMessageExecuteType, | ||
SapphireMessageResponse, | ||
} from '../../codeyCommand'; | ||
import { CodeyUserError } from '../../codeyUserError'; | ||
import { | ||
getMessageForLeetcodeProblem, | ||
getLeetcodeProblemDataFromId, | ||
} from '../../components/leetcode'; | ||
|
||
const leetcodeSpecificExecuteCommand: SapphireMessageExecuteType = async ( | ||
_client, | ||
messageFromUser, | ||
args, | ||
): Promise<SapphireMessageResponse> => { | ||
const problemId = <number>args['problem-ID']; | ||
if (!Number.isInteger(problemId)) { | ||
throw new CodeyUserError(messageFromUser, 'Problem ID must be an integer.'); | ||
} | ||
const result = await getLeetcodeProblemDataFromId(problemId); | ||
|
||
return getMessageForLeetcodeProblem(result); | ||
}; | ||
|
||
export const leetcodeSpecificCommandDetails: CodeyCommandDetails = { | ||
name: 'specific', | ||
aliases: ['spec', 's'], | ||
description: 'Get a LeetCode problem with specified problem ID.', | ||
detailedDescription: `**Examples:** | ||
\`${container.botPrefix}leetcode specific 1\``, | ||
|
||
isCommandResponseEphemeral: false, | ||
executeCommand: leetcodeSpecificExecuteCommand, | ||
options: [ | ||
{ | ||
name: 'problem-ID', | ||
description: 'The problem ID.', | ||
type: CodeyCommandOptionType.NUMBER, | ||
required: true, | ||
}, | ||
], | ||
subcommandDetails: {}, | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
import { Command } from '@sapphire/framework'; | ||
import { CodeyCommand, CodeyCommandDetails } from '../../codeyCommand'; | ||
import { leetcodeRandomCommandDetails } from '../../commandDetails/leetcode/leetcodeRandomCommandDetails'; | ||
import { leetcodeSpecificCommandDetails } from '../../commandDetails/leetcode/leetcodeSpecificCommandDetails'; | ||
|
||
const leetcodeCommandDetails: CodeyCommandDetails = { | ||
name: 'leetcode', | ||
aliases: [], | ||
description: 'Handle LeetCode functions.', | ||
detailedDescription: ``, // leave blank for now | ||
options: [], | ||
subcommandDetails: { | ||
random: leetcodeRandomCommandDetails, | ||
specific: leetcodeSpecificCommandDetails, | ||
}, | ||
defaultSubcommandDetails: leetcodeRandomCommandDetails, | ||
}; | ||
|
||
export class LeetcodeCommand extends CodeyCommand { | ||
details = leetcodeCommandDetails; | ||
|
||
public constructor(context: Command.Context, options: Command.Options) { | ||
super(context, { | ||
...options, | ||
aliases: leetcodeCommandDetails.aliases, | ||
description: leetcodeCommandDetails.description, | ||
detailedDescription: leetcodeCommandDetails.detailedDescription, | ||
}); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,160 @@ | ||
import axios from 'axios'; | ||
import { APIApplicationCommandOptionChoice } from 'discord-api-types/v9'; | ||
import { convertHtmlToMarkdown } from '../utils/markdown'; | ||
|
||
export const TOTAL_NUMBER_OF_PROBLEMS = 2577; | ||
|
||
const leetcodeIdUrl = 'https://lcid.cc/info'; | ||
const leetcodeApiUrl = 'https://leetcode.com/graphql'; | ||
const leetcodeUrl = 'https://leetcode.com/problems'; | ||
|
||
const LeetcodeTagsDict = { | ||
array: 'Array', | ||
string: 'String', | ||
'hash-table': 'Hash Table', | ||
'dynamic-programming': 'Dynamic Programming', | ||
math: 'Math', | ||
sorting: 'Sorting', | ||
greedy: 'Greedy', | ||
'depth-first-search': 'Depth-First Search', | ||
database: 'Database', | ||
'binary-search': 'Binary Search', | ||
'breadth-first-search': 'Breadth-First Search', | ||
tree: 'Tree', | ||
matrix: 'Matrix', | ||
'binary-tree': 'Binary Tree', | ||
'two-pointers': 'Two Pointers', | ||
'bit-manipulation': 'Bit Manipulation', | ||
stack: 'Stack', | ||
'heap-priority-queue': 'Heap (Priority Queue)', | ||
graph: 'Graph', | ||
design: 'Design', | ||
'prefix-sum': 'Prefix Sum', | ||
simulation: 'Simulation', | ||
counting: 'Counting', | ||
backtracking: 'Backtracking', | ||
'sliding-window': 'Sliding Window', | ||
}; | ||
|
||
interface LeetcodeTopicTag { | ||
name: string; | ||
} | ||
|
||
export enum LeetcodeDifficulty { | ||
'Easy', | ||
'Medium', | ||
'Hard', | ||
} | ||
|
||
interface LeetcodeIdProblemDataFromUrl { | ||
difficulty: LeetcodeDifficulty; | ||
likes: number; | ||
dislikes: number; | ||
categoryTitle: string; | ||
frontendQuestionId: number; | ||
paidOnly: boolean; | ||
title: string; | ||
titleSlug: string; | ||
topicTags: LeetcodeTopicTag[]; | ||
totalAcceptedRaw: number; | ||
totalSubmissionRaw: number; | ||
} | ||
|
||
interface LeetcodeProblemDataFromUrl { | ||
data: { | ||
question: { | ||
content: string; | ||
}; | ||
}; | ||
} | ||
|
||
interface LeetcodeProblemData { | ||
difficulty: LeetcodeDifficulty; | ||
likes: number; | ||
dislikes: number; | ||
categoryTitle: string; | ||
paidOnly: boolean; | ||
title: string; | ||
titleSlug: string; | ||
topicTags: LeetcodeTopicTag[]; | ||
totalAcceptedRaw: number; | ||
totalSubmissionRaw: number; | ||
contentAsMarkdown: string; | ||
problemId: number; | ||
} | ||
|
||
export const createInitialValuesForTags = (): APIApplicationCommandOptionChoice[] => { | ||
return [ | ||
...Object.entries(LeetcodeTagsDict).map((e) => { | ||
return { | ||
name: e[1], | ||
value: e[0], | ||
}; | ||
}), | ||
]; | ||
}; | ||
|
||
export const getLeetcodeProblemDataFromId = async ( | ||
problemId: number, | ||
): Promise<LeetcodeProblemData> => { | ||
const resFromLeetcodeById: LeetcodeIdProblemDataFromUrl = ( | ||
await axios.get(`${leetcodeIdUrl}/${problemId}`) | ||
).data; | ||
const resFromLeetcode: LeetcodeProblemDataFromUrl = ( | ||
await axios.get(leetcodeApiUrl, { | ||
params: { | ||
operationName: 'questionData', | ||
variables: { | ||
titleSlug: resFromLeetcodeById.titleSlug, | ||
}, | ||
query: | ||
'query questionData($titleSlug: String!) {\n question(titleSlug: $titleSlug) {\n questionId\n questionFrontendId\n boundTopicId\n title\n titleSlug\n content\n translatedTitle\n translatedContent\n isPaidOnly\n difficulty\n likes\n dislikes\n isLiked\n similarQuestions\n contributors {\n username\n profileUrl\n avatarUrl\n __typename\n }\n langToValidPlayground\n topicTags {\n name\n slug\n translatedName\n __typename\n }\n companyTagStats\n codeSnippets {\n lang\n langSlug\n code\n __typename\n }\n stats\n hints\n solution {\n id\n canSeeDetail\n __typename\n }\n status\n sampleTestCase\n metaData\n judgerAvailable\n judgeType\n mysqlSchemas\n enableRunCode\n enableTestMode\n envInfo\n libraryUrl\n __typename\n }\n}\n', | ||
}, | ||
}) | ||
).data; | ||
|
||
const result: LeetcodeProblemData = { | ||
...resFromLeetcodeById, | ||
contentAsMarkdown: convertHtmlToMarkdown(resFromLeetcode.data.question.content), | ||
problemId: problemId, | ||
}; | ||
return result; | ||
}; | ||
|
||
export const getListOfLeetcodeProblemIds = async ( | ||
difficulty?: LeetcodeDifficulty, | ||
tag?: string, | ||
): Promise<number[]> => { | ||
const filters = { | ||
...(typeof difficulty !== 'undefined' | ||
? { difficulty: difficulty.toString().toUpperCase() } | ||
: {}), | ||
...(typeof tag !== 'undefined' ? { tags: [tag] } : {}), | ||
}; | ||
const resFromLeetcode = ( | ||
await axios.get(leetcodeApiUrl, { | ||
params: { | ||
variables: { | ||
categorySlug: '', | ||
filters: filters, | ||
limit: 2000, | ||
skip: 0, | ||
}, | ||
query: | ||
'query problemsetQuestionList($categorySlug: String, $limit: Int, $skip: Int, $filters: QuestionListFilterInput) {\n problemsetQuestionList: questionList(\n categorySlug: $categorySlug\n limit: $limit\n skip: $skip\n filters: $filters\n ) {\n total: totalNum\n questions: data {\n acRate\n difficulty\n freqBar\n frontendQuestionId: questionFrontendId\n isFavor\n paidOnly: isPaidOnly\n status\n title\n titleSlug\n topicTags {\n name\n id\n slug\n }\n hasSolution\n hasVideoSolution\n }\n }\n}\n ', | ||
}, | ||
}) | ||
).data; | ||
const result = resFromLeetcode.data.problemsetQuestionList.questions.map( | ||
(question: { frontendQuestionId: number }) => question.frontendQuestionId, | ||
); | ||
return result; | ||
}; | ||
|
||
export const getMessageForLeetcodeProblem = (leetcodeProblemData: LeetcodeProblemData): string => { | ||
const title = `#${leetcodeProblemData.problemId}: ${leetcodeProblemData.title}`; | ||
const content = leetcodeProblemData.contentAsMarkdown; | ||
const url = `${leetcodeUrl}/${leetcodeProblemData.titleSlug}`; | ||
const difficulty = leetcodeProblemData.difficulty; | ||
return `**${title} - ${difficulty}**\n*Problem URL: ${url}*\n\n${content}`; | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
import TurndownService from 'turndown'; | ||
|
||
export const convertHtmlToMarkdown = (html: string): string => { | ||
const turndownService = new TurndownService(); | ||
return turndownService.turndown(html); | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Would we want to send multiple messages instead of just truncating the message?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Sending multiple messages might look weird if the truncation occurs in a weird spot, eg in the middle of a word.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
That is fair. I guess it might potentially mess up code blocks and equations as well, in which it might be more effort than what it is worth to detect them.