forked from techlover1/PugBot-for-Discord
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathpugbot.py
4075 lines (3817 loc) · 152 KB
/
pugbot.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
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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Pickup Game Bot for use with discord
# Modified by: Alex Laswell for use with Fortress Forever
# Based on:
# PugBot-for-Discord by techlover1 https://github.com/techlover1/PugBot-for-Discord
import asyncio
import config
from collections import OrderedDict
import datetime
from datetime import timedelta
import discord
from discord import Game
from discord.ext.commands import Bot
from os import system
import pymongo
from pymongo.collection import ReturnDocument
import random
from random import choice, shuffle
import re
import requests
import subprocess
import time
import valve.rcon
# Configurable constants
adminChannelID = config.adminChannelID
adminRoleID = config.adminRoleID
adminRoleMention = config.adminRoleMention
bannedChannelID = config.bannedChannelID
blueteamChannelID = config.blueteamChannelID
cmdprefix = config.cmdprefix
dbtoken = config.dbtoken
discordServerID = config.discordServerID
durationOfCheckin = config.durationOfCheckin
durationOfMapVote = config.durationOfMapVote
durationOfReadyUp = config.durationOfReadyUp
durationOfVeto = config.durationOfVeto
flaskServerURL = config.flaskServerURL
newPlayerRoleID = config.newPlayerRoleID
newPlayerRoleStr = config.newPlayerRoleStr
numRestarts = 0
playerRoleID = config.playerRoleID
poolRoleID = config.poolRoleID
probationRoleID = config.probationRoleID
quotes = config.quotes
readyupChannelID = config.readyupChannelID
redteamChannelID = config.redteamChannelID
requestChannelID = config.requestChannelID
rconPW = config.rconPW
server_address = config.server_address
serverID = config.serverID
serverIDRegEx = config.serverIDRegEx
serverPattern = config.serverPattern
serverPW = config.serverPW
singleChannelID = config.singleChannelID
sizeOfGame = config.sizeOfGame
sizeOfTeams = config.sizeOfTeams
sizeOfMapPool = config.sizeOfMapPool
sizeOfRecentMap = config.sizeOfRecentMap
timeoutRoleID = config.timeoutRoleID
token = config.token
vipPlayerID = config.vipPlayerID
websiteKey = config.websiteKey
websiteURL = config.websiteURL
# Globals
BLUE_TEAM = []
CHOSEN_MAP = []
LAST_BLUE_TEAM = []
LAST_MAP = []
LAST_RED_TEAM = []
LAST_TIME = time.time()
MAP_PICKS = {}
PLAYERS = []
RED_TEAM = []
START_TIME = time.time()
STARTER = []
PICKUP_RUNNING = False
RANDOM_TEAMS = False
VOTE_FOR_MAPS = True
# the bot, client, and server objects
Bot = Bot(command_prefix=cmdprefix)
client = discord.Client()
server = None
adminRole = None
accessRole = None
newPlayerRole = None
poolRole = None
probationRole = None
timeoutRole = None
# create the MongoDB client and connect to the database
dbclient = pymongo.MongoClient(dbtoken)
database = dbclient.FortressForever
# a valve RCON (Remote CONnection)
rcon = valve.rcon.RCON(server_address, rconPW)
rcon.connect()
rcon.authenticate()
#
# Functions A-Z
#
# do not allow commands if the author is in a timeout
async def author_is_in_timeout(message):
global server
member = server.get_member(message.author.id)
if timeoutRoleID in [r.id for r in member.roles]:
if message.content.startswith(cmdprefix):
emb = discord.Embed(
description="I'm sorry, you cannot use any of these commands while you are in timeout. You will need to speak with a "
+ adminRoleMention
+ " for further details.",
colour=0xFF0000,
)
emb.set_author(name=Bot.user.name, icon_url=Bot.user.avatar_url)
await message.author.send(embed=emb)
return True
return False
# Select the BLUE_TEAM
async def blue_team_picks(caps, context, playerPool):
global BLUE_TEAM, RED_TEAM, PLAYERS, server
playerPicked = False
await send_emb_message_to_channel(
0x00FF00,
caps[0].mention
+ " type @player to pick. Available players are:\n\n"
+ "\n".join([p.mention for p in playerPool]),
context,
)
while not playerPicked:
# check for a pick and catch it if they don't mention an available player
try:
def check(msg):
return msg.author == server.get_member(caps[0].id)
inputobj = await Bot.wait_for("message", check=check)
picked = inputobj.mentions[0]
# If the player is in players and they are not already picked, add to the team
if picked in PLAYERS:
if picked not in RED_TEAM and picked not in BLUE_TEAM:
BLUE_TEAM.append(picked)
try:
playerPool.remove(picked)
except ValueError:
pass # 'picked' is not in playerPool, so just move on
playerPicked = True
await send_emb_message_to_channel_blue(
picked.mention + " has been added to the team", context
)
else:
await send_emb_message_to_channel(
0xFF0000, picked.mention + " is already on a team", context
)
else:
await send_emb_message_to_channel(
0xFF0000, picked.mention + " is not in this pickup", context
)
except (IndexError):
pass
# check that the admin who started the game is still here
async def check_for_afk_admin():
global adminRoleID, cmdprefix, STARTER
# check for advanced filtering
def check(msg):
if adminRoleID in [r.id for r in msg.author.roles]:
return msg.content.startswith(cmdprefix + "here")
inputobj = None
try:
inputobj = await Bot.wait_for("message", timeout=durationOfCheckin, check=check)
except Exception:
pass
# returns 'None' if asyncio.TimeoutError thrown
if inputobj != None: # game_starter did !checkin
if inputobj.author != STARTER[0]:
# another admin has stepped in
STARTER = []
STARTER.append(inputobj.author)
return True
else: # game_starter did not !checkin
return False
# cycle through the all the players in the pool and verify they are ready
async def check_for_afk_players():
global PLAYERS, readyupChannelID, server
ready_channel = discord.utils.get(server.channels, id=readyupChannelID)
ready_users = ready_channel.members
afk_players = []
# only preform this check if the readyupChannelID is a valid voice channel
if ready_channel is not None:
# check to verify if each player is in the ready-up channel
for p in PLAYERS:
if p not in ready_users:
afk_players.append(p) # add to missing players list
return afk_players
async def check_for_map_nominations(context):
global cmdprefix, MAP_PICKS, sizeOfGame, sizeOfMapPool, PICKUP_RUNNING, PLAYERS
while (
len(MAP_PICKS) < sizeOfMapPool and PICKUP_RUNNING and len(PLAYERS) == sizeOfGame
):
# need to build the list of maps
mapStr = ""
for k in MAP_PICKS:
mapStr = mapStr + str(MAP_PICKS[k]) + " (" + k.mention + ")\n"
await send_emb_message_to_channel(
0xFF0000,
"Players must nominate more maps before we can proceed\nCurrently Nominated Maps ("
+ str(len(MAP_PICKS))
+ "/"
+ str(sizeOfMapPool)
+ ")\n"
+ mapStr,
context,
)
async def needMapPicks(msg):
# check function for advanced filtering
def check(msg):
return msg.content.startswith(cmdprefix + "nominate")
# wait until someone nominates another map
try:
await Bot.wait_for("message", timeout=30, check=check)
except Exception:
pass
await needMapPicks(context.message)
# allows the game_starter to veto admin commands
async def check_for_veto(command, context):
global cmdprefix, STARTER
# generic check to allow game_starter to !veto another admin's command
await send_emb_message_to_channel(
0xFF0000,
STARTER[0].mention
+ "\n\n"
+ context.author.mention
+ " is trying to "
+ command
+ " your pickup. You have "
+ str(durationOfVeto)
+ " seconds to "
+ cmdprefix
+ "veto them, or the command will happen",
context,
)
# check for advanced filtering
def check(msg):
return msg.author == STARTER[0] and msg.content.lower().startswith(
cmdprefix + "veto"
)
inputobj = None
try:
inputobj = await Bot.wait_for("message", timeout=durationOfVeto, check=check)
except Exception:
pass
if inputobj != None: # game_starter did !veto the command
return True
else: # game_starter did not !veto
return False
# Check to see if the message has been sent via a Direct Message to the bot
async def command_is_in_wrong_channel(context):
global requestChannelID, singleChannelID
if context.command.name == "pug":
if context.channel.id != requestChannelID:
# Bot only listens to the request channel when granting access
await send_emb_message_to_channel(
0xFF0000,
context.author.mention
+ " you cannot use this command in this channel. Retry inside the "
+ server.get_channel(requestChannelID).name
+ " channel",
context,
)
return True
else:
return False
elif context.command.name == "addserver" or context.command.name == "delserver":
# Bot only listens to these commands via direct message
if context.message.guild is not None:
await send_emb_message_to_channel(
0xFF0000,
context.author.mention
+ " this command will only work as a direct message to the bot",
context,
)
return True
else:
return False
elif (
context.command.name == "ban"
or context.command.name == "permaban"
or context.command.name == "unban"
):
# Admin channel commands
if (
context.channel.id != adminChannelID
and context.channel.id != bannedChannelID
and context.channel.id != singleChannelID
):
# Bot will only listen to the above channels when banning or unbanning players
await send_emb_message_to_user(
0xFF0000,
"I'm sorry, you cannot use that command in the "
+ context.channel.name
+ " channel. Retry inside the "
+ server.get_channel(adminChannelID).name
+ ", "
+ server.get_channel(bannedChannelID).name
+ ", or the "
+ server.get_channel(singleChannelID).name
+ " channel",
context,
)
return True
else:
return False
elif context.channel.id != singleChannelID:
# Bot only listens to one channel for all other commands
await send_emb_message_to_channel(
0xFF0000,
context.author.mention
+ " you cannot use this command in this channel. Retry inside the "
+ server.get_channel(singleChannelID).name
+ " channel",
context,
)
return True
return False
async def command_will_fubar_server(command):
if command == "exit":
return True
elif command == "quit":
return True
elif command == "test":
return True
else:
return False
async def count_votes_message_channel(tdelta, keys, context, votelist, votetotals):
global sizeOfMapPool
tmpstr = ""
# reset totals
votetotals = []
[votetotals.append(0) for x in range(sizeOfMapPool)]
# tally the buckets
for k, v in votelist.items():
votetotals[v - 1] += 1
# zip with keys to make a nice dict
totals = OrderedDict(zip(keys, votetotals))
for x, y in totals.items():
tmpstr = tmpstr + str(x) + " : " + str(y) + "\n"
# set up the remaining time to vote timedelta
tdelta0 = tdelta - timedelta(microseconds=tdelta.microseconds)
await send_emb_message_to_channel(
0x00FF00,
tmpstr
+ "\n"
+ str(durationOfMapVote - tdelta0.total_seconds())
+ " seconds remaining",
context,
)
async def go_go_gadget_pickup(context):
global adminRole, BLUE_TEAM, CHOSEN_MAP, cmdprefix, durationOfReadyUp, MAP_PICKS, server, sizeOfGame, STARTER, PICKUP_RUNNING, PLAYERS, poolRole, poolRoleID, RANDOM_TEAMS, RED_TEAM, rcon, readyupChannelID, server_address, rconPW, VOTE_FOR_MAPS
afk_players = []
BLUE_TEAM = []
caps = []
RED_TEAM = []
playerPool = []
playerPoolStr = ""
counter = 0
countdown = time.time()
elapsedtime = time.time() - countdown
inputobj = 0 # used to manipulate the objects from messages
pick_captains_counter = 0
ready_channel = discord.utils.get(context.guild.channels, id=readyupChannelID)
RANDOM_TEAMS = (
True
) # if game starter does not change, will pick teams randomly from players list
td = timedelta(seconds=elapsedtime)
await send_emb_message_to_channel(
0x00FF00,
"The pickup is starting!!\n\n"
+ poolRole.mention
+ " join the "
+ ready_channel.name
+ " channel to signify you are present and ready",
context,
)
# set up the embedded message in-case we need to message players
emb = discord.Embed(
title="The pickup is starting!!\n\nJoin the "
+ ready_channel.name
+ " channel to signify you are present and ready",
colour=0xFF0000,
)
emb.set_author(name=Bot.user.name, icon_url=Bot.user.avatar_url)
# give the players time to ready-up
while td.total_seconds() < durationOfReadyUp:
# only check every 5 seconds
await asyncio.sleep(5)
# loop through the channel and check to see if everyone has joined it or not
afk_players = await check_for_afk_players()
if len(afk_players) > 0:
afkstr = "\n".join([p.mention for p in afk_players])
elapsedtime = time.time() - countdown
td = timedelta(seconds=elapsedtime)
# only message everyone on every third iteration
if (counter % 3) == 0:
await send_emb_message_to_channel(
0xFF0000, "Missing players:\n\n" + afkstr + "\nPlease join the " + ready_channel.name, context
)
for p in afk_players:
try:
await p.send(embed=emb)
except Exception:
pass
counter += 1
else:
# all players in list are idle in channel and ready
break
# if afk_players has people in it, then those player(s) timed out
if len(afk_players) > 0:
for idleUser in afk_players:
PLAYERS.remove(idleUser) # remove from players list
MAP_PICKS.pop(
idleUser, None
) # remove this players nomination if they had one
try:
await idleUser.remove_roles(poolRole)
except Exception:
pass
await send_emb_message_to_channel(
0xFF0000,
idleUser.mention
+ " has been removed from the pickup due to inactivity",
context,
)
await Bot.change_presence(
activity=discord.Game(
name="Pickup ("
+ str(len(PLAYERS))
+ "/"
+ str(sizeOfGame)
+ ") "
+ cmdprefix
+ "add"
)
)
return False # break out if we remove a player
await send_emb_message_to_channel(
0x00FF00, "All players are confirmed ready!", context
)
# Verifying admin status if they have not already confirmed ready
if STARTER[0] not in PLAYERS:
await send_emb_message_to_channel(
0xFFA500,
"Verifying that we have an admin\n\n"
+ STARTER[0].mention
+ " please reply with "
+ cmdprefix
+ "here so we can proceed",
context,
)
adminPresent = False
while not adminPresent:
adminPresent = await check_for_afk_admin()
if not adminPresent:
# do we have an admin in the pool we can give the pickup to
for p in PLAYERS:
if await user_has_access(p):
# admin found : transferring pickup
await send_emb_message_to_channel(
0xFF0000,
STARTER[0].mention
+ " seems to be missing\n\nTransferring the game to "
+ p.mention,
context,
)
STARTER = []
STARTER.append(p)
adminPresent = True
break # no need to find another admin
if not adminPresent:
# try to private message the game_starter
emb = discord.Embed(
description="You did not reply with "
+ cmdprefix
+ "here and your pickup has been put on hold",
colour=0xFF0000,
)
emb.set_author(name=Bot.user.name, icon_url=Bot.user.avatar_url)
await STARTER[0].send(embed=emb)
# ping all admins to see if someone can take over
await send_emb_message_to_channel(
0xFF0000,
adminRole.mention
+ " the admin who started this pickup seems to be missing. "
+ cmdprefix
+ "here and save the pickup",
context,
)
# adminPresent == True
#
# Begin the pickup
#
# Map Selection
await Bot.change_presence(activity=discord.Game(name="Map Selection"))
if len(CHOSEN_MAP) > 0:
await verify_chosen_map_is_good(context)
# do we have the right amount of map nominations
if len(CHOSEN_MAP) == 0:
await check_for_map_nominations(context)
if not await pickup_is_full(context):
return False # exit go_go if someone has removed
if len(CHOSEN_MAP) == 0:
await pick_map(context)
if not await pickup_is_full(context):
return False # exit go_go if someone has removed
# by having the game admin approve
# we can make sure teams end up fair more often
adminApproves = False
while not adminApproves:
# loop until the game starter makes a decision
pick_captains_counter = (
1
) # tracks how many times the game_starter has been asked
shuffle(PLAYERS) # shuffle the player pool
RANDOM_TEAMS = await pick_captains(caps, context)
while len(caps) < 2:
if len(PLAYERS) < sizeOfGame:
if len(PLAYERS) > 0:
# game is no longer full
await send_emb_message_to_channel(
0xFF0000, "ABORTING: The pickup is no longer full", context
)
await Bot.change_presence(
activity=discord.Game(
name="Pickup ("
+ str(len(PLAYERS))
+ "/"
+ str(sizeOfGame)
+ ") "
+ cmdprefix
+ "add"
)
)
return False
else:
# game has been !ended
await Bot.change_presence(activity=discord.Game(name=" "))
return True
elif pick_captains_counter > 2:
# game_starter is afk ... pug will be ended
await send_emb_message_to_channel(
0xFF0000,
"This pickup has been abandoned by the admin and will now be ended\n\n"
+ adminRole.mention
+ " someone who is here, will need to start a new one",
context,
)
await Bot.change_presence(activity=discord.Game(name=" "))
return True
else:
RANDOM_TEAMS = await pick_captains(caps, context)
pick_captains_counter += 1
if not await pickup_is_full(context):
return False # exit go_go if someone has removed
# set up the initial teams
if RANDOM_TEAMS:
for i in range(0, sizeOfTeams):
RED_TEAM.append(PLAYERS[i])
BLUE_TEAM.append(PLAYERS[i + sizeOfTeams])
else:
# only add the captains if not already added
# cmdprefix + manual already adds 'captains' to teams
in_team = False
for p in BLUE_TEAM:
if p in caps:
in_team = True
if not in_team:
BLUE_TEAM.append(caps[0])
in_team = False
for p in RED_TEAM:
if p in caps:
in_team = True
if not in_team:
RED_TEAM.append(caps[1])
# copy the player pool over
for p in PLAYERS:
if p not in caps:
playerPool.append(p)
# Switch off picking until the teams are all full
await Bot.change_presence(activity=discord.Game(name="Team Selection"))
# if teams are not already full:
if len(RED_TEAM) < sizeOfTeams and len(BLUE_TEAM) < sizeOfTeams:
if not await pickup_is_full(context):
return False # exit go_go if someone has removed
await send_emb_message_to_channel(
0x00FF00, caps[0].mention + " vs " + caps[1].mention, context
)
# Blue captain picks first
await blue_team_picks(caps, context, playerPool)
if len(playerPool) > 1:
# only make the captain pick if they have a choice
await red_team_picks(caps, context, playerPool)
else:
RED_TEAM.append(playerPool[0])
await send_emb_message_to_channel_red(
playerPool[0].mention + " has been added to the team", context
)
while len(RED_TEAM) < sizeOfTeams and len(BLUE_TEAM) < sizeOfTeams:
if not await pickup_is_full(context):
return False # exit go_go if someone has removed
# Red captain gets two picks first round so start with red
await red_team_picks(caps, context, playerPool)
if not await pickup_is_full(context):
return False # exit go_go if someone has removed
if len(playerPool) > 1:
# only make the captain pick if they have a choice
await blue_team_picks(caps, context, playerPool)
else:
BLUE_TEAM.append(playerPool[0])
await send_emb_message_to_channel_blue(
playerPool[0].mention + " has been added to the team", context
)
# both teams are full
# verify everything looks good
await send_emb_message_to_channel_blue(
"\n".join([p.mention for p in BLUE_TEAM]), context
) # Blue Team information
await send_emb_message_to_channel_red(
"\n".join([p.mention for p in RED_TEAM]), context
) # Red Team information
await send_emb_message_to_channel(
0xFFA500,
STARTER[0].mention
+ " these are the teams\n\nMap selection: "
+ CHOSEN_MAP
+ "\n\nReply with "
+ cmdprefix
+ "accept to accept them or with "
+ cmdprefix
+ "repick and we can choose again",
context,
)
didChoose = False
while not didChoose:
# check for advanced filtering
def check(msg):
if msg.author == STARTER[0]:
if msg.content.startswith(
cmdprefix + "accept"
) or msg.content.startswith(cmdprefix + "repick"):
return True
return False
inputobj = None
try:
inputobj = await Bot.wait_for(
"message", timeout=durationOfCheckin, check=check
)
except Exception:
pass
# returns 'None' if asyncio.TimeoutError thrown
if inputobj != None:
didChoose = True
# switch on choice
if inputobj.content.startswith(cmdprefix + "accept"):
adminApproves = True
elif inputobj.content.startswith(cmdprefix + "repick"):
# reset so we can pick new teams
caps = []
BLUE_TEAM = []
playerPool = []
RED_TEAM = []
adminApproves = False
else:
didChoose = False
await send_emb_message_to_channel(
0xFF0000,
STARTER[0].mention
+ " please make a selection:\n\n"
+ cmdprefix
+ "accept to **accept** the teams\n\n"
+ cmdprefix
+ "repick to discard these teams and **repick** new ones",
context,
)
# adminApproves and everything is set
# pm users and message server with game information
await send_information(context)
# change the map in the server to the chosen map
try:
rcon = valve.rcon.RCON(server_address, rconPW)
rcon.connect()
rcon.authenticate()
resp = rcon.execute("changelevel " + CHOSEN_MAP)
print(
"LOG MESSAGE: RCON command <changelevel "
+ CHOSEN_MAP
+ "> response received\n\t"
+ str(resp)
+ "\nAt time "
+ time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
)
except Exception as inst:
print(inst)
pass
# move the players to their respective voice channels
for p in RED_TEAM:
try:
await p.edit(voice_channel=Bot.get_channel(redteamChannelID))
except (ValueError, HTTPException, Forbidden):
continue
for p in BLUE_TEAM:
try:
await p.edit(voice_channel=Bot.get_channel(blueteamChannelID))
except (ValueError, HTTPException, Forbidden):
continue
# Save all the information for !last
await save_last_game_info()
# Build the list of players for the website
for i in range(sizeOfTeams):
playerPoolStr += BLUE_TEAM[i].name + ","
playerPoolStr += RED_TEAM[i].name + ","
playerPoolStr = playerPoolStr[:-1] # delete the last comma
# POST to the information to the website
await post_to_website(playerPoolStr)
# remove the players from the pool
await remove_everyone_from_pool_role(context)
return True
# Lists all of the maps in the MongoDB table : maps
async def list_all_the_maps(msg):
global database
# find will return all documents in the maps collection
foundmaps = database.maps.find({})
# convert to a list so we can index into it
maps = list(foundmaps)
# with the aliases, this message gets big quickly so we
# need to chunk up the maplist into sections to accommodate
emb = discord.Embed(
description="Currently, you may nominate any of the following maps:",
colour=0xFFA500,
)
emb.set_author(name=Bot.user.name, icon_url=Bot.user.avatar_url)
# print the maps in groups of 20
iCount = 0
for map in maps:
if iCount % 20 == 0:
await msg.author.send(embed=emb)
emb = discord.Embed(description="", colour=0xFFA500)
emb.set_author(name=Bot.user.name, icon_url=Bot.user.avatar_url)
emb.add_field(name=str(map["name"]), value=str(map["aliases"]), inline=False)
iCount += 1
await msg.author.send(embed=emb)
# Check if the map was played in the last few pickups
async def map_was_recently_played(mapname):
global database, sizeOfRecentMap
iCount = 0
pugs = database.pickups.find({})
pugs.sort( "_id", pymongo.DESCENDING )
for pug in pugs:
if iCount >= sizeOfRecentMap:
return False
if pug["map"] == mapname:
return True
iCount += 1
# Check to see if the map nominated is an alias
async def mapname_is_valid(mpname):
# access the global vars
global database
# check in name
cursor = database.maps.find(
{"$or": [{"name": mpname}, {"name": "ff_" + mpname}, {"aliases": mpname}]}
)
for map in cursor:
return map["name"]
# did not find mapname
return "INVALID"
# wait until the game starter makes a decision
async def pick_captains(caps, context):
global BLUE_TEAM, cmdprefix, PLAYERS, RED_TEAM, sizeOfTeams, STARTER
bcap = Bot.user.name
rcap = Bot.user.name
# set presence
await Bot.change_presence(activity=discord.Game(name="Selecting Captains"))
# human readable Usage message to channel
emb = discord.Embed(
description=STARTER[0].mention + " please select one of the options below",
colour=0xFFA500,
)
emb.set_author(name=Bot.user.name, icon_url=Bot.user.avatar_url)
emb.add_field(
name=cmdprefix + "captains",
value="to manually select the captains",
inline=False,
)
emb.add_field(
name=cmdprefix + "manual", value="to manually select both teams", inline=False
)
emb.add_field(
name=cmdprefix + "randcapts", value="to randomize the captains. Provide a list of two or more users to narrow the pool of choices. e.g. @p1 @p2 @p3\nIf no players are provided, captains are picked from the entire pool.", inline=False
)
emb.add_field(
name=cmdprefix + "shuffle", value="to randomize the teams", inline=False
)
await context.channel.send(embed=emb)
# check function for advance filtering
def check(msg):
if msg.author == STARTER[0]:
if msg.content.startswith(cmdprefix + "captains"):
return True
elif msg.content.startswith(cmdprefix + "manual"):
return True
elif msg.content.startswith(cmdprefix + "randcapts"):
return True
elif msg.content.startswith(cmdprefix + "shuffle"):
return True
return False
# wait up to two (2) minutes for the game starter to make a decision
inputobj = None
try:
inputobj = await Bot.wait_for("message", timeout=120, check=check)
except Exception:
pass
# returns 'None' if asyncio.TimeoutError thrown
if inputobj != None:
# switch on choice
if inputobj.content.startswith(cmdprefix + "captains"):
# msg.mentions returns an unordered list
# therefore we have to get each name individually
# this way the admin has control over who is blue and red
plyrStr = "\n".join([p.mention for p in PLAYERS])
await send_emb_message_to_channel_blue(
STARTER[0].mention
+ " pick the blue team captain using @playername in your reply. Available players are:\n\n"
+ plyrStr,
context,
)
while bcap == Bot.user.name:
try:
# try to get the user the admin has specified
def check(msg):
return msg.author == STARTER[0]
inputobj = None
try:
inputobj = await Bot.wait_for(
"message", timeout=60, check=check
)
except Exception:
pass
if inputobj != None:
bcap = inputobj.mentions[0]
if bcap not in PLAYERS:
await send_emb_message_to_channel(
0xFF0000,
STARTER[0].mention
+ " player must be added to the pickup. Available players are:\n\n"
+ plyrStr,
context,
)
bcap = Bot.user.name
else: # timeout
await send_emb_message_to_channel_blue(
STARTER[0].mention
+ " pick the blue team captain using @playername in your reply. Available players are:\n\n"
+ plyrStr,
context,
)
except (IndexError):
# keep trying if they did not mention someone
await send_emb_message_to_channel_blue(
STARTER[0].mention
+ " pick the blue team captain using @playername in your reply. Available players are:\n\n"
+ plyrStr,
context,
)
# do the same for red team
temp = [] # list for players
for p in PLAYERS:
if p != bcap:
temp.append(p)
plyrStr = "\n".join([p.mention for p in temp])
await send_emb_message_to_channel_red(
STARTER[0].mention
+ " pick the red team captain using @playername in your reply. Available players are:\n\n"
+ plyrStr,
context,
)
while rcap == Bot.user.name:
try:
# try to get the user the admin has specified
def check(msg):
return msg.author == STARTER[0]
inputobj = None
try:
inputobj = await Bot.wait_for(
"message", timeout=60, check=check
)
except Exception:
pass
if inputobj != None:
rcap = inputobj.mentions[0]
if rcap not in PLAYERS:
await send_emb_message_to_channel(
0xFF0000,
STARTER[0].mention
+ " player must be added to the pickup. Available players are:\n\n"
+ plyrStr,
context,
)
rcap = Bot.user.name
else: # timeout
await send_emb_message_to_channel_red(
STARTER[0].mention
+ " pick the red team captain using @playername in your reply. Available players are:\n\n"
+ plyrStr,
context,
)
except (IndexError):
# keep trying if they did not mention someone
await send_emb_message_to_channel_red(
STARTER[0].mention
+ " pick the red team captain using @playername in your reply. Available players are:\n\n"
+ plyrStr,
context,
)
if bcap == rcap:
await send_emb_message_to_channel(
0xFF0000,
STARTER[0].mention