Skip to content
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

Refactor Code #78

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion api/routers/webhooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ def send_memes(webhook: Webhook, subreddits: Iterable[str], quantity: int):
tp.submit(send_meme, webhook, subreddits)
for _ in range(quantity - sent)
]
new_sent = sum([r.result() for r in results])
new_sent = sum(r.result() for r in results)
skipped += (quantity - sent) - new_sent
sent += new_sent
return sent, skipped
Expand Down
31 changes: 17 additions & 14 deletions bot/cogs/coc.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,11 +44,13 @@ async def on_raw_reaction_add(self, payload: discord.RawReactionActionEvent):
if payload.user_id == self.bot.user.id:
return

if self.session_message_id != 0:
if payload.message_id == self.session_message_id:
if payload.emoji.id == 859056281788743690:
if payload.user_id not in self.session_users:
self.session_users.append(payload.user_id)
if (
self.session_message_id != 0
and payload.message_id == self.session_message_id
and payload.emoji.id == 859056281788743690
and payload.user_id not in self.session_users
):
self.session_users.append(payload.user_id)
if payload.message_id != coc_message:
return

Expand All @@ -66,11 +68,13 @@ async def on_raw_reaction_remove(self, payload: discord.RawReactionActionEvent):
if payload.user_id == self.bot.user.id:
return

if self.session_message_id != 0:
if payload.message_id == self.session_message_id:
if payload.emoji.id == 859056281788743690:
if payload.user_id in self.session_users:
self.session_users.remove(payload.user_id)
if (
self.session_message_id != 0
and payload.message_id == self.session_message_id
and payload.emoji.id == 859056281788743690
and payload.user_id in self.session_users
):
self.session_users.remove(payload.user_id)

if payload.message_id != coc_message:
return
Expand Down Expand Up @@ -118,9 +122,8 @@ async def session_start(self, ctx: commands.context):
)

for member in self.role.members:
if member != ctx.author:
if member.status != discord.Status.offline:
pager.add_line(member.mention + ", ")
if member != ctx.author and member.status != discord.Status.offline:
pager.add_line(f'{member.mention}, ')

