Skip to content

Tasks (Sourcery refactored)#9

Open
sourcery-ai[bot] wants to merge 1 commit intotasksfrom
sourcery/tasks
Open

Tasks (Sourcery refactored)#9
sourcery-ai[bot] wants to merge 1 commit intotasksfrom
sourcery/tasks

Conversation

@sourcery-ai
Copy link
Copy Markdown

@sourcery-ai sourcery-ai Bot commented Sep 10, 2022

Pull Request #8 refactored by Sourcery.

If you're happy with these changes, merge this Pull Request using the Squash and merge strategy.

NOTE: As code is pushed to the original Pull Request, Sourcery will
re-run and update (force-push) this Pull Request with new refactorings as
necessary. If Sourcery finds no refactorings at any point, this Pull Request
will be closed automatically.

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 tasks branch, then run:

git fetch origin sourcery/tasks
git merge --ff-only FETCH_HEAD
git reset HEAD^

Help us improve this pull request!

Comment thread main.py

self.db: Optional[motor_asyncio.AsyncIOMotorClient] = None
self.models = list()
self.models = []
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Bot.__init__ refactored with the following changes:

Comment thread main.py
Comment on lines 80 to 97

if platform == "linux" or platform == "linux2" or platform == "darwin":
if platform in ["linux", "linux2", "darwin", "win32"]:
# os.system("clear")
jurigged.watch(pattern="./extensions/*.py")

self.logger.info(f"--Pro Clubs Nation Bot {self.config.version}")
self.logger.info("Connected to {} guild(s)".format(len(self.guilds)))
self.logger.info(f"Logged in as {self.user}.")
self.logger.info(f"Extensions: {', '.join(self.ext)}")


elif platform == "win32":
# os.system('cls')
jurigged.watch(pattern="./extensions/*.py")

self.logger.info(f"--Pro Clubs Nation Bot {self.config.version}")
self.logger.info("Connected to {} guild(s)".format(len(self.guilds)))
self.logger.info(f"Connected to {len(self.guilds)} guild(s)")
self.logger.info(f"Logged in as {self.user}.")
self.logger.info(f"Extensions: {', '.join(self.ext)}")
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Bot.on_ready refactored with the following changes:

This removes the following comments ( why? ):

# os.system('cls')

Comment thread extensions/botutil.py
if show_seconds:
return f"{minutes_fmt} and {seconds_fmt}"
return f"{minutes_fmt}"
return f"{minutes_fmt} and {seconds_fmt}" if show_seconds else f"{minutes_fmt}"
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function strf_delta refactored with the following changes:

Comment thread extensions/botutil.py
async def get_async(self):
async with httpx.AsyncClient(timeout=None) as client:
return await client.get(url)
return await client.get(self)
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function BotInfo.get_async refactored with the following changes:

Comment thread extensions/botutil.py
Comment on lines -235 to -238
guild_list = []
guild_list = [f"[ {guild.name} ]" for guild in self.bot.guilds]

for guild in self.bot.guilds:
guild_list.append(f"[ {guild.name} ]")
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function BotInfo._guild_names refactored with the following changes:

Comment thread extensions/botutil.py
Comment on lines -320 to +316

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Found the following improvement in Function BotInfo._server_info:

Comment on lines -38 to +45
if ctx.author.id == 111252573054312448 or ctx.author.id == 421064675267051531:
await ctx.message.delete()
threads = await ChannelConverter().convert(ctx, "verification-threads")
general = await ChannelConverter().convert(ctx, "general-discussion")
embed = Embed(
title="Welcome to PCN Discord",
description=f"""1. Discord is provided as a courtesy by the owners of PCN, meaning that it is a privilege, not a right
if ctx.author.id not in [111252573054312448, 421064675267051531]:
return
await ctx.message.delete()
threads = await ChannelConverter().convert(ctx, "verification-threads")
general = await ChannelConverter().convert(ctx, "general-discussion")
embed = Embed(
title="Welcome to PCN Discord",
description=f"""1. Discord is provided as a courtesy by the owners of PCN, meaning that it is a privilege, not a right
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function DiscordVerification.verify_init refactored with the following changes:

Comment on lines -108 to +151
await ctx.author.add_role(await RoleConverter().convert(ctx, "Waiting Verification"), "Waiting for verification.")
await ctx.author.remove_role(await RoleConverter().convert(ctx, "New Member"), "Verification started")
await ctx.author.add_role(await RoleConverter().convert(ctx, "Waiting Verification"), "Waiting for verification.")
await ctx.author.remove_role(await RoleConverter().convert(ctx, "New Member"), "Verification started")

thread = await channel.create_public_thread(
name=f"{ctx.author.display_name}'s Verification",
auto_archive_duration=AutoArchiveDuration.ONE_WEEK,
reason="Verification Thread",
# invitable=False,
)
await thread.add_member(ctx.author.id)
thread = await channel.create_public_thread(
name=f"{ctx.author.display_name}'s Verification",
auto_archive_duration=AutoArchiveDuration.ONE_WEEK,
reason="Verification Thread",
# invitable=False,
)
await thread.add_member(ctx.author.id)

if not previous_tag:
previous_tag = "--"
if not previous_tag:
previous_tag = "--"

await thread.send(
f"Welcome to your verification thread, {ctx.author.mention}."
"\nThis thread was created automatically by the bot due to your Gamer Tag not being found.\n\n"
"**Provided Information:**\n\n"
f"Gamertag: **{current_tag}**\n"
f"Previous Gamertags: **{previous_tag}**\n"
"Verified Onsite: **False**"
"\n\n**Please make sure you have Direct Messages enabled for this server."
"\nYou will be notified via DM when access is granted.**"
"\nTo enble DMs for this server only on mobile, click server name > Allow Direct Messages."
"\nTo enable DMs for this server only on desktop, click server name > Privacy Settings > Allow Direct Messages."
"\n\n**Discord verifications are automatically checked every 24 hours.**"
)
await thread.send(
f"Welcome to your verification thread, {ctx.author.mention}."
"\nThis thread was created automatically by the bot due to your Gamer Tag not being found.\n\n"
"**Provided Information:**\n\n"
f"Gamertag: **{current_tag}**\n"
f"Previous Gamertags: **{previous_tag}**\n"
"Verified Onsite: **False**"
"\n\n**Please make sure you have Direct Messages enabled for this server."
"\nYou will be notified via DM when access is granted.**"
"\nTo enble DMs for this server only on mobile, click server name > Allow Direct Messages."
"\nTo enable DMs for this server only on desktop, click server name > Privacy Settings > Allow Direct Messages."
"\n\n**Discord verifications are automatically checked every 24 hours.**"
)


await ctx.send(f"{ctx.author.mention} Your verification thread has been created here: {thread.mention}", ephemeral=True)

existing_verification = await VerificationQueue.find_one({"discord_id": ctx.author.id})
if existing_verification is None:
waiting_verification = VerificationQueue(
discord_id=ctx.author.id,
discord_name=ctx.author.display_name,
gamertag=current_tag,
status="New",
reason="Waiting for website verification",
updated=datetime.now(),
discord_thread=thread.id,
)
await waiting_verification.save()
await ctx.send(f"{ctx.author.mention} Your verification thread has been created here: {thread.mention}", ephemeral=True)

existing_verification = await VerificationQueue.find_one({"discord_id": ctx.author.id})
if existing_verification is None:
waiting_verification = VerificationQueue(
discord_id=ctx.author.id,
discord_name=ctx.author.display_name,
gamertag=current_tag,
status="New",
reason="Waiting for website verification",
updated=datetime.now(),
discord_thread=thread.id,
)
await waiting_verification.save()
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function DiscordVerification.create_thread refactored with the following changes:

Comment thread extensions/player.py
Comment on lines -62 to +63
self.logger.error(e)
elif gamertag is not None:
self.logger.error(e)
else:
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function PlayerStats.player_stats refactored with the following changes:

Comment thread extensions/queue.py
Comment on lines -149 to +165
db_repsonse = orjson.loads(search_response)

if not db_repsonse:
if not (db_repsonse := orjson.loads(search_response)):
return False
else:
for db_player in db_repsonse:
if len(db_repsonse) <= 1:
async with session.get(self.bot.config.urls.players.format(db_player['slug'])) as gamertag_lookup:
if gamertag_lookup.status == 200:
lookup_player = await gamertag_lookup.text()
player_found = orjson.loads(lookup_player)

if len(player_found) < 1:
return False
else:
return True
else:
if re.match(doc.gamertag, db_player["title"]['rendered'], flags=re.I):
async with session.get(self.bot.config.urls.players.format(db_player['slug'])) as gamertag_lookup:
if gamertag_lookup.status == 200:
lookup_player = await gamertag_lookup.text()
player_found = orjson.loads(lookup_player)

if len(player_found) < 1:
return False
else:
return True
for db_player in db_repsonse:
if len(db_repsonse) <= 1:
async with session.get(self.bot.config.urls.players.format(db_player['slug'])) as gamertag_lookup:
if gamertag_lookup.status == 200:
lookup_player = await gamertag_lookup.text()
player_found = orjson.loads(lookup_player)

return len(player_found) >= 1
elif re.match(doc.gamertag, db_player["title"]['rendered'], flags=re.I):
async with session.get(self.bot.config.urls.players.format(db_player['slug'])) as gamertag_lookup:
if gamertag_lookup.status == 200:
lookup_player = await gamertag_lookup.text()
player_found = orjson.loads(lookup_player)

return len(player_found) >= 1
Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function fetch_api refactored with the following changes:

@sourcery-ai
Copy link
Copy Markdown
Author

sourcery-ai Bot commented Sep 10, 2022

Sourcery Code Quality Report

✅  Merging this PR will increase code quality in the affected files by 1.23%.

Quality metrics Before After Change
Complexity 13.01 🙂 11.51 🙂 -1.50 👍
Method Length 127.19 😞 125.00 😞 -2.19 👍
Working memory 12.01 😞 11.87 😞 -0.14 👍
Quality 49.58% 😞 50.81% 🙂 1.23% 👍
Other metrics Before After Change
Lines 985 960 -25
Changed files Quality Before Quality After Quality Change
main.py 75.19% ⭐ 78.17% ⭐ 2.98% 👍
extensions/botutil.py 55.28% 🙂 55.11% 🙂 -0.17% 👎
extensions/discord_verifier.py 27.05% 😞 28.84% 😞 1.79% 👍
extensions/player.py 49.91% 😞 50.01% 🙂 0.10% 👍
extensions/queue.py 40.61% 😞 44.21% 😞 3.60% 👍

Here are some functions in these files that still need a tune-up:

File Function Complexity Length Working Memory Quality Recommendation
extensions/discord_verifier.py DiscordVerification.create_thread 53 ⛔ 659 ⛔ 22 ⛔ 5.81% ⛔ Refactor to reduce nesting. Try splitting into smaller methods. Extract out complex expressions
extensions/botutil.py BotInfo.debug_info 10 🙂 572 ⛔ 14 😞 33.65% 😞 Try splitting into smaller methods. Extract out complex expressions
extensions/queue.py fetch_api 18 🙂 193 😞 15 😞 34.64% 😞 Try splitting into smaller methods. Extract out complex expressions
extensions/queue.py Queue.check_queue 15 🙂 255 ⛔ 13 😞 35.76% 😞 Try splitting into smaller methods. Extract out complex expressions
extensions/player.py PlayerStats.player_stats 18 🙂 259 ⛔ 11 😞 36.51% 😞 Try splitting into smaller methods. Extract out complex expressions

Legend and Explanation

The emojis denote the absolute quality of the code:

  • ⭐ excellent
  • 🙂 good
  • 😞 poor
  • ⛔ very poor

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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

0 participants