Skip to content
This repository was archived by the owner on Jun 13, 2022. It is now read-only.

Sourcery refactored main branch #4

Open
wants to merge 1 commit 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
13 changes: 11 additions & 2 deletions cogs/announcements.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
)

Comment on lines -155 to +165
Copy link
Author

Choose a reason for hiding this comment

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

Function Announcements.sh_announcement refactored with the following changes:

await ctx.send(embed=embed_list)

@commands.command()
Expand Down
5 changes: 1 addition & 4 deletions cogs/moderation.py
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Copy link
Author

Choose a reason for hiding this comment

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

Function Moderation.purge refactored with the following changes:

await ctx.send(f'{amount} {pluralstring} purged.')

@commands.command()
Expand Down
12 changes: 5 additions & 7 deletions cogs/neil.py
Original file line number Diff line number Diff line change
Expand Up @@ -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] != '':
Copy link
Author

Choose a reason for hiding this comment

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

Function makestring refactored with the following changes:

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:
Expand All @@ -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
Expand All @@ -70,15 +68,15 @@ 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

if capitalise:
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

Expand Down
95 changes: 46 additions & 49 deletions cogs/polling.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Comment on lines -48 to +53
Copy link
Author

Choose a reason for hiding this comment

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

Function Polling.createpoll refactored with the following changes:

This removes the following comments ( why? ):

#timeout

takingOptions = False
else:
await ctx.send("At least one option must be provided!")
Expand Down Expand Up @@ -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
Expand All @@ -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)
Expand All @@ -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
Expand All @@ -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)
Comment on lines -154 to +185
Copy link
Author

Choose a reason for hiding this comment

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

Function Polling.updatePollResults refactored with the following changes:


@commands.Cog.listener()
async def on_message_delete(self,message):
Expand All @@ -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)
Comment on lines -208 to +205
Copy link
Author

Choose a reason for hiding this comment

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

Function Polling.checkactivepolls refactored with the following changes:


def setup(client):
client.add_cog(Polling(client))
25 changes: 10 additions & 15 deletions cogs/roleassignment.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}
Comment on lines -37 to +38
Copy link
Author

Choose a reason for hiding this comment

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

Function RoleAssignment.createroleassignment refactored with the following changes:

takingOptions = False
self.roleassocdict[message_id] = appenddict
await ctx.send(str(self.roleassocdict))
Expand Down Expand Up @@ -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}")
Comment on lines -80 to +83
Copy link
Author

Choose a reason for hiding this comment

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

Function RoleAssignment.updateRoles refactored with the following changes:

else:
print("Role not found")
except KeyError:
Expand All @@ -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}")
Comment on lines -101 to +96
Copy link
Author

Choose a reason for hiding this comment

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

Function RoleAssignment.clearroleassignments refactored with the following changes:


@commands.command()
async def showroleassignments(self, ctx):
Expand Down