if not len(pager.pages):
return await ctx.send(
Expand Down Expand Up @@ -278,7 +281,7 @@ async def coc_invite(self, ctx: commands.Context, *, url: str = None):
for member_id in self.session_users:
if member_id != ctx.author.id:
member = self.bot.get_user(member_id)
pager.add_line(member.mention + ", ")
pager.add_line(f'{member.mention}, ')

if not len(pager.pages):
return await ctx.send(
Expand Down
5 changes: 2 additions & 3 deletions bot/cogs/github.py
Original file line number Diff line number Diff line change
Expand Up @@ -244,8 +244,7 @@ async def get_file_from_svg_url(
i, b""
) # removes everything that needs to be excluded (eg. the uncentered A+)
drawing = svg2rlg(BytesIO(res))
file = BytesIO(renderPM.drawToString(drawing, fmt=fmt))
return file
return BytesIO(renderPM.drawToString(drawing, fmt=fmt))

def process_theme(self, theme):
theme = theme.lower()
Expand All @@ -258,7 +257,7 @@ def repo_desc_format(result):
description = result["description"]
if not description:
return ""
return description if len(description) < 100 else (description[:100] + "...")
return description if len(description) < 100 else f'{description[:100]}...'

async def github_request(
self,
Expand Down
3 changes: 1 addition & 2 deletions bot/cogs/help_command.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,7 @@ def get_command_signature(self, command):

async def send_bot_help(self, mapping):
embed = discord.Embed(title="Bot Commands", colour=self.COLOUR)
description = self.context.bot.description
if description:
if description := self.context.bot.description:
embed.description = description

for cog, cmds in mapping.items():
Expand Down
3 changes: 2 additions & 1 deletion bot/cogs/rtfm.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,8 +74,9 @@ def session(self) -> aiohttp.ClientSession:
async def build(self, target) -> None:
url = self.targets[target]
req = await self.session.get(
self.url_overrides.get(target, url + "/objects.inv")
self.url_overrides.get(target, f'{url}/objects.inv')
)

if req.status != 200:
warnings.warn(
Warning(
Expand Down
4 changes: 2 additions & 2 deletions bot/cogs/stackexchange.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ async def stack_profile(self, ctx: commands.Context, **kwargs):
if not data["items"]:
return await ctx.send("You don't have an account in this site!")
profile = data["items"][0]
embed = Embed(title=site["name"] + " Profile", color=0x0077CC)
embed = Embed(title=f'{site["name"]} Profile', color=0x0077CC)

embed.add_field(name="Username", value=profile["display_name"], inline=False)
embed.add_field(name="Reputation", value=profile["reputation"], inline=False)
Expand Down Expand Up @@ -152,7 +152,7 @@ async def stackexchange_search(self, ctx: commands.Context, **kwargs):
embed.set_thumbnail(url=site["icon_url"])
if data["items"]:
for i, q in enumerate(data["items"], 1):
tags = "\u2800".join(["`" + t + "`" for t in q["tags"]])
tags = "\u2800".join([f'`{t}`' for t in q["tags"]])
embed.add_field(
name=str(i) + " " + html.unescape(q["title"]),
value=search_result_template.format(site=site, q=q, tags=tags),
Expand Down
9 changes: 5 additions & 4 deletions bot/cogs/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,10 +125,11 @@ async def source(self, ctx: commands.Context, *, command=None):
if command is None:
return await ctx.send(
embed=Embed(
description=f"My source can be found [here](https://github.com/TechStruck/TechStruck-Bot)!",
color=0x8ADCED
description='My source can be found [here](https://github.com/TechStruck/TechStruck-Bot)!',
color=0x8ADCED,
)
)
)


if command == "help":
src = type(self.bot.help_command)
Expand All @@ -143,7 +144,7 @@ async def source(self, ctx: commands.Context, *, command=None):
color=0x8ADCED
)
)

src = cmd.callback.__code__
module = cmd.callback.__module__
filename = src.co_filename
Expand Down
10 changes: 7 additions & 3 deletions bot/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,9 +77,13 @@ async def setprefix(self, ctx: commands.Context, *, prefix: str):
async def prefix(self, ctx: commands.Context):
"""View current prefix of bot"""
await ctx.send(
f"My prefix here is `"
+ (self.bot.prefix_cache[ctx.guild.id] if ctx.guild else ".")
+ "`"
(
(
'My prefix here is `'
+ (self.bot.prefix_cache[ctx.guild.id] if ctx.guild else ".")
)
+ "`"
)
)

@commands.command()
Expand Down
7 changes: 4 additions & 3 deletions bot/utils/embed_flag_input.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,11 +67,12 @@ def process_message_mentions(message: str) -> str:
return ""
for _type, _id in re.findall(r"(role|user):(\d{18})", message):
message = message.replace(
_type + ":" + _id, f"<@!{_id}>" if _type == "user" else f"<@&{_id}>"
f'{_type}:{_id}', f"<@!{_id}>" if _type == "user" else f"<@&{_id}>"
)

for label in ("mention", "ping"):
for role in ("everyone", "here"):
message = message.replace(label + ":" + role, f"@{role}")
message = message.replace(f'{label}:{role}', f"@{role}")
return message


Expand Down Expand Up @@ -172,7 +173,7 @@ def dict_to_embed(data: Dict[str, str], author: Union[User, Member] = None):
setattr(embed, field, value)
for field in "thumbnail", "image":
if value := data.pop(field, None):
getattr(embed, "set_" + field)(url=value)
getattr(embed, f'set_{field}')(url=value)

if data.pop("auto_author", False) and author:
embed.set_author(name=author.display_name, icon_url=str(author.avatar_url))
Expand Down
6 changes: 2 additions & 4 deletions bot/utils/fuzzy.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ def partial_ratio(a, b):
o = SequenceMatcher(None, short, long[start:end])
r = o.ratio()

if 100 * r > 99:
if r > 99 / 100:
return 100
scores.append(r)

Expand Down Expand Up @@ -157,9 +157,7 @@ def finder(text, collection, *, key=None, lazy=True):
suggestions.append((len(r.group()), r.start(), item))

def sort_key(tup):
if key:
return tup[0], tup[1], key(tup[2])
return tup
return (tup[0], tup[1], key(tup[2])) if key else tup

if lazy:
return (z for _, _, z in sorted(suggestions, key=sort_key))
Expand Down
8 changes: 5 additions & 3 deletions utils/db_backup.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,13 @@
async def backup():
conn = await asyncpg.connect(str(config.database_uri))
tables = ("users", "thanks", "guilds", "jokes")
data = {
field: [dict(rec) for rec in await conn.fetch("SELECT * FROM {}".format(field))]
return {
field: [
dict(rec)
for rec in await conn.fetch("SELECT * FROM {}".format(field))
]
for field in tables
}
return data


def main():
Expand Down
6 changes: 1 addition & 5 deletions utils/embed.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,11 +38,7 @@ def bot_type_converter(data, add_timestamp=False):
embed_data = data.get("embed")
file_names = data.get("files", [])

embed = None

if embed_data:
embed = build_embed(embed_data)

embed = build_embed(embed_data) if embed_data else None
return text, embed, [File(fn) for fn in file_names]


Expand Down