Skip to content

Commit

Permalink
refactor: cleanup code
Browse files Browse the repository at this point in the history
event.py and clash_of_code.py are excepted.

- remove i18n
- create a sub-module in utils for API scrappers
- remove some useless functions...
- fix annotations
- reformat files using bandit
  • Loading branch information
AiroPi committed Aug 7, 2022
1 parent 56ffe96 commit 534b407
Show file tree
Hide file tree
Showing 20 changed files with 128 additions and 924 deletions.
78 changes: 38 additions & 40 deletions src/cogs/doc.py
Original file line number Diff line number Diff line change
@@ -1,90 +1,88 @@
from __future__ import annotations

from typing import TYPE_CHECKING
from urllib import parse

import discord
from discord import app_commands
from discord.ext import commands
from aiohttp import ClientSession
from bs4 import BeautifulSoup
from discord import app_commands
from discord.ext import commands

from utils.constants import BUG_CENTER_ID
from utils.i18n import _
# from .utils import checkers
# from .utils.misc import delete_with_emote

if TYPE_CHECKING:
from main import HelpCenterBot


class Doc(commands.Cog):
def __init__(self, bot: 'HelpCenterBot'):
self.bot = bot
def __init__(self, bot: HelpCenterBot) -> None:
self.bot: HelpCenterBot = bot
self.bot.tree.add_command(self.doc, guild=discord.Object(id=BUG_CENTER_ID))

@app_commands.command(
name='doc',
description='Shows 4 or fewer links referring to a documentation on readthedocs.io :D',
)
@app_commands.describe(
doc="The documentation you want to search for.",
query="The search query."
name="doc",
description="Shows 4 or fewer links referring to a documentation on readthedocs.io :D",
)
@app_commands.describe(doc="The documentation you want to search for.", query="The search query.")
# @checkers.authorized_channels()
async def doc(self,
inter: discord.Interaction,
doc: str,
query: str):

url = 'https://readthedocs.org/api/v2/search/'
async def doc(self, inter: discord.Interaction, doc: str, query: str) -> None:
url = "https://readthedocs.org/api/v2/search/"
params = {
'q': query,
'project': doc,
'version': 'master',
"q": query,
"project": doc,
"version": "master",
}
async with ClientSession() as session:
async with session.get(url, params=params) as r:
json = await r.json()
print(json)

if not json.get('count'):
return await inter.response.send_message(_('Nothing found.', inter))
if not json.get("count"):
return await inter.response.send_message("Nothing found.")

embed = discord.Embed(title=_("{} Results (click here for a complete search)".format(json['count'])),
url="{}/en/stable/search.html?q={}".format(json['results'][0]['domain'], query))
embed = discord.Embed(
title=f"{json['count']} Results (click here for a complete search)",
url=f"{json['results'][0]['domain']}/en/stable/search.html?q={query}",
)

description = ""

for result in json['results'][:4]:
for result in json["results"][:4]:
try:
for block in result['blocks'][:2]:
description += f"\n[{block['title']}]({result['domain']}{result['path']}?highlight={query}#{block['id']})"
for block in result["blocks"][:2]:
description += (
f"\n[{block['title']}]({result['domain']}{result['path']}?highlight={query}#{block['id']})"
)
except KeyError:
# embed.description += f"\n[{result['title']}]({result['domain']}{result['path']}?highlight={query}#{block['id']})"
pass

embed.description = description

embed.set_footer(text=_('Documentations provided by https://readthedocs.org'))
await inter.response.send_message(_("Results for query **{0}** and documentation **{1}**".format(query, doc)), embed=embed)
# await delete_with_emote(self.bot, inter.author, await inter.original_message())
embed.set_footer(text="Documentations provided by https://readthedocs.org")
await inter.response.send_message("Results for query **{query}** and documentation **{doc}**", embed=embed)

@doc.autocomplete('doc')
@doc.autocomplete("doc")
async def doc_autocomplete(self, interaction: discord.Interaction, current: str) -> list[app_commands.Choice[str]]:
if len(current) < 4:
return [app_commands.Choice(name='discord.py', value='discord.py')]
return [app_commands.Choice(name="discord.py", value="discord.py")]

async with ClientSession() as session:
async with session.get("https://readthedocs.org/search/?type=project&version=latest&q=" + parse.quote_plus(current)) as r:
async with session.get(
"https://readthedocs.org/search/?type=project&version=latest&q=" + parse.quote_plus(current)
) as r:
result = await r.text()
soup = BeautifulSoup(result, 'html.parser')
soup = BeautifulSoup(result, "html.parser")

return [
app_commands.Choice(name=value, value=value)
for tag in soup.select('#content > div > div > div > div.module > div > div.module-list > div > ul > li > p.module-item-title > a')
if (value := tag.get_text().split(' (')[0].strip()) or True
for tag in soup.select(
"#content > div > div > div > div.module > div > div.module-list > div > ul > li > p.module-item-title > a"
)
if (value := tag.get_text().split(" (")[0].strip()) or True
][:25]


async def setup(bot: 'HelpCenterBot'):
async def setup(bot: HelpCenterBot) -> None:
await bot.add_cog(Doc(bot))
bot.logger.info("Extension [doc] loaded successfully.")
30 changes: 16 additions & 14 deletions src/cogs/googleit.py
Original file line number Diff line number Diff line change
@@ -1,41 +1,43 @@
from __future__ import annotations

from typing import TYPE_CHECKING
from urllib import parse

import discord
from discord import app_commands
from discord.ext import commands

# from .utils import checkers
# from .utils.misc import delete_with_emote
from utils.i18n import _
from utils.constants import BUG_CENTER_ID

if TYPE_CHECKING:
from main import HelpCenterBot


class GoogleIt(commands.Cog):
def __init__(self, bot: 'HelpCenterBot') -> None:
def __init__(self, bot: HelpCenterBot) -> None:
"""Allow you to transform a query to a google research using https://letmegooglethat.com."""
self.bot = bot
self.bot: HelpCenterBot = bot
self.bot.tree.add_command(self.google_it, guild=discord.Object(id=BUG_CENTER_ID))

@app_commands.command(
name='googleit',
description='Show how to do a google search :D',
name="googleit",
description="Show how to do a google search :D",
)
# @checkers.authorized_channels()
async def google_it(self, inter: discord.Interaction, search: str) -> None: # Using string (with *, arg) instead of array (*arg) to prevent argument missing.
async def google_it(
self, inter: discord.Interaction, search: str
) -> None: # Using string (with *, arg) instead of array (*arg) to prevent argument missing.
"""Return an url link that animate a google research."""

stringed_array = " ".join(word[:50] for word in search.split(' ')[:32]) # Maximum of 32 words, and a word has 50 chars max.
stringed_array = " ".join(
word[:50] for word in search.split(" ")[:32]
) # Maximum of 32 words, and a word has 50 chars max.
query = parse.quote_plus(stringed_array)

await inter.response.send_message(_("The google tool is very powerful, see how it works!\n", inter) +
f"<https://googlethatforyou.com/?q={query}>")
# await delete_with_emote(self.bot, inter.user, await inter.original_message())
await inter.response.send_message(
f"The google tool is very powerful, see how it works!\n<https://googlethatforyou.com/?q={query}>"
)


async def setup(bot: 'HelpCenterBot') -> None:
async def setup(bot: HelpCenterBot) -> None:
await bot.add_cog(GoogleIt(bot))
bot.logger.info("Extension [google_it] loaded successfully.")
43 changes: 14 additions & 29 deletions src/cogs/lines.py
Original file line number Diff line number Diff line change
@@ -1,53 +1,38 @@
from typing import TYPE_CHECKING

import discord
from discord import app_commands, ui
from discord.ext import commands
from discord import ui
from discord import app_commands
from typing_extensions import Self

from utils.constants import BUG_CENTER_ID

# from .utils.misc import delete_with_emote
from utils.i18n import _

if TYPE_CHECKING:
from main import HelpCenterBot


# LANGUAGES = ["python", "javascript", "typescript", "java", "rust", "lisp", "elixir"]


# async def lines_autocomplete(inter: discord.ApplicationCommandInteraction, user_input: str) -> list[str]:
# return [lang for lang in LANGUAGES + [user_input] if user_input.lower() in lang]

class LinesModal(ui.Modal, title='Add lines to your code'):
language = ui.TextInput(label='Language')
code = ui.TextInput(label='Code', style=discord.TextStyle.paragraph, min_length=5, max_length=1950)

async def on_submit(self, inter: discord.Interaction):
class LinesModal(ui.Modal, title="Add lines to your code"):
language = ui.TextInput[Self](label="Language")
code = ui.TextInput[Self](label="Code", style=discord.TextStyle.paragraph, min_length=5, max_length=1950)

numbered_code = '\n'.join(f'{i+1:>3} | {line}' for i, line in enumerate(str(self.code).splitlines()))
async def on_submit(self, interaction: discord.Interaction) -> None:
numbered_code: str = "\n".join(f"{i+1:>3} | {line}" for i, line in enumerate(str(self.code).splitlines()))

await inter.response.send_message(_('Numbered code of {0} :\n').format(inter.user) +
'```' + (str(self.language) or '') + '\n' +
numbered_code +
'\n```')
# await delete_with_emote(inter.client, ctx.author, await ctx.original_message())
await interaction.response.send_message(
f"Numbered code of {interaction.user} :\n```{str(self.language) or ''}\n{numbered_code}\n```"
)


class Lines(commands.Cog):
def __init__(self, bot: 'HelpCenterBot') -> None:
self.bot = bot
def __init__(self, bot: HelpCenterBot) -> None:
self.bot: HelpCenterBot = bot
self.bot.tree.add_command(self.lines, guild=discord.Object(id=BUG_CENTER_ID))

@app_commands.command(
name='lines',
description='Ajouter le numéro des lignes à votre code.'
)
@app_commands.command(name="lines", description="Ajouter le numéro des lignes à votre code.")
async def lines(self, inter: discord.Interaction) -> None:
await inter.response.send_modal(LinesModal())


async def setup(bot: 'HelpCenterBot') -> None:
async def setup(bot: HelpCenterBot) -> None:
await bot.add_cog(Lines(bot))
bot.logger.info("Extension [lines] loaded successfully.")
2 changes: 1 addition & 1 deletion src/cogs/miscellaneous.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,9 @@
from discord.ext import commands
from typing_extensions import Self # TODO: remove on 3.11 release

from utils.api.gist import create_new_gist, delete_gist
from utils.constants import BUG_CENTER_ID
from utils.custom_errors import CustomError
from utils.gist import create_new_gist, delete_gist

if TYPE_CHECKING:
from re import Pattern
Expand Down
4 changes: 2 additions & 2 deletions src/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ def __init__(self) -> None:
# self.before_invoke(self.set_command_language)
self.add_check(self.is_on_bug_center)

async def setup_hook(self):
async def setup_hook(self) -> None:
for ext in self.initial_extensions:
try:
await self.load_extension(ext)
Expand All @@ -65,7 +65,7 @@ async def on_ready(self) -> None:
logger.info(f"Logged in as : {bot_user.name}")
logger.info(f"ID : {bot_user.id}")

def is_on_bug_center(self, ctx: "Context[HelpCenterBot]") -> bool:
def is_on_bug_center(self, ctx: commands.Context[HelpCenterBot]) -> bool:
if ctx.guild and ctx.guild.id != BUG_CENTER_ID:
raise custom_errors.NotInBugCenter()
return True
Expand Down
Binary file removed src/resources/locale/en_EN/LC_MESSAGES/help_center.mo
Binary file not shown.
19 changes: 0 additions & 19 deletions src/resources/locale/en_EN/LC_MESSAGES/help_center.po

This file was deleted.

Binary file not shown.
Loading

0 comments on commit 534b407

Please sign in to comment.