From 85614a66c5ad56c365f0d25d0f6d9186939e077c Mon Sep 17 00:00:00 2001 From: Sourcery AI <> Date: Thu, 17 Mar 2022 07:55:04 +0000 Subject: [PATCH] 'Refactored by Sourcery' --- cogs/announcements.py | 13 +++++- cogs/moderation.py | 5 +-- cogs/neil.py | 12 +++--- cogs/polling.py | 95 ++++++++++++++++++++---------------------- cogs/roleassignment.py | 25 +++++------ 5 files changed, 73 insertions(+), 77 deletions(-) diff --git a/cogs/announcements.py b/cogs/announcements.py index 5f81833..ac2ced6 100644 --- a/cogs/announcements.py +++ b/cogs/announcements.py @@ -152,8 +152,17 @@ async def sh_announcement(self, ctx): embed_list = discord.Embed() embed_list.title = "All Created Events: " for i in range(ann_len): - outstr = "Target Channel: " + str(self.ann_list[i][5]) + "\n Description: " + str(self.ann_list[i][2]) - embed_list.add_field(name=str(self.ann_list[i][0]) + " - " + str(self.ann_list[i][1]), value=outstr) + outstr = ( + f"Target Channel: {str(self.ann_list[i][5])}" + + "\n Description: " + + str(self.ann_list[i][2]) + ) + + embed_list.add_field( + name=f'{str(self.ann_list[i][0])} - {str(self.ann_list[i][1])}', + value=outstr, + ) + await ctx.send(embed=embed_list) @commands.command() diff --git a/cogs/moderation.py b/cogs/moderation.py index a3ab296..6f79519 100644 --- a/cogs/moderation.py +++ b/cogs/moderation.py @@ -9,10 +9,7 @@ def __init__(self, client): @commands.command() async def purge(self, ctx, amount = 5): await ctx.channel.purge(limit = amount + 1) - if amount == 1: - pluralstring = 'message was' - else: - pluralstring = 'messages were' + pluralstring = 'message was' if amount == 1 else 'messages were' await ctx.send(f'{amount} {pluralstring} purged.') @commands.command() diff --git a/cogs/neil.py b/cogs/neil.py index a0610b1..0994df2 100644 --- a/cogs/neil.py +++ b/cogs/neil.py @@ -45,9 +45,7 @@ def makestring(rule, length): while not validstart: oldwords = random.choice(list(rule.keys())).split(' ') #random starting words - if oldwords[0] == '': - pass - else: + if oldwords[0] != '': if (ord(oldwords[0][0]) >= 65) and (ord(oldwords[0][0]) <= 90): validstart = True elif ord(oldwords[0][0]) >= 97 and ord(oldwords[0][0]) <= 122: @@ -56,11 +54,11 @@ def makestring(rule, length): string = ' '.join(oldwords) + ' ' - for i in range(length): + for _ in range(length): try: key = ' '.join(oldwords) newword = random.choice(rule[key]) - string += newword + ' ' + string += f'{newword} ' for word in range(len(oldwords)): oldwords[word] = oldwords[(word + 1) % len(oldwords)] oldwords[-1] = newword @@ -70,7 +68,7 @@ def makestring(rule, length): lastperiodindex = string.rfind(".") if lastperiodindex == -1: - return string[0:len(string)-1] + "." + return string[:-1] + "." string = string[:lastperiodindex+1] return string @@ -78,7 +76,7 @@ def makestring(rule, length): string = string[0].upper() + string[1:] lastperiodindex = string.rfind(".") if lastperiodindex == -1: - return string[0:len(string)-1] + "." + return string[:-1] + "." string = string[:lastperiodindex+1] return string diff --git a/cogs/polling.py b/cogs/polling.py index 6f741ee..035f4e6 100644 --- a/cogs/polling.py +++ b/cogs/polling.py @@ -45,14 +45,12 @@ async def createpoll(self, ctx, channel : discord.TextChannel): takingOptions = True emojisDone = [] while takingOptions: - echoOptionsString = '' - for option in options: - echoOptionsString += f"{option[0]} {option[1]}\n" + echoOptionsString = ''.join(f"{option[0]} {option[1]}\n" for option in options) await ctx.send(f"Type your poll answer.\nType the emote corresponding to the option first, then add a space, then type the answer. For example, \'👍 Yes\'.\nIf you are done with your options, type 'done'.\nCurrent options:\n{echoOptionsString}") try: option = await self.client.wait_for('message', check = lambda message: message.author == ctx.author, timeout = 120.0) if option.content == 'done': - if len(options) > 0: + if options: takingOptions = False else: await ctx.send("At least one option must be provided!") @@ -90,9 +88,10 @@ async def createpoll(self, ctx, channel : discord.TextChannel): except ValueError: await ctx.send("Invalid time entered. Please try again.") - optionsString = '' - for optionTuple in options: - optionsString += (f'{optionTuple[0]} {optionTuple[1]}\n') + optionsString = ''.join( + f'{optionTuple[0]} {optionTuple[1]}\n' for optionTuple in options + ) + pollEmbed = discord.Embed(title = f'Poll: {question}', description = description, color = discord.Colour.from_rgb(254, 254, 254)) pollEmbed.add_field(name = 'Options (react to vote)', value = optionsString, inline = True) #blank fields to force new line @@ -102,9 +101,10 @@ async def createpoll(self, ctx, channel : discord.TextChannel): endtimestring = endtime.strftime("%m/%d/%Y, %H:%M:%S") pollEmbed.set_footer(text = f"Poll closes at {endtimestring}\nPoll created by {ctx.author.name}#{ctx.author.discriminator}", icon_url = ctx.author.avatar_url) - resultsstring = '' - for option in options: - resultsstring += f'{option[0]} ░░░░░░░░░░ 0% (0)\n' + resultsstring = ''.join( + f'{option[0]} ░░░░░░░░░░ 0% (0)\n' for option in options + ) + pollEmbed.add_field(name = 'Results', value = resultsstring, inline = True) await channel.send(embed = pollEmbed) @@ -122,16 +122,15 @@ async def createpoll(self, ctx, channel : discord.TextChannel): closeMessage = await channel.fetch_message(pollMessage.id) closeEmbed = closeMessage.embeds[0] - closeEmbed.title = '[Closed] ' + closeEmbed.title + closeEmbed.title = f'[Closed] {closeEmbed.title}' #change 'closes' in the footer to 'closed' currentFooterText = closeEmbed.footer.text authoriconurl = closeEmbed.footer.icon_url - newFooterText = currentFooterText[:10] + 'd' + currentFooterText[11:] + newFooterText = f'{currentFooterText[:10]}d{currentFooterText[11:]}' closeEmbed.set_footer(text = newFooterText, icon_url = authoriconurl) await message.edit(embed = closeEmbed) self.activePollMessageIDs.remove(pollMessage.id) - #timeout except asyncio.TimeoutError: await ctx.send('Poll creation timed out.') return @@ -151,41 +150,39 @@ async def on_raw_reaction_add(self,payload): async def updatePollResults(self, payload): """Performs a count of the reactions of the message in which the poll is contained, and updates the Results field of the corresponding embed.""" - if payload.message_id in self.activePollMessageIDs: - channel = await self.client.fetch_channel(payload.channel_id) - message = await channel.fetch_message(payload.message_id) - pollembed = message.embeds[0] - - #makes shallow copy of reaction list and ensure entries are sorted in descending order - reactionslist = sorted(message.reactions[:], key = lambda reaction: reaction.count, reverse = True) - totalreactions = 0 - #remove the bot's count to get the 'true' polling numbers - for reaction in reactionslist: - reaction.count -= 1 - totalreactions += reaction.count - #removes existing embed - pollembed.remove_field(-1) - - #add new embed - resultsstring = '' - for reaction in reactionslist: - if totalreactions > 0: - reactPercentage = 100*(reaction.count / totalreactions) - else: - reactPercentage = 0 - nearestPercentage = round(reactPercentage) - fullBlocks = nearestPercentage // 10 - rem = nearestPercentage - 10*fullBlocks - if rem >= 5: - partialBlocks = 1 - else: - partialBlocks = 0 - totalBlocks = partialBlocks + fullBlocks - blocksString = '█' * fullBlocks + partialBlocks*'▓' + (10-totalBlocks)*'░' - resultsstring += f'{reaction.emoji} {blocksString} {round(reactPercentage,1)}% ({reaction.count})\n' - pollembed.add_field(name = 'Results', value = resultsstring, inline = True) - - await message.edit(embed = pollembed) + if payload.message_id not in self.activePollMessageIDs: + return + channel = await self.client.fetch_channel(payload.channel_id) + message = await channel.fetch_message(payload.message_id) + pollembed = message.embeds[0] + + #makes shallow copy of reaction list and ensure entries are sorted in descending order + reactionslist = sorted(message.reactions[:], key = lambda reaction: reaction.count, reverse = True) + totalreactions = 0 + #remove the bot's count to get the 'true' polling numbers + for reaction in reactionslist: + reaction.count -= 1 + totalreactions += reaction.count + #removes existing embed + pollembed.remove_field(-1) + + #add new embed + resultsstring = '' + for reaction in reactionslist: + if totalreactions > 0: + reactPercentage = 100*(reaction.count / totalreactions) + else: + reactPercentage = 0 + nearestPercentage = round(reactPercentage) + fullBlocks = nearestPercentage // 10 + rem = nearestPercentage - 10*fullBlocks + partialBlocks = 1 if rem >= 5 else 0 + totalBlocks = partialBlocks + fullBlocks + blocksString = '█' * fullBlocks + partialBlocks*'▓' + (10-totalBlocks)*'░' + resultsstring += f'{reaction.emoji} {blocksString} {round(reactPercentage,1)}% ({reaction.count})\n' + pollembed.add_field(name = 'Results', value = resultsstring, inline = True) + + await message.edit(embed = pollembed) @commands.Cog.listener() async def on_message_delete(self,message): @@ -205,7 +202,7 @@ async def createpoll_error(self, ctx, error): @commands.command() async def checkactivepolls(self, ctx): """Prints current active polls in terminal.""" - print(str(self.activePollMessageIDs)) + print(self.activePollMessageIDs) def setup(client): client.add_cog(Polling(client)) diff --git a/cogs/roleassignment.py b/cogs/roleassignment.py index 2a5a009..e0a0d98 100644 --- a/cogs/roleassignment.py +++ b/cogs/roleassignment.py @@ -34,12 +34,8 @@ async def createroleassignment(self, ctx, message_id): if not acceptable: await ctx.send("Format not correct. Try again.") else: - splitassoclist = [] - for element in assoclist: - splitassoclist.append(element.split(' ', 1)) - appenddict = {} - for element in splitassoclist: - appenddict[element[0]] = element[1] + splitassoclist = [element.split(' ', 1) for element in assoclist] + appenddict = {element[0]: element[1] for element in splitassoclist} takingOptions = False self.roleassocdict[message_id] = appenddict await ctx.send(str(self.roleassocdict)) @@ -77,15 +73,14 @@ async def updateRoles(self, payload, addRoleBool : bool): return if role is not None: member = guild.get_member(payload.user_id) - if member is not None: - if addRoleBool: - await member.add_roles(role) - print(f"{member.name}#{member.discriminator} was assigned the role {role.name}") - else: - await member.remove_roles(role) - print(f"{member.name}#{member.discriminator} was unassigned the role {role.name}") - else: + if member is None: print("Member not found") + elif addRoleBool: + await member.add_roles(role) + print(f"{member.name}#{member.discriminator} was assigned the role {role.name}") + else: + await member.remove_roles(role) + print(f"{member.name}#{member.discriminator} was unassigned the role {role.name}") else: print("Role not found") except KeyError: @@ -98,7 +93,7 @@ async def updateRoles(self, payload, addRoleBool : bool): async def clearroleassignments(self, ctx): """Delete current role assignment posts.""" self.roleassocdict = {} - await ctx.send(f"Role associations have been cleared. {str(self.roleassocdict)}") + await ctx.send(f"Role associations have been cleared. {self.roleassocdict}") @commands.command() async def showroleassignments(self, ctx):