-
-
Notifications
You must be signed in to change notification settings - Fork 254
Add WTF Python Command #859
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
Merged
Merged
Changes from all commits
Commits
Show all changes
45 commits
Select commit
Hold shift + click to select a range
d3c9780
Add WTF Python Command
Shivansh-007 56ea9e2
Fix grammar in docstrings, remove redundant variable, remove the use …
Shivansh-007 d23cc4d
Fix indentation issues and make use of triple quotes
Shivansh-007 4dcc2fe
Update docstrings and remove redundant list()
Shivansh-007 415b7a4
Change minimum certainty to 75.
Shivansh-007 3b8eadd
Make 'make_embed' function a non async function
Shivansh-007 6465862
Try to unload WTFPython Extension if max fetch requests hit i.e. 3 el…
Shivansh-007 a2cdfe9
Correct log messages.
Shivansh-007 3ae3aad
Make flake8 happy :D
Shivansh-007 4a18a2d
Remove redundant class attributes and async functions.
Shivansh-007 2a518f9
Apply requested grammar and style changes.
Shivansh-007 a4c494f
Fix unload and load extension logic.
Shivansh-007 f82169f
Fix typo in `WTF_PYTHON_RAW_URL`
Shivansh-007 d893d42
Changed fuzzy_wuzzy to rapidfuzz
brad90four ba60b8a
Merge branch 'main' of https://github.com/python-discord/sir-lancebot…
brad90four a702969
Merge main
brad90four 1e7b581
Move wtf_python.py to bot/exts/utilities, flake8
brad90four 4c0ae39
Fix trailing commas and long lines
brad90four 62d3a81
# This is a combination of 3 commits.
brad90four 9d59b52
Squashing commits
brad90four 4eb7c67
Pulling from main
brad90four 2ca1691
Add debug logs, and send embed
brad90four f6e9d28
Add markdown file creation
brad90four 0eb3670
Move the list(map(str.strip , ...) to for loop
brad90four cc55239
Remove line
brad90four 5dcc43f
Use StringIO for file creation
brad90four 917de69
Update file creation with StringIO
brad90four d74c8f3
Remove embed file preview
brad90four f49c9e0
chore: update wtf_python docstring
brad90four 3adc085
chore: change regex to search, remove file preview
brad90four 8c1f3ec
feat: update caching as recommended
brad90four f3d752a
chore: remove logging statements
brad90four a1832be
feat: scheduled task for fetch_readme
brad90four 761a3f7
chore: fix hyperlink, remove dead code
brad90four a26ca12
fix: capitalization clean up
brad90four c942f32
chore: remove unused code
brad90four 170676c
chore: remove more unused code
brad90four 32a0f9a
feat: add light grey logo image in embed
brad90four 04d71f8
feat: add light grey image
brad90four bc64aa6
chore: remove debug log message
brad90four 2197fc6
feat: add found search result header
brad90four f60b724
feat: limit user query to 50 characters
brad90four 14e9d7b
cleanup: remove debug logging
brad90four cd58665
fix: restructure if not match statement
brad90four ca1e447
Merge branch 'main' into feature/wtf-python
Xithrius 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 hidden or 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,126 @@ | ||
import logging | ||
import random | ||
import re | ||
from typing import Optional | ||
|
||
import rapidfuzz | ||
from discord import Embed, File | ||
from discord.ext import commands, tasks | ||
|
||
from bot import constants | ||
from bot.bot import Bot | ||
|
||
log = logging.getLogger(__name__) | ||
|
||
WTF_PYTHON_RAW_URL = "http://raw.githubusercontent.com/satwikkansal/wtfpython/master/" | ||
BASE_URL = "https://github.com/satwikkansal/wtfpython" | ||
LOGO_PATH = "./bot/resources/utilities/wtf_python_logo.jpg" | ||
|
||
ERROR_MESSAGE = f""" | ||
Unknown WTF Python Query. Please try to reformulate your query. | ||
|
||
**Examples**: | ||
```md | ||
{constants.Client.prefix}wtf wild imports | ||
{constants.Client.prefix}wtf subclass | ||
{constants.Client.prefix}wtf del | ||
``` | ||
If the problem persists send a message in <#{constants.Channels.dev_contrib}> | ||
""" | ||
|
||
MINIMUM_CERTAINTY = 55 | ||
|
||
|
||
class WTFPython(commands.Cog): | ||
"""Cog that allows getting WTF Python entries from the WTF Python repository.""" | ||
|
||
def __init__(self, bot: Bot): | ||
self.bot = bot | ||
self.headers: dict[str, str] = {} | ||
self.fetch_readme.start() | ||
|
||
@tasks.loop(minutes=60) | ||
async def fetch_readme(self) -> None: | ||
"""Gets the content of README.md from the WTF Python Repository.""" | ||
async with self.bot.http_session.get(f"{WTF_PYTHON_RAW_URL}README.md") as resp: | ||
log.trace("Fetching the latest WTF Python README.md") | ||
if resp.status == 200: | ||
raw = await resp.text() | ||
self.parse_readme(raw) | ||
|
||
def parse_readme(self, data: str) -> None: | ||
""" | ||
Parses the README.md into a dict. | ||
|
||
It parses the readme into the `self.headers` dict, | ||
where the key is the heading and the value is the | ||
link to the heading. | ||
""" | ||
# Match the start of examples, until the end of the table of contents (toc) | ||
table_of_contents = re.search( | ||
r"\[👀 Examples\]\(#-examples\)\n([\w\W]*)<!-- tocstop -->", data | ||
)[0].split("\n") | ||
|
||
for header in list(map(str.strip, table_of_contents)): | ||
match = re.search(r"\[▶ (.*)\]\((.*)\)", header) | ||
if match: | ||
hyper_link = match[0].split("(")[1].replace(")", "") | ||
self.headers[match[0]] = f"{BASE_URL}/{hyper_link}" | ||
|
||
def fuzzy_match_header(self, query: str) -> Optional[str]: | ||
""" | ||
Returns the fuzzy match of a query if its ratio is above "MINIMUM_CERTAINTY" else returns None. | ||
|
||
"MINIMUM_CERTAINTY" is the lowest score at which the fuzzy match will return a result. | ||
The certainty returned by rapidfuzz.process.extractOne is a score between 0 and 100, | ||
with 100 being a perfect match. | ||
""" | ||
match, certainty, _ = rapidfuzz.process.extractOne(query, self.headers.keys()) | ||
return match if certainty > MINIMUM_CERTAINTY else None | ||
|
||
@commands.command(aliases=("wtf", "WTF")) | ||
async def wtf_python(self, ctx: commands.Context, *, query: str) -> None: | ||
""" | ||
Search WTF Python repository. | ||
|
||
Gets the link of the fuzzy matched query from https://github.com/satwikkansal/wtfpython. | ||
Usage: | ||
--> .wtf wild imports | ||
""" | ||
if len(query) > 50: | ||
embed = Embed( | ||
title=random.choice(constants.ERROR_REPLIES), | ||
description=ERROR_MESSAGE, | ||
colour=constants.Colours.soft_red, | ||
) | ||
match = None | ||
else: | ||
match = self.fuzzy_match_header(query) | ||
|
||
if not match: | ||
embed = Embed( | ||
title=random.choice(constants.ERROR_REPLIES), | ||
description=ERROR_MESSAGE, | ||
colour=constants.Colours.soft_red, | ||
) | ||
await ctx.send(embed=embed) | ||
return | ||
|
||
embed = Embed( | ||
title="WTF Python?!", | ||
colour=constants.Colours.dark_green, | ||
description=f"""Search result for '{query}': {match.split("]")[0].replace("[", "")} | ||
[Go to Repository Section]({self.headers[match]})""", | ||
) | ||
logo = File(LOGO_PATH, filename="wtf_logo.jpg") | ||
embed.set_thumbnail(url="attachment://wtf_logo.jpg") | ||
await ctx.send(embed=embed, file=logo) | ||
|
||
def cog_unload(self) -> None: | ||
"""Unload the cog and cancel the task.""" | ||
self.fetch_readme.cancel() | ||
|
||
|
||
def setup(bot: Bot) -> None: | ||
"""Load the WTFPython Cog.""" | ||
bot.add_cog(WTFPython(bot)) |
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
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.
Uh oh!
There was an error while loading. Please reload this page.