-
Notifications
You must be signed in to change notification settings - Fork 6
/
botutils.py
249 lines (217 loc) · 8.85 KB
/
botutils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
import discord
from pdf2image import convert_from_path
import os
import pickle
import random
async def deleteAllMessages(bot, guildId, whitelistChannels):
"""
@param bot the instance of the running bot in use by the calling function
@param guildId the Guild ID in use by the calling function
@param whitelistChannels the list of whitelisted channels from which messages
are not deleted
"""
guild = bot.get_guild(int(guildId))
for channel in guild.text_channels:
if channel.name not in whitelistChannels:
while(True):
deleted = await channel.purge(limit=1000)
if not len(deleted):
break
def getAuthorized(ctx, message_start, message_end, *authorizedRoles):
"""
@param ctx
"""
author = ctx.message.author
authorRoles = [str(role).lower() for role in author.roles[1:]]
for role in authorizedRoles:
if role in authorRoles:
return True, ''
response = message_start+', or '.join(authorizedRoles)+message_end
return False, response
def getAuthorizedUser(author, message_start, message_end, *authorizedRoles):
"""
@param ctx
"""
authorRoles = [str(role).lower() for role in author.roles[1:]]
for role in authorizedRoles:
if role in authorRoles:
return True, ''
response = message_start+', or '.join(authorizedRoles)+message_end
return False, response
def getAuthorizedServer(bot, guildId, ctx):
guild = bot.get_guild(int(guildId))
if ctx.message.guild != guild:
print("Ignoring message sent from other server")
return False
else:
return True
def getAuthorAndName(ctx):
"""
Takes the context variable from the calling function and returns the author
object and the author display name, formatted.
@param ctx the context passed to the calling function
@return author the author object
@return authorName the display name of the author
"""
author = ctx.message.author
authorName = str(author.display_name).split("#")[0]
return author, authorName
def getCommonChannels(bot, guildId, whitelistChannels):
"""
@param bot the instance of the running bot in use by the calling function
@param guildId the Guild ID in use by the calling function
@param whitelistChannels the channels that are not on the commonChannels or on
the teamChannels
@return commonChannels a dictionary mapping channel names to channel IDs
"""
guild = bot.get_guild(int(guildId))
commonChannels = {}
for channel in guild.text_channels:
cn = channel.name
if not (cn.startswith('team') and cn.endswith('-chat')):
if cn not in whitelistChannels:
commonChannels[cn] = bot.get_channel(channel.id)
return commonChannels
def getTeamChannels(bot, guildId, numberOfTeams):
"""
@param bot the instance of the running bot in use by the calling function
@param guildId the Guild ID in use by the calling function
@param numberOfTeams the limit on the number of teams for the quiz
@return teamChannels a dictionary mapping team names to channel IDs
"""
guild = bot.get_guild(int(guildId))
teamChannels = {}
for channel in guild.text_channels:
cn = channel.name
if cn.startswith('team') and cn.endswith('-chat'):
teamNo = int(cn.split('team')[1].split('-chat')[0])
if teamNo <= numberOfTeams:
teamChannels[cn.replace('-chat','')] = bot.get_channel(channel.id)
return teamChannels
def getTeamDistribution(bot, guildId, scores, names=False):
"""
@param bot the instance of the running bot in use by the calling function
@param guildId the Guild ID in use by the calling function
@param scores the scores dictionary that also tracks active teams
@return teamDistribution Dictionary of teams and their members
"""
guild = bot.get_guild(int(guildId))
teamDistribution = {}
for team in scores:
teamDistribution[team] = []
for member in guild.members:
for role in member.roles:
if role.name.startswith("team"):
try:
assert role.name in teamDistribution
if names:
teamDistribution[role.name].append(member.display_name)
else:
teamDistribution[role.name].append(member)
except:
print("Please check that teamnames match roles (no \
spaces). Someone might have a role of a team \
that isn't in this quiz.")
return teamDistribution
def getTeamMembers(teamDistribution, team):
"""
@param teamDistribution team distribution generated by getTeamDistribution
@param team the team we are trying to get members of
@return list of string display names of team members
"""
memberList = []
for member in teamDistribution[team]:
memberList.append(member.display_name.split("#")[0])
return memberList
def getTeam(author):
"""
Takes the author object and returns the team the author is a member of
@param author the author object
"""
tmp = []
for role in author.roles[1:]:
if role.name.startswith('team'):
tmp.append(str(role.name.lower()))
team = ', '.join(tmp)
return team
async def unassignTeams(bot, guildId, ctx):
"""
@param bot the instance of the running bot in use by the calling function
@param guildId the Guild ID in use by the calling function
"""
guild = bot.get_guild(int(guildId))
for member in guild.members:
for role in member.roles:
if role.name.startswith("team"):
try:
await member.remove_roles(role)
response = 'Removing {} from {}.\
'.format(str(member.display_name),str(role.name))
await ctx.send(str(response))
except:
print("Did not remove",member,"from",role,"because of \
permissions. Make the bot an admin and run this again.")
def deleteFiles(directoryPath, *extensions):
for extension in extensions:
filelist = [f for f in os.listdir(directoryPath) if f.endswith(extension)]
print("deleting",extension, filelist)
for f in filelist:
os.remove(os.path.join(directoryPath, f))
def convertToImages(presentationDirPath, presentationFileName):
deleteFiles(presentationDirPath, '.jpg')
presentationFilePath = os.path.join(presentationDirPath, presentationFileName)
imagelist = []
print("Converting PDF to images (might take couple of minutes while no message is displayed; do not panic)")
pages = convert_from_path(presentationFilePath, 100)
print("Now saving images")
for index, page in enumerate(pages):
filename = str(index)+'.jpg'
page.save(os.path.join(presentationDirPath, filename), 'JPEG')
imagelist.append(filename)
print("generating page, ", filename)
return imagelist
def getMostFrequentSlide(presentationDirPath):
filelist = [(f,os.stat(os.path.join(presentationDirPath,f)).st_size) for f in os.listdir(presentationDirPath) if f.endswith('jpg')]
file_sizes = {}
for f in filelist:
rounded_size = (f[1] // 60) * 60
if rounded_size in file_sizes:
file_sizes[rounded_size].append(f[0])
else:
file_sizes[rounded_size] = [f[0]]
most_common_slides = file_sizes[(max(file_sizes, key= lambda x: len(file_sizes[x])))]
return most_common_slides
async def previewSlide(ctx, filename):
with open(filename, 'rb') as f:
picture = discord.File(f)
channel = ctx.message.channel
await channel.send("Is this the safety slide?",file=picture)
async def updateSlides(ctx, filename, commonChannels, teamChannels, questionChannel, qmChannel, scoreChannel):
url = ""
with open(filename, 'rb') as f:
picture = discord.File(f)
channel = commonChannels[questionChannel]
await channel.send(file=picture)
message = await commonChannels[questionChannel].history(limit=1).flatten()
if len(message) > 0:
message = message[0]
if len(message.attachments) > 0:
print(message.attachments[0].url)
url = message.attachments[0].url
channel = commonChannels[qmChannel]
await channel.send(url)
channel = commonChannels[scoreChannel]
await channel.send(url)
shuffledTeams = list(teamChannels.keys())
random.shuffle(shuffledTeams)
for team in shuffledTeams:
await teamChannels[team].send(url)
response = "All teams have received the slide"
await ctx.message.channel.send(response)
def saveSlideState(saveTo, state):
with open(saveTo, 'wb') as f:
pickle.dump(state, f)
def recoverSlideState(savePath):
with open(savePath, 'rb') as f:
state = pickle.load(f)
return state