forked from FiendsOfTheElements/FFR-Bot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
483 lines (391 loc) · 16.4 KB
/
main.py
File metadata and controls
483 lines (391 loc) · 16.4 KB
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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
import asyncio
import logging
import re
import time
from datetime import datetime, timedelta
import random
import urllib
import urllib.request
import json
from io import StringIO
from discord.ext import commands
from discord.utils import get
from races import Races
# format logging
logging.basicConfig(
format='%(asctime)s %(levelname)-8s %(message)s',
level=logging.INFO,
datefmt='%Y-%m-%d %H:%M:%S')
description = 'FFR discord bot'
bot = commands.Bot(command_prefix='?', description=description, case_insensitive=True)
# constants
ADMINS = ["Primordial Forces", "Dev Admin"]
Sleep_Time = 5000
challengeseedadmin = "challengeseedadmin"
asyncseedadmin = "asyncseedadmin"
adminroles = [challengeseedadmin, asyncseedadmin]
challengeseedrole = "challengeseed"
asyncseedrole = "asyncseed"
nonadminroles = [challengeseedrole, asyncseedrole]
challengeseedchannel = "challengeseed"
challengeseedleaderboard = "challengeseedleaderboard"
challengeseedspoiler = "challengeseedspoilerchat"
asyncchannel = "async-seed_flags"
asyncleaderboard = "async-leaderboard"
asyncspoiler = "async-spoilers"
bot.add_cog(Races(bot, ADMINS))
@bot.event
async def on_ready():
print(datetime.now().strftime('%Y-%m-%d %H:%M:%S'), ' Logged in as')
print(bot.user.name)
print(bot.user.id)
print('------')
def is_admin(ctx):
user = ctx.author
return (any(role.name in ADMINS for role in user.roles)) or (user.id == int(140605120579764226))
def allow_seed_rolling(ctx):
return (ctx.channel.name == "call_for_races") or (ctx.channel.category_id == get(ctx.guild.categories, name="races").id)
@bot.command()
async def purgemembers(ctx):
"""
Removes members from the role associated with the channel,
works for asyncseedrole and challengeseedrole
:param ctx: context of the command
:return: None
"""
user = ctx.message.author
role = await getrole(ctx)
if role in user.roles and role.name in adminroles:
if role.name == challengeseedadmin:
role = get(ctx.message.guild.roles, name=challengeseedrole)
else:
role = get(ctx.message.guild.roles, name=asyncseedrole)
members = ctx.message.guild.members
role_members = [x for x in members if role in x.roles]
for x in role_members:
await x.remove_roles(role)
else:
await user.send(("... Wait a second.. YOU AREN'T AN ADMIN! (note, you need the correct admin role"
" and need to use this in the spoilerchat for the role you want to purge members"
" from)"))
await ctx.message.delete()
@bot.command()
async def submit(ctx, runnertime: str = None):
"""
Submits a runners time to the leaderboard and gives the appropriate role
:param runnertime: time of the runner, in the format H:M:S, e.g. 2:32:12
:param ctx: context of the command
:return: None
"""
user = ctx.message.author
role = await getrole(ctx)
if runnertime is None:
await user.send("You must include a time when you submit a time.")
await ctx.message.delete()
return
if role is not None and role not in user.roles and role.name in nonadminroles:
try:
# convert to seconds using this method to make sure the time is readable and valid
# also allows for time input to be lazy, ie 1:2:3 == 01:02:03 yet still maintain a consistent
# style on the leaderboard
t = datetime.strptime(runnertime, "%H:%M:%S")
except ValueError:
await user.send("The time you provided '" + str(runnertime) +
"', this is not in the format HH:MM:SS (or you took a day or longer)")
await ctx.message.delete()
return
await user.add_roles(role)
delta = timedelta(hours=t.hour, minutes=t.minute, seconds=t.second)
username = re.sub('[()-]', '', user.display_name)
leaderboard = await getleaderboard(ctx)
leaderboard_list = leaderboard.content.split("\n")
# the title is at the start and the forfeit # is after the hyphen at the end of the last line
title = leaderboard_list[0]
forfeits = int(leaderboard_list[-1].split('-')[-1])
# trim the leaderboard to remove the title and forfeit message
leaderboard_list = leaderboard_list[2:len(leaderboard_list)-2]
for i in range(len(leaderboard_list)):
leaderboard_list[i] = re.split('[)-]', leaderboard_list[i])[1:]
# convert the time back to hours minutes and seconds for the leaderboard
totsec = delta.total_seconds()
h = totsec // 3600
m = (totsec % 3600) // 60
s = (totsec % 3600) % 60
leaderboard_list.append(
[" "+username+" ", " %d:%02d:%02d" % (h, m, s)])
# sort the times
leaderboard_list.sort(
key=lambda x: datetime.strptime(x[1].strip(), "%H:%M:%S"))
# build the string for the leaderboard
new_leaderboard = title+"\n\n"
for i in range(len(leaderboard_list)):
new_leaderboard += str(i+1) + ")" + \
leaderboard_list[i][0]+"-" + leaderboard_list[i][1] + "\n"
new_leaderboard += "\nForfeits - " + str(forfeits)
await leaderboard.edit(content=new_leaderboard)
await (await getspoilerchat(ctx)).send('GG %s' % user.mention)
await ctx.message.delete()
await changeparticipants(ctx)
else:
await user.send("You already have the relevent role.")
await ctx.message.delete()
@bot.command()
async def remove(ctx):
"""
Removes people from the leaderboard and allows them to reenter a time
This entire function is gross, it works but is messy
:param ctx: context of the command
:param players: @mentions of the players that will be removed from the leaderboard
:return: None
"""
user = ctx.message.author
if ctx.message.mentions is None:
await user.send("You did not mention a player.")
await ctx.message.delete()
return
channel = ctx.message.channel
roles = ctx.message.guild.roles
role = None
channels = ctx.message.guild.channels
challengeseed = get(channels, name=challengeseedleaderboard)
asyncseed = get(channels, name=asyncleaderboard)
if channel == challengeseed:
role = get(roles, name=challengeseedadmin)
remove_role = get(roles, name= challengeseedrole)
participantnumchannel = get(channels, name= challengeseedchannel)
if channel == asyncseed:
role = get(roles, name=asyncseedadmin)
remove_role = get(roles, name=asyncseedrole)
participantnumchannel = get(channels, name=asyncchannel)
if role in user.roles:
leaderboard = channel.history(oldest_first=True, limit=100)
async for x in leaderboard:
if bot.user == x.author:
leaderboard = x
leaderboard_list = leaderboard.content.split("\n")
# the title is at the start and the forfeit # is after the hyphen at the end of the last line
title = leaderboard_list[0]
forfeits = int(leaderboard_list[-1].split('-')[-1])
# trim the leaderboard to remove the title and forfeit message
leaderboard_list = leaderboard_list[2:len(leaderboard_list) - 2]
for i in range(len(leaderboard_list)):
leaderboard_list[i] = re.split('[)-]', leaderboard_list[i])[1:]
players = ctx.message.mentions
if not players:
await user.send("You did not mention a player.")
await ctx.message.delete()
return
for player in players:
i = 0
for i in range(len(leaderboard_list)):
if leaderboard_list[i][0][1:len(leaderboard_list[i][0])-1] == re.sub('[()-]', '', player.display_name):
del leaderboard_list[i]
await player.remove_roles(remove_role)
await changeparticipants(ctx, increment=False, channel=participantnumchannel)
break
# should already be sorted
#leaderboard_list.sort(
# key=lambda x: datetime.strptime(x[1].strip(), "%H:%M:%S"))
# build the string for the leaderboard
new_leaderboard = title + "\n\n"
for i in range(len(leaderboard_list)):
new_leaderboard += str(i + 1) + ")" + \
leaderboard_list[i][0] + "-" + leaderboard_list[i][1] + "\n"
new_leaderboard += "\nForfeits - " + str(forfeits)
await leaderboard.edit(content=new_leaderboard)
await ctx.message.delete()
@bot.command()
async def createleaderboard(ctx, name):
"""
Creates a leaderboard post with a title and the number of forfeits
:param ctx: context of the command
:param name: title of the leaderboard
:return: None
"""
user = ctx.message.author
if name is None:
await user.send("You did not submit a name.")
await ctx.message.delete()
return
role = await getrole(ctx)
# gross way of doing this, works for now
if role in user.roles and role.name == challengeseedadmin:
await get(ctx.message.guild.channels, name=challengeseedleaderboard).send(name+"\n\nForfeits - 0")
await get(ctx.message.guild.channels, name=challengeseedchannel).send("Number of participants: 0")
elif role in user.roles and role.name == asyncseedadmin:
await get(ctx.message.guild.channels, name=asyncleaderboard).send(name + "\n\nForfeits - 0")
await get(ctx.message.guild.channels, name=asyncchannel).send("Number of participants: 0")
else:
await user.send(("... Wait a second.. YOU AREN'T AN ADMIN! (note, you need the admin role"
"for this channel)"))
await ctx.message.delete()
@bot.command()
async def ff(ctx):
"""
Increments the number of forfeits and gives the appropriate role to the user
:param ctx: context of the command
:return: None
"""
user = ctx.message.author
role = await getrole(ctx)
if role is not None and role not in user.roles and role.name in nonadminroles:
await user.add_roles(role)
leaderboard = await getleaderboard(ctx)
new_leaderboard = leaderboard.content.split("\n")
forfeits = int(new_leaderboard[-1].split("-")[-1]) + 1
new_leaderboard[-1] = "Forfeits - " + str(forfeits)
seperator = "\n"
new_leaderboard = seperator.join(new_leaderboard)
await leaderboard.edit(content=new_leaderboard)
await ctx.message.delete()
await changeparticipants(ctx)
else:
await ctx.message.delete()
# @bot.command()
# async def testexit():
# await ctx.channel.send("exiting, should restart right away")
# SystemExit()
@bot.command()
async def spec(ctx):
"""
Gives the user the appropriate role
:param ctx: context of the command
:return: None
"""
user = ctx.message.author
role = await getrole(ctx)
if role is not None and role.name in nonadminroles:
await user.add_roles(role)
await ctx.message.delete()
async def getrole(ctx):
"""
Returns the Role object depending on the channel the command is used in
Acts as a check for making sure commands are executed in the correct spot as well
:param ctx: context of the command
:return: Role or None
"""
user = ctx.message.author
roles = ctx.message.guild.roles
channel = ctx.message.channel
channels = ctx.message.guild.channels
challengeseed = get(channels, name=challengeseedchannel)
asyncseed = get(channels, name=asyncchannel)
chalseedspoilerobj = get(channels, name=challengeseedspoiler)
asyseedspoilerobj = get(channels, name=asyncspoiler)
if channel == challengeseed:
role = get(roles, name=challengeseedrole)
elif channel == asyncseed:
role = get(roles, name=asyncseedrole)
elif channel == chalseedspoilerobj:
role = get(roles, name=challengeseedadmin)
elif channel == asyseedspoilerobj:
role = get(roles, name=asyncseedadmin)
else:
await user.send("That command isn't allowed here.")
return None
return role
async def getleaderboard(ctx):
"""
Returns the leaderboard Message object depending on the channel the command is used in
:param ctx: context of the command
:return: Message or None
"""
user = ctx.message.author
channel = ctx.message.channel
channels = ctx.message.guild.channels
challengeseed = get(channels, name=challengeseedchannel)
asyncseed = get(channels, name=asyncchannel)
if channel == challengeseed:
leaderboard = get(channels, name=challengeseedleaderboard).history(oldest_first=True, limit=100)
elif channel == asyncseed:
leaderboard = get(channels, name=asyncleaderboard).history(oldest_first=True, limit=100)
else:
await user.send("That command isn't allowed here.")
return None
async for x in leaderboard:
if bot.user == x.author:
leaderboard = x
return leaderboard
async def getspoilerchat(ctx):
"""
Returns the spoiler Channel object depending on the channel the command is used in
:param ctx: context of the command
:return: Channel or None
"""
user = ctx.message.author
channel = ctx.message.channel
channels = ctx.message.guild.channels
challengeseed = get(channels, name=challengeseedchannel)
asyncseed = get(channels, name=asyncchannel)
if channel == challengeseed:
spoilerchat = get(channels, name='challengeseedspoilerchat')
elif channel == asyncseed:
spoilerchat = get(channels, name='async-spoilers')
else:
await user.send("That command isn't allowed here.")
return None
return spoilerchat
async def changeparticipants(ctx,increment = True, channel = None):
"""
changes the participant number
:param ctx: context of the command
:param increment: sets if it is incremented or decremented
:return: None
"""
participants = (ctx.message.channel if channel is None else channel).history(oldest_first=True, limit=100)
async for x in participants:
if x.author == bot.user:
participants = x
num_partcipents = int(participants.content.split(":")[1])
if increment:
num_partcipents += 1
else:
num_partcipents -= 1
new_participants = "Number of participants: " + str(num_partcipents)
await participants.edit(content=new_participants)
# used to clear channels for testing purposes
# @bot.command(pass_context = True)
# async def purge(ctx):
# channel = ctx.message.channel
# await bot.purge_from(channel, limit=100000)
# @bot.command()
# async def whoami(ctx):
# await ctx.author.send(ctx.author.id)
# await ctx.message.delete()
def handle_exit(client,loop):
# taken from https://stackoverflow.com/a/50981577
loop.run_until_complete(client.logout())
for t in asyncio.Task.all_tasks(loop=loop):
if t.done():
t.exception()
continue
t.cancel()
try:
loop.run_until_complete(asyncio.wait_for(t, 5, loop=loop))
t.exception()
except asyncio.InvalidStateError:
pass
except asyncio.TimeoutError:
pass
except asyncio.CancelledError:
pass
def run_client(client, *args, **kwargs):
loop = asyncio.get_event_loop()
while True:
try:
print(datetime.now().strftime('%Y-%m-%d %H:%M:%S'), "Starting connection")
loop.run_until_complete(client.start(*args, **kwargs))
except KeyboardInterrupt:
handle_exit(client, loop)
client.loop.close()
print("Program ended")
break
except Exception as e:
print(datetime.now().strftime('%Y-%m-%d %H:%M:%S'), " Error", e)
handle_exit(client, loop)
print(datetime.now().strftime('%Y-%m-%d %H:%M:%S'), "Waiting until restart")
time.sleep(Sleep_Time)
with open('token.txt', 'r') as f:
token = f.read()
token = token.strip()
run_client(bot, token)