-
Notifications
You must be signed in to change notification settings - Fork 25
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
Sourcery refactored main branch #472
Conversation
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.
Sourcery timed out performing refactorings.
Due to GitHub API limits, only the first 60 comments can be shown.
keys = list(iterkeys(self)) | ||
keys.sort() | ||
keys = sorted(iterkeys(self)) | ||
args = ", ".join(["%s=%r" % (key, self[key]) for key in keys]) | ||
return "%s(%s)" % (self.__class__.__name__, args) | ||
return f"{self.__class__.__name__}({args})" |
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.
Function Object.__repr__
refactored with the following changes:
- Remove an unnecessary list construction call prior to sorting (
skip-sorted-list-construction
) - Replace interpolated string formatting with f-string (
replace-interpolation-with-fstring
)
if isinstance(x, (list, tuple)): | ||
return type(x)(objectify(v) for v in x) | ||
return x | ||
return type(x)(objectify(v) for v in x) if isinstance(x, (list, tuple)) else x |
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.
Function objectify
refactored with the following changes:
- Lift code into else after jump in control flow (
reintroduce-else
) - Replace if statement with if expression (
assign-if-exp
)
opts = dict(indent=4, default_flow_style=False) | ||
opts.update(options) | ||
opts = dict(indent=4, default_flow_style=False) | options |
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.
Function toYAML
refactored with the following changes:
- Merge dictionary updates via the union operator [×2] (
dict-assign-update-to-union
)
if not data: | ||
return {} | ||
return dict(zip(data[0], zip(data[0][10:], data[0][5:10]))) | ||
return dict(zip(data[0], zip(data[0][10:], data[0][5:10]))) if data else {} |
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.
Function get_batting
refactored with the following changes:
- Swap if/else branches of if expression to remove negation (
swap-if-expression
) - Lift code into else after jump in control flow (
reintroduce-else
) - Replace if statement with if expression (
assign-if-exp
)
if not data: | ||
return {} | ||
return dict(zip(data[1], zip(data[1][10:], data[1][5:10]))) | ||
return dict(zip(data[1], zip(data[1][10:], data[1][5:10]))) if data else {} |
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.
Function get_bowling
refactored with the following changes:
- Swap if/else branches of if expression to remove negation (
swap-if-expression
) - Lift code into else after jump in control flow (
reintroduce-else
) - Replace if statement with if expression (
assign-if-exp
)
chn = self.__guild.get_channel(channel) | ||
if chn: | ||
if chn := self.__guild.get_channel(channel): |
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.
Function BaseCustomCommand.get_overwrites_for
refactored with the following changes:
- Use named expression to simplify assignment and conditional (
use-named-expression
)
for reaction in self.__message.reactions: | ||
if str(reaction.emoji) == emoji: | ||
return [ | ||
return next( | ||
( | ||
[ | ||
CustomMember(member) | ||
async for member in reaction.users() | ||
if isinstance(member, discord.Member) | ||
] | ||
return [] | ||
for reaction in self.__message.reactions | ||
if str(reaction.emoji) == emoji | ||
), | ||
[], | ||
) |
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.
Function BaseCustomCommandOnMsg.reactions_users
refactored with the following changes:
- Use the built-in function
next
instead of a for-loop (use-next
)
if not ctx.invoked_subcommand: | ||
try: | ||
starboard_data: Dict[ | ||
str, Union[str, int, List[int], bool, None] | ||
] = self.bot.server_config[ctx.guild.id]["starboard"] | ||
except KeyError: | ||
return await self.bot.invoke_help_command(ctx) | ||
if ctx.invoked_subcommand: | ||
return | ||
try: | ||
starboard_data: Dict[ | ||
str, Union[str, int, List[int], bool, None] | ||
] = self.bot.server_config[ctx.guild.id]["starboard"] | ||
except KeyError: | ||
return await self.bot.invoke_help_command(ctx) | ||
|
||
channel: Optional[discord.TextChannel] = ctx.guild.get_channel( | ||
starboard_data.get("channel", 0) | ||
) | ||
limit: Optional[int] = starboard_data.get("limit") | ||
is_locked: Optional[bool] = starboard_data.get("is_locked") | ||
channel: Optional[discord.TextChannel] = ctx.guild.get_channel( | ||
starboard_data.get("channel", 0) | ||
) | ||
limit: Optional[int] = starboard_data.get("limit") | ||
is_locked: Optional[bool] = starboard_data.get("is_locked") | ||
|
||
ignore_channel = ", ".join( | ||
[ | ||
f"{ctx.guild.get_channel(c)} ({c})" | ||
for c in starboard_data.get("ignore_channel", []) | ||
] | ||
) | ||
max_duration: Optional[str] = starboard_data.get("max_duration") | ||
ignore_channel = ", ".join( | ||
[ | ||
f"{ctx.guild.get_channel(c)} ({c})" | ||
for c in starboard_data.get("ignore_channel", []) | ||
] | ||
) | ||
max_duration: Optional[str] = starboard_data.get("max_duration") | ||
|
||
return await ctx.reply( | ||
f"Configuration of this server [starboard]\n\n" | ||
f"`Channel :` **{channel.mention if channel else 'None'} ({starboard_data.get('channel')})**\n" | ||
f"`Limit :` **{limit}**\n" | ||
f"`Locked :` **{is_locked}**\n" | ||
f"`Ignore :` **{ignore_channel or 'None'}**\n" | ||
f"`Duration:` **{max_duration}**\n" | ||
) | ||
return await ctx.reply( | ||
f"Configuration of this server [starboard]\n\n" | ||
f"`Channel :` **{channel.mention if channel else 'None'} ({starboard_data.get('channel')})**\n" | ||
f"`Limit :` **{limit}**\n" | ||
f"`Locked :` **{is_locked}**\n" | ||
f"`Ignore :` **{ignore_channel or 'None'}**\n" | ||
f"`Duration:` **{max_duration}**\n" | ||
) |
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.
Function Configuration.starboard
refactored with the following changes:
- Add guard clause (
last-if-guard
)
if not ctx.invoked_subcommand: | ||
chn: discord.TextChannel = channel or ctx.channel | ||
if event.lower() not in events: | ||
return await ctx.reply( | ||
f"{ctx.author.mention} invalid event. Available events `{'`, `'.join(events)}`" | ||
) | ||
hooks: List[discord.Webhook] = await chn.webhooks() | ||
if len(hooks) >= 10: | ||
for hook in hooks: | ||
if hook is not None and hook.user.id == self.bot.user.id: # type: ignore | ||
webhook = hook | ||
post = {str(event.lower()): str(webhook.url)} | ||
await self.bot.mongo.parrot_db.logging.update_one( | ||
{"_id": ctx.guild.id}, {"$set": post}, upsert=True | ||
) | ||
break | ||
else: | ||
return await ctx.reply( | ||
f"{ctx.author.mention} can not register event (`{event.replace('_', ' ').title()}`) in {chn.mention}. This happens when channel has already 10 webhooks created." | ||
if ctx.invoked_subcommand: | ||
return | ||
chn: discord.TextChannel = channel or ctx.channel | ||
if event.lower() not in events: | ||
return await ctx.reply( | ||
f"{ctx.author.mention} invalid event. Available events `{'`, `'.join(events)}`" | ||
) | ||
hooks: List[discord.Webhook] = await chn.webhooks() | ||
if len(hooks) >= 10: | ||
for hook in hooks: | ||
if hook is not None and hook.user.id == self.bot.user.id: # type: ignore | ||
webhook = hook | ||
post = {event.lower(): str(webhook.url)} | ||
await self.bot.mongo.parrot_db.logging.update_one( | ||
{"_id": ctx.guild.id}, {"$set": post}, upsert=True | ||
) | ||
break | ||
else: | ||
webhook: discord.Webhook = await chn.create_webhook( | ||
name=self.bot.user.name, | ||
reason=f"On request from {ctx.author} ({ctx.author.id}) | Reason: Setting Up Logging", | ||
) | ||
await self.bot.mongo.parrot_db.logging.update_one( | ||
{"_id": ctx.guild.id}, | ||
{"$set": {str(event): str(webhook.url)}}, | ||
upsert=True, | ||
return await ctx.reply( | ||
f"{ctx.author.mention} can not register event (`{event.replace('_', ' ').title()}`) in {chn.mention}. This happens when channel has already 10 webhooks created." | ||
) | ||
await ctx.reply( | ||
f"{ctx.author.mention} all `{event.replace('_', ' ').title()}` will be posted on {chn.mention}" | ||
else: | ||
webhook: discord.Webhook = await chn.create_webhook( | ||
name=self.bot.user.name, | ||
reason=f"On request from {ctx.author} ({ctx.author.id}) | Reason: Setting Up Logging", | ||
) | ||
await self.bot.mongo.parrot_db.logging.update_one( | ||
{"_id": ctx.guild.id}, | ||
{"$set": {event: str(webhook.url)}}, | ||
upsert=True, | ||
) | ||
|
||
await ctx.reply( | ||
f"{ctx.author.mention} all `{event.replace('_', ' ').title()}` will be posted on {chn.mention}" | ||
) |
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.
Function Configuration.logging
refactored with the following changes:
- Add guard clause (
last-if-guard
) - Remove unnecessary casts to int, str, float or bool [×2] (
remove-unnecessary-cast
)
{"_id": ctx.guild.id}, {"$set": {str(event.lower()): ""}} | ||
{"_id": ctx.guild.id}, {"$set": {event.lower(): ""}} | ||
) | ||
|
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.
Function Configuration.logging_remove
refactored with the following changes:
- Remove unnecessary casts to int, str, float or bool (
remove-unnecessary-cast
)
"duration": duration if duration else None, | ||
"duration": duration or None, | ||
} | ||
} | ||
}, | ||
) | ||
|
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.
Function Configuration.warnadd
refactored with the following changes:
- Simplify if expression by using or (
or-if-exp-identity
)
if setting.lower() in ("ignore-role", "ignore_role", "ignorerole", "ignore"): | ||
if setting.lower() in { | ||
"ignore-role", | ||
"ignore_role", | ||
"ignorerole", | ||
"ignore", | ||
}: |
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.
Function Configuration.gsetup
refactored with the following changes:
- Use set when checking membership of a collection of literals (
collection-into-set
)
if ctx.invoked_subcommand is not None: | ||
return | ||
try: | ||
server_stats: Dict[str, Any] = self.bot.server_config[ctx.guild.id][ | ||
"stats_channels" | ||
] | ||
except KeyError: | ||
return await self.bot.invoke_help_command(ctx) | ||
table = [] | ||
table_role = [] | ||
if ctx.invoked_subcommand is None: | ||
try: | ||
server_stats: Dict[str, Any] = self.bot.server_config[ctx.guild.id][ | ||
"stats_channels" | ||
] | ||
except KeyError: | ||
return await self.bot.invoke_help_command(ctx) | ||
for key, value in server_stats.items(): | ||
if key != "role": | ||
chn = ( | ||
self.bot.get_channel(value["channel_id"]) | ||
if value.get("channel_id") | ||
else 0 | ||
) | ||
table.append( | ||
[ | ||
key.title(), | ||
f"#{chn.name}" if chn else "None", | ||
value.get("channel_type"), | ||
value.get("template"), | ||
] | ||
) | ||
for _role in server_stats.get("role", {}): | ||
role = ctx.guild.get_role(_role.get("role_id", 0)) | ||
channel = ctx.guild.get_channel(_role.get("channel_id", 0)) | ||
template = _role.get("template") | ||
channel_type = _role.get("channel_type") | ||
table_role.append( | ||
for key, value in server_stats.items(): | ||
if key != "role": | ||
chn = ( | ||
self.bot.get_channel(value["channel_id"]) | ||
if value.get("channel_id") | ||
else 0 | ||
) | ||
table.append( | ||
[ | ||
role.name if role else "None", | ||
channel.name if channel else "None", | ||
channel_type, | ||
template, | ||
key.title(), | ||
f"#{chn.name}" if chn else "None", | ||
value.get("channel_type"), | ||
value.get("template"), | ||
] | ||
) | ||
await ctx.send( | ||
f"""``` | ||
table_role = [] | ||
for _role in server_stats.get("role", {}): | ||
role = ctx.guild.get_role(_role.get("role_id", 0)) | ||
channel = ctx.guild.get_channel(_role.get("channel_id", 0)) | ||
template = _role.get("template") | ||
channel_type = _role.get("channel_type") | ||
table_role.append( | ||
[ | ||
role.name if role else "None", | ||
channel.name if channel else "None", | ||
channel_type, | ||
template, | ||
] | ||
) | ||
await ctx.send( | ||
f"""``` | ||
{str(tabulate(table, headers=["Name", "Channel", "Type", "Template"], tablefmt="pretty"))} | ||
`````` | ||
{str(tabulate(table_role, headers=["Role", "Channel", "Type", "Template"], tablefmt="pretty"))} | ||
```""" | ||
) | ||
) |
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.
Function Configuration.serverstats
refactored with the following changes:
- Move assignments closer to their usage (
move-assign
) - Add guard clause (
last-if-guard
)
easterified_data_set = {} | ||
easterified_data_set = {x: PfpEffects.closest(x) for x in data_set} | ||
|
||
for x in data_set: | ||
easterified_data_set[x] = PfpEffects.closest(x) |
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.
Function PfpEffects.easterify_effect
refactored with the following changes:
- Convert for loop into dictionary comprehension (
dict-comprehension
)
new_img = PfpEffects.join_images(img_squares) | ||
|
||
return new_img | ||
return PfpEffects.join_images(img_squares) |
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.
Function PfpEffects.mosaic_effect
refactored with the following changes:
- Inline variable that is immediately returned (
inline-immediately-returned-variable
)
error_embed = discord.Embed( | ||
return discord.Embed( | ||
colour=Colours.soft_red, | ||
title=random.choice(NEGATIVE_REPLIES), | ||
description=f"{desc}", # fuck you pycord | ||
) | ||
|
||
return error_embed |
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.
Function Fun.make_error_embed
refactored with the following changes:
- Inline variable that is immediately returned (
inline-immediately-returned-variable
)
if len(player_data) == 0: | ||
if not player_data: |
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.
Function Fun.send_score
refactored with the following changes:
- Simplify sequence length comparison (
simplify-len-comparison
)
if (animal := animal.lower()) in ( | ||
if (animal := animal.lower()) not in ( |
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.
Function Fun.animal_fact
refactored with the following changes:
- Add guard clause (
last-if-guard
)
if len(ret) >= 2048: | ||
return ret[0:2000] + " [...]" | ||
return ret | ||
return ret[:2000] + " [...]" if len(ret) >= 2048 else ret |
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.
Function Fun.urbandictionary
refactored with the following changes:
- Lift code into else after jump in control flow (
reintroduce-else
) - Replace if statement with if expression (
assign-if-exp
) - Replace a[0:x] with a[:x] and a[x:len(a)] with a[x:] (
remove-redundant-slice-index
) - Replace range(0, x) with range(x) (
remove-zero-from-range
)
if len(member.name) > 20: | ||
name = member.name[:20:] | ||
else: | ||
name = member.name | ||
name = member.name[:20:] if len(member.name) > 20 else member.name |
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.
Function Fun.ytcomment
refactored with the following changes:
- Replace if statement with if expression (
assign-if-exp
)
em.set_footer(text=f"{ctx.author.name}") | ||
else: | ||
em = discord.Embed( | ||
title=f"{member.name} reply!", | ||
description=f"{random.choice(t)}", | ||
timestamp=discord.utils.utcnow(), | ||
) | ||
em.set_footer(text=f"{ctx.author.name}") | ||
em.set_footer(text=f"{ctx.author.name}") |
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.
Function Fun.truth
refactored with the following changes:
- Hoist repeated code outside conditional statement (
hoist-statement-from-if
)
em.set_footer(text=f"{ctx.author}") | ||
else: | ||
em = discord.Embed( | ||
title=f"{member} reply!", | ||
description=f"{random.choice(t)}", | ||
timestamp=discord.utils.utcnow(), | ||
) | ||
em.set_footer(text=f"{ctx.author}") | ||
em.set_footer(text=f"{ctx.author}") |
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.
Function Fun.twister
refactored with the following changes:
- Hoist repeated code outside conditional statement (
hoist-statement-from-if
)
params = {"image_url": member.display_avatar.url, "axis": axis if axis else "X"} | ||
params = {"image_url": member.display_avatar.url, "axis": axis or "X"} |
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.
Function Fun.shear
refactored with the following changes:
- Simplify if expression by using or (
or-if-exp-identity
)
choose = "tails" if str(choose).lower() in ("tails", "tail", "t") else "heads" | ||
choose = "tails" if choose.lower() in {"tails", "tail", "t"} else "heads" |
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.
Function Fun.coinflip
refactored with the following changes:
- Use set when checking membership of a collection of literals (
collection-into-set
) - Remove unnecessary casts to int, str, float or bool (
remove-unnecessary-cast
)
if displayname not in new_name: | ||
return new_name | ||
return None | ||
return new_name if displayname not in new_name else None |
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.
Function Easter.find_separators
refactored with the following changes:
- Lift code into else after jump in control flow (
reintroduce-else
) - Replace if statement with if expression (
assign-if-exp
)
for index, command in enumerate(commands_list): | ||
for command in commands_list: |
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.
Function GroupHelpPageSource.format_page
refactored with the following changes:
- Remove unnecessary calls to
enumerate
when the index is not used (remove-unused-enumerate
)
alias = command.name if not parent else f"{parent} {command.name}" | ||
alias = f"{parent} {command.name}" if parent else command.name |
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.
Function PaginatedHelpCommand.get_command_signature
refactored with the following changes:
- Swap if/else branches of if expression to remove negation (
swap-if-expression
)
syntax = self.get_command_signature(command) | ||
if syntax: | ||
if syntax := self.get_command_signature(command): |
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.
Function PaginatedHelpCommand.common_command_formatting
refactored with the following changes:
- Use named expression to simplify assignment and conditional (
use-named-expression
)
if len(subcommands) == 0: | ||
if not subcommands: | ||
return await self.send_command_help(group) | ||
entries = subcommands | ||
# entries = await self.filter_commands(subcommands, sort=True) | ||
if len(entries) == 0: | ||
if not entries: |
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.
Function PaginatedHelpCommand.send_group_help
refactored with the following changes:
- Simplify sequence length comparison [×2] (
simplify-len-comparison
)
@@ -536,7 +535,6 @@ async def server_info(self, ctx: Context): | |||
for name, value, inline in fields: | |||
embed.add_field(name=name, value=value, inline=inline) | |||
|
|||
info = [] |
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.
Function Meta.server_info
refactored with the following changes:
- Use named expression to simplify assignment and conditional (
use-named-expression
) - Move assignment closer to its usage within a block (
move-assign-in-block
) - Convert for loop into list comprehension (
list-comprehension
) - Split conditional into multiple branches (
split-or-ifs
) - Merge duplicate blocks in conditional (
merge-duplicate-blocks
) - Remove redundant conditional (
remove-redundant-if
)
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.
Thank you for contributing to Parrot :)
1b7550e
to
a70521a
Compare
Sourcery Code Quality Report✅ Merging this PR will increase code quality in the affected files by 0.21%.
Here are some functions in these files that still need a tune-up:
Legend and ExplanationThe emojis denote the absolute quality of the code:
The 👍 and 👎 indicate whether the quality has improved or gotten worse with this pull request. Please see our documentation here for details on how these metrics are calculated. We are actively working on this report - lots more documentation and extra metrics to come! Help us improve this quality report! |
Branch
main
refactored by Sourcery.If you're happy with these changes, merge this Pull Request using the Squash and merge strategy.
See our documentation here.
Run Sourcery locally
Reduce the feedback loop during development by using the Sourcery editor plugin:
Review changes via command line
To manually merge these changes, make sure you're on the
main
branch, then run:Help us improve this pull request!