Skip to content

Commit

Permalink
Run black formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
Kreusada committed Jun 1, 2023
1 parent 7ab8514 commit 84f6592
Show file tree
Hide file tree
Showing 15 changed files with 79 additions and 63 deletions.
1 change: 1 addition & 0 deletions blackformatter/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,6 @@

__red_end_user_data_statement__ = get_end_user_data_statement(__file__)


async def setup(bot: Red):
await bot.add_cog(BlackFormatter(bot))
4 changes: 3 additions & 1 deletion blackformatter/black_formatter.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,9 @@ async def _black(self, ctx: commands.Context, line_length: Optional[int] = None)

try:
output = black.format_file_contents(
sort, fast=True, mode=black.FileMode(line_length=line_length or black.DEFAULT_LINE_LENGTH)
sort,
fast=True,
mode=black.FileMode(line_length=line_length or black.DEFAULT_LINE_LENGTH),
)
except black.NothingChanged:
await ctx.send("There was nothing to change in this code.")
Expand Down
4 changes: 1 addition & 3 deletions cogpaths/cogpaths.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,7 @@ async def red_delete_data_for_user(self, **kwargs):
async def cogpath(self, ctx: commands.Context, cog: CogConverter):
"""Get the paths for a cog."""
cog_path = pathlib.Path(inspect.getfile(cog.__class__)).parent.resolve()
cog_data_path = pathlib.Path(
data_manager.cog_data_path() / cog.qualified_name
).resolve()
cog_data_path = pathlib.Path(data_manager.cog_data_path() / cog.qualified_name).resolve()
if not os.path.exists(cog_data_path):
cog_data_path = None
if not isinstance(getattr(cog, "config", None), Config):
Expand Down
5 changes: 4 additions & 1 deletion consoleclearer/consoleclearer.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from redbot.core import commands
from redbot.core.bot import Red


class ConsoleClearer(commands.Cog):
"""Clear your console."""

Expand All @@ -27,5 +28,7 @@ async def clearconsole(self, ctx: commands.Context):
Completely clears [botname]'s console.
"""
os.system("clear" if os.name == "posix" else "cls")
print(f"Red console cleared | {datetime.datetime.utcnow().strftime('%b %d %Y %H:%M:%S')} (UTC)")
print(
f"Red console cleared | {datetime.datetime.utcnow().strftime('%b %d %Y %H:%M:%S')} (UTC)"
)
await ctx.send("Red console cleared.")
8 changes: 4 additions & 4 deletions flags/flags.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ async def convert(self, ctx: Context, argument: str) -> Optional[Dict[str, Union
neighbour_list = soup.find("ul", class_="flag-grid")
if neighbour_list:
for li in neighbour_list.find_all("li"):
neighbours[li.span.text] = alpha_2_to_unicode(li.img['src'][16:-4])
neighbours[li.span.text] = alpha_2_to_unicode(li.img["src"][16:-4])
ret["neighbours"] = neighbours

table = soup.find("table", class_="table-dl")
Expand Down Expand Up @@ -171,7 +171,7 @@ async def flag(self, ctx: Context, *, argument: CountryConverter):

menu = LabelledMenu()
menu.add_option("Flag Information", embed=embed, emoji="\N{WAVING WHITE FLAG}")

embed = discord.Embed(
title=title,
colour=await ctx.embed_colour(),
Expand All @@ -184,15 +184,15 @@ async def flag(self, ctx: Context, *, argument: CountryConverter):
overflow[k] = v
else:
embed.add_field(name=k, value=v)

for k, v in overflow.items():
embed.add_field(name=k, value=v, inline=False)

embed.set_thumbnail(url=image)
menu.add_option("Country Information", embed=embed, emoji="\N{EARTH GLOBE EUROPE-AFRICA}")
menu.set_neighbouring_countries(neighbours)
await menu.start(ctx)
#await menu(ctx, [embed], {"\N{CROSS MARK}": close_menu})
# await menu(ctx, [embed], {"\N{CROSS MARK}": close_menu})

@commands.command()
async def flagemojis(self, ctx: commands.Context, *countries: CountryConverter):
Expand Down
29 changes: 18 additions & 11 deletions flags/menus.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,33 +4,36 @@
from discord.interactions import Interaction
from redbot.core.commands import Context


def alpha_2_to_unicode(alpha_2):
return "".join(unicodedata.lookup("REGIONAL INDICATOR SYMBOL LETTER " + a) for a in alpha_2)


class LabelledMenuSelect(discord.ui.Select):
def __init__(self, neighbours: dict[str, str]):
options = [
discord.SelectOption(label=k, emoji=v)
for k, v in neighbours.items()
]
options = [discord.SelectOption(label=k, emoji=v) for k, v in neighbours.items()]
super().__init__(placeholder="Neighbouring countries", options=options, row=1)

async def callback(self, interaction: discord.Interaction):
await interaction.response.send_message(
f"Get information about {self.values[0]} with the command `{self.view.context.clean_prefix}flag {self.values[0]}`!",
ephemeral=True
ephemeral=True,
)


class LabelledMenuButton(discord.ui.Button):
async def callback(self, interaction: discord.Interaction):
self.grey_all_buttons()
self.style = discord.ButtonStyle.green
await interaction.response.edit_message(view=self.view, **self.view.options[self.label]["kwargs"])
await interaction.response.edit_message(
view=self.view, **self.view.options[self.label]["kwargs"]
)

def grey_all_buttons(self):
for button in self.view.children:
button.style = discord.ButtonStyle.grey


class LabelledMenu(discord.ui.View):
def __init__(self):
super().__init__()
Expand All @@ -44,9 +47,9 @@ def add_option(
label: str,
/,
content: Optional[str] = None,
*,
*,
embed: Optional[discord.Embed] = None,
emoji: Optional[str] = None
emoji: Optional[str] = None,
):
self.options[label] = {"emoji": emoji, "kwargs": {"embed": embed, "content": content}}
self.__insertion_order.append(label)
Expand All @@ -60,7 +63,9 @@ def set_neighbouring_countries(self, neighbours: dict[str, str]):
async def start(self, ctx: Context):
self.context = ctx
self.children[0].style = discord.ButtonStyle.green
self.message = await ctx.send(**self.options[self.__insertion_order[0]]["kwargs"], view=self)
self.message = await ctx.send(
**self.options[self.__insertion_order[0]]["kwargs"], view=self
)

async def on_timeout(self):
for child in self.children:
Expand All @@ -69,6 +74,8 @@ async def on_timeout(self):

async def interaction_check(self, interaction: discord.Interaction):
if interaction.user.id != self.context.author.id:
await interaction.response.send_message("You are not allowed to interact with this.", ephemeral=True)
await interaction.response.send_message(
"You are not allowed to interact with this.", ephemeral=True
)
return False
return True
return True
18 changes: 9 additions & 9 deletions onthisday/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,6 @@ async def convert(self, ctx: Context, arg: str) -> datetime.datetime:

class YearDropdown(discord.ui.Select):
def __init__(self, otd: "OnThisDay", /):

self.otd = otd
cy = current_year()
options = [
Expand Down Expand Up @@ -212,8 +211,9 @@ async def display_events(
event = self.year_data[year]
years_ago = int(self.year) - int("".join(filter(str.isdigit, year)))
content = (
event["content"] + "\n\n" +
f"This event occured on the __{date_suffix(self.date_number)} of {MONTH_MAPPING[self.month_number].capitalize()}, {year}__."
event["content"]
+ "\n\n"
+ f"This event occured on the __{date_suffix(self.date_number)} of {MONTH_MAPPING[self.month_number].capitalize()}, {year}__."
)
embed = discord.Embed(
title=f"On this day, {years_ago} years ago...",
Expand All @@ -222,8 +222,7 @@ async def display_events(
)
embed.set_footer(text="See the below links for related wikipedia articles")
_d = {
f"The year '{year}'": "https://en.wikipedia.org/wiki/"
+ year,
f"The year '{year}'": "https://en.wikipedia.org/wiki/" + year,
f"The date '{self.date_number.zfill(2)}/{self.month_number.zfill(2)}'": self.date_wiki,
}
embed.add_field(
Expand Down Expand Up @@ -251,9 +250,7 @@ async def run_otd(
) as session:
if session.status != 200:
return await ctx.maybe_send_embed(
warning(
"An error occured whilst retrieving information for this day."
)
warning("An error occured whilst retrieving information for this day.")
)
content = await session.json()
except aiohttp.ClientError:
Expand All @@ -271,7 +268,10 @@ async def run_otd(
if random:
await self.display_events(ctx, year=choice(list(data.keys())))
else:
await ctx.send("Choose a year range to select from:", view=YearRangeDropdownView(self),)
await ctx.send(
"Choose a year range to select from:",
view=YearRangeDropdownView(self),
)

def cache_date(self, date: Optional[datetime.datetime], /) -> Dict[str, int]:
if date is None:
Expand Down
30 changes: 17 additions & 13 deletions pypi/pypi.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,49 +126,53 @@ async def pypi(self, ctx, project: str):
)

embed.add_field(
name="Installation",
value=box(f"pip install -U {info['name']}"),
inline=False
name="Installation", value=box(f"pip install -U {info['name']}"), inline=False
)

filtered_links = dict(filter(lambda x: URL_RE.match(x[1]), list(info["project_urls"].items())))
filtered_links = dict(
filter(lambda x: URL_RE.match(x[1]), list(info["project_urls"].items()))
)
for link in info["project_urls"].values():
match = GIT_REPO_RE.match(link)
if not match or match.group(1) == "sponsors":
continue
try:
details = await self.make_request(("https://api.github.com/repos/" + link[19:]).rstrip(".git"))
details = await self.make_request(
("https://api.github.com/repos/" + link[19:]).rstrip(".git")
)
except ValueError:
default_branch = None
else:
default_branch = details["default_branch"]
break
else:
default_branch = None

if default_branch:
embed.add_field(
name="Development Installation",
value=box(f"pip install -U git+{link}@{default_branch}#egg={info['name']}", lang="fix"),
value=box(
f"pip install -U git+{link}@{default_branch}#egg={info['name']}", lang="fix"
),
inline=False,
)

values = []
for release in list(releases.keys())[-5:]:
if not (r := releases[release]):
continue
release_time = r[-1]['upload_time'][:10]
release_time = "-".join(reversed(release_time.split("-"))) # format date properly
release_time = r[-1]["upload_time"][:10]
release_time = "-".join(reversed(release_time.split("-"))) # format date properly
values.append(f"+ {release} (~{release_time})")

embed.add_field(
name="Recent Releases",
value=box("\n".join(values), lang="diff"),
inline=False
name="Recent Releases", value=box("\n".join(values), lang="diff"), inline=False
)

if requires_dist := info["requires_dist"]:
value = "\n".join("• " + d.replace("(", "[").replace(")", "]") for d in requires_dist[:10])
value = "\n".join(
"• " + d.replace("(", "[").replace(")", "]") for d in requires_dist[:10]
)
if remaining := requires_dist[10:]:
value += f"\nand {len(remaining)} more..."
embed.add_field(
Expand Down
3 changes: 2 additions & 1 deletion pypi/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,11 @@
from discord.ui import Button, View
from typing import Dict


class JumpUrlView(View):
def __init__(self, pypi_url: str, *, project_urls: Dict[str, str]):
super().__init__()
button = Button(label="Page on PyPi", url=pypi_url, row=1)
self.add_item(button)
for index, (name, url) in enumerate(project_urls.items()):
self.add_item(Button(label=name, url=url, row=math.floor(index / 3 + 2)))
self.add_item(Button(label=name, url=url, row=math.floor(index / 3 + 2)))
1 change: 1 addition & 0 deletions quotes/quotes.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from redbot.core.bot import Red
from redbot.core.utils.chat_formatting import bold, warning


class Quotes(commands.Cog):
"""Get a random quote."""

Expand Down
10 changes: 2 additions & 8 deletions roleboards/roleboards.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,10 +50,7 @@ async def topmembers(self, ctx: commands.Context, index: ValidUserIndex):
"""
data = get_members(ctx.guild, index=index)
pages = format_embed_pages(
ctx,
data=data,
data_type="members",
embed_colour=await ctx.embed_colour()
ctx, data=data, data_type="members", embed_colour=await ctx.embed_colour()
)
menu = SimpleMenu(pages, use_select_menu=True)
await menu.start(ctx)
Expand All @@ -70,10 +67,7 @@ async def toproles(self, ctx: commands.Context, index: ValidRoleIndex):
"""
data = get_roles(ctx.guild, index=index)
pages = format_embed_pages(
ctx,
data=data,
data_type="roles",
embed_colour=await ctx.embed_colour()
ctx, data=data, data_type="roles", embed_colour=await ctx.embed_colour()
)
menu = SimpleMenu(pages, use_select_menu=True)
await menu.start(ctx)
11 changes: 8 additions & 3 deletions roleboards/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from redbot.core.commands import BadArgument, Context, Converter
from redbot.core.utils.chat_formatting import box


class ValidRoleIndex(Converter):
async def convert(self, ctx: Context, argument):
try:
Expand All @@ -30,6 +31,7 @@ async def convert(self, ctx: Context, argument):
)
return argument


def format_embed_pages(
ctx: Context,
*,
Expand All @@ -44,7 +46,7 @@ def format_embed_pages(
total_data = len(getattr(ctx.guild, data_type))

if data_type == "roles":
total_data -= 1 # @everyone
total_data -= 1 # @everyone

for sector in data:
description = "\n".join(
Expand All @@ -67,19 +69,22 @@ def format_embed_pages(

return pages


def yield_chunks(l, n):
for i in range(0, len(l), n):
yield l[i : i + n]


def get_roles(guild: discord.Guild, *, index: int):
key = lambda x: len(x.members)
roles = [r for r in guild.roles if r.id != guild.id] # exclude @everyone
roles = [r for r in guild.roles if r.id != guild.id] # exclude @everyone
top_roles = sorted(roles, key=key, reverse=True)
data = [(x.name, len(x.members)) for x in top_roles[:index]]
return list(yield_chunks(data, 10))


def get_members(guild: discord.Guild, *, index: int):
key = lambda x: len(x.roles)
top_members = sorted([x for x in guild.members], key=key, reverse=True)
data = [(x.display_name, len(x.roles) - 1) for x in top_members[:index]]
return list(yield_chunks(data, 10))
return list(yield_chunks(data, 10))
Loading

0 comments on commit 84f6592

Please sign in to comment.