-
Notifications
You must be signed in to change notification settings - Fork 3
/
pug.py
executable file
·1566 lines (1434 loc) · 62 KB
/
pug.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
#!/usr/bin/python
import config
import irclib
import math
import psycopg2
import random
import re
import string
import SRCDS
import thread
import threading
import time
#irclib.DEBUG = 1
def add(userName, userCommand):
global state, userLimit, userList
print "State : " + state
userAuthorizationLevel = isAuthorizedToAdd(userName)
if state != 'idle':
winStats = getWinStats(userName)
medicStats = getMedicStats(userName)
print medicStats
# if not userAuthorizationLevel:
# send("NOTICE " + userName + " : You must be authorized by an admin to PUG here. Ask any peons or any admins to allow you the access to add to the PUGs. The best way to do it is by asking directly in the channel or by asking a friend that has the authorization to do it. If you used to have access, type \"!stats me\" in order to find who deleted your access and talk with him in order to get it back.")
# return 0
if state == 'captain' or state == 'highlander' or state == 'normal':
remove(userName, printUsers=0)
if ((len(userList) == (userLimit -1) and classCount('medic') == 0) or (len(userList) == (userLimit -1) and classCount('medic') <= 1)) and not isMedic(userCommand):
if not isUser(userName) and userAuthorizationLevel == 3:
userLimit = userLimit + 1
elif not isUser(userName):
send("NOTICE " + userName + " : The only class available is medic. Type \"!add medic\" to join this round as this class.")
return 0
if userAuthorizationLevel == 3 and not isUser(userName) and len(userList) == userLimit:
userLimit = userLimit + 1
if len(extractClasses(userCommand)) == 0:
send("NOTICE " + userName + " : " + "Error! You need to specify a class. Example: \"!add scout\".")
return 0
elif len(extractClasses(userCommand)) > 1:
send("NOTICE " + userName + " : " + "Error! You can only add as one class.")
return 0
elif extractClasses(userCommand)[0] not in getAvailableClasses():
send("NOTICE " + userName + " : The class you specified is not in the available class list: " + ", ".join(getAvailableClasses()) + ".")
return 0
if len(userList) < userLimit:
print "User add : " + userName + " Command : " + userCommand
userList[userName] = createUser(userName, userCommand, userAuthorizationLevel)
printUserList()
if len(userList) >= (getTeamSize() * 2) and classCount('medic') > 1:
if classCount('demo') < 2 or classCount('scout') < 4 or classCount('soldier') < 3:
return 0
if state == 'captain' and countCaptains() < 2:
send("PRIVMSG " + config.channel + " :\x037,01Warning!\x030,01 This PUG needs 2 captains to start.")
return 0
if len(findAwayUsers()) == 0:
initGame()
elif type(awayTimer).__name__ == 'float':
sendMessageToAwayPlayers()
elif state == 'scrim':
if len(userList) == (userLimit - 2) and classCount('medic') == 0 and not isMedic(userCommand):
send("NOTICE " + userName + " : The only class available is medic. Type \"!add medic\" to join this round as this class.")
return 0
print "User add : " + userName + " Command : " + userCommand
userList[userName] = createUser(userName, userCommand, userAuthorizationLevel)
printUserList()
if len(userList) >= 6 and classCount('medic') > 0:
if len(findAwayUsers()) == 0:
initGame()
elif type(awayTimer).__name__ == 'float':
sendMessageToAwayPlayers()
elif state == 'picking':
if initTimer.isAlive():
if isInATeam(userName):
return 0
if isUserCountOverLimit():
if userAuthorizationLevel == 1:
return 0
elif userAuthorizationLevel == 3 and not isUser(userName):
userLimit = userLimit + 1
userList[userName] = createUser(userName, userCommand, userAuthorizationLevel)
printUserList()
else:
send("NOTICE " + userName + " : You can't add during the picking process.")
return 0
else:
send("PRIVMSG " + config.channel + " :\x030,01You can't \"!add\" until a pug has started.")
def addGame(userName, userCommand):
resetVariables()
global classList, gameServer, lastGameType, state, userLimit
if not setIP(userName, userCommand):
return 0
# Game type.
if re.search('captain', userCommand):
classList = ['demo', 'medic', 'scout', 'soldier']
lastGameType = 'captain'
state = 'captain'
userLimit = 24
elif re.search('highlander', userCommand):
classList = ['demo', 'engineer', 'heavy', 'medic', 'pyro', 'scout', 'sniper', 'soldier', 'spy']
lastGameType = 'highlander'
state = 'highlander'
userLimit = 18
else:
classList = ['demo', 'medic', 'scout', 'soldier']
lastGameType = 'normal'
state = 'normal'
userLimit = 12
updateLast(gameServer.split(':')[0], gameServer.split(':')[1], -(time.time()))
send("PRIVMSG " + config.channel + ' :\x030,01PUG started. Game type: ' + state + '. Type "!add" to join a game.')
def analyseIRCText(connection, event):
global adminList, userList, commandPat
userName = extractUserName(event.source())
userCommand = event.arguments()[0]
escapedChannel = cleanUserCommand(config.channel).replace('\\.', '\\\\.')
escapedUserCommand = cleanUserCommand(event.arguments()[0])
saveToLogs("[" + time.ctime() + "] <" + userName + "> " + userCommand + "\n")
#print userName, userCommand, escapedChannel, escapedUserCommand
if userName in userList:
updateUserStatus(userName, escapedUserCommand)
if re.match('^.*\\\\ \\\\\(.*\\\\\)\\\\ has\\\\ access\\\\ \\\\\x02\d*\\\\\x02\\\\ in\\\\ \\\\' + escapedChannel + '\\\\.$', escapedUserCommand):
adminList[userCommand.split()[0]] = int(userCommand.split()[4].replace('\x02', ''))
match = commandPat.match(userCommand)
if not match:
return
command = match.group("command")
params = match.group("params")
#print match.groupdict()
#print userName, command, params
if isAdminCommand(userName, command):
if isAdmin(userName):
#Execute the admin command.
executeCommand(userName, command, params.strip())
else :
# Exit and report an error.
send("PRIVMSG " + config.channel + " :\x030,01Warning " + userName + ", you are trying an admin command as a normal user.")
elif isUserCommand(userName, command):
executeCommand(userName, command, params.strip())
def assignCaptains(mode = 'captain'):
global teamA, teamB
if mode == 'captain':
captain1 = getAPlayer('captain')
userList[captain1['nick']]['status'] = 'captain'
assignUserToTeam(captain1['class'][0], 0, 'a', userList[captain1['nick']])
captain2 = getAPlayer('captain')
userList[captain2['nick']]['status'] = 'captain'
assignUserToTeam(captain2['class'][0], 0, 'b', userList[captain2['nick']])
send("PRIVMSG " + config.channel + ' :\x030,01Captains are \x0311,01' + teamA[0]['nick'] + '\x030,01 and \x034,01' + teamB[0]['nick'] + "\x030,01.")
elif mode == 'scrim':
captain1 = getAPlayer('captain')
assignUserToTeam(captain1['class'][0], 0, 'a', userList[captain1['nick']])
send("PRIVMSG " + config.channel + ' :\x030,01Captain is \x0308,01' + teamA[0]['nick'] + '\x030,01.')
printCaptainChoices()
def assignUserToTeam(gameClass, recursiveFriend, team, user):
global pastGames, teamA, teamB, userList
if gameClass:
user['class'] = [gameClass]
else:
user['class'] = []
if not team:
team = random.choice(['a', 'b'])
user['team'] = team
# Assign the user to the team if the team's not full.
if len(getTeam(team)) < getTeamSize(): # Debug : 6
getTeam(team).append(user)
else:
getTeam(getOppositeTeam(team)).append(user)
pastGames[len(pastGames) - 1]['players'].append(userList[user['nick']])
del userList[user['nick']]
return 0
def authorize(userName, userCommand, userLevel = 1):
commandList = string.split(userCommand, ' ')
if len(commandList) < 2:
send("NOTICE " + userName + " : Error, your command has too few arguments. Here is an example of a valid \"!authorize\" command: \"!authorize nick level\". The level is a value ranging from 0 to 500.")
return 0
adminLevel = isAdmin(userName)
if len(commandList) == 3 and commandList[2] != '' and re.match('^\d*$', commandList[2]) and int(commandList[2]) < adminLevel:
adminLevel = int(commandList[2])
authorizationStatus = getAuthorizationStatus(commandList[1])
authorizationText = ''
if userLevel == 0:
authorizationText = 'restricted'
elif userLevel == 1:
authorizationText = 'authorized'
elif userLevel == 2:
authorizationText = 'protected'
else:
authorizationText = 'authorized'
if userLevel > 1 and adminLevel <= 250:
send("NOTICE " + userName + " : Error, you lack access to this command.")
return 0
if(authorizationStatus[2] > adminLevel):
send("NOTICE " + userName + " : Error, you can't authorize this user because an other admin with a higher level already authorized or restricted him. And please, don't authorize this user under an other alias, respect the level system.")
return 0
else:
cursor = connection.cursor()
cursor.execute('INSERT INTO authorizations VALUES (%s, %s, %s, %s, %s)', (commandList[1], userLevel, adminLevel, time.time(), userName))
cursor.execute('COMMIT;')
send("NOTICE " + userName + " : You successfully " + authorizationText + " \"" + commandList[1] + "\" to play in \"" + config.channel + "\".")
def autoGameStart():
global lastGameType
if state == 'idle':
server = getAvailableServer()
else:
return 0
cursor = connection.cursor()
cursor.execute('UPDATE servers SET last = 0 WHERE last < 0 AND botID = %s', (botID,))
cursor.execute('COMMIT;')
if lastGameType == 'captain':
lastGameType = 'normal'
elif lastGameType == 'normal':
lastGameType = 'captain'
if server and startMode == 'automatic':
addGame(nick, '!addgame ' + lastGameType + ' ' + server['ip'] + ':' + server['port'])
def buildTeams():
global userList
fullClassList = classList
if getTeamSize() == 6:
fullClassList = formalTeam
for team in ['a', 'b']:
for gameClass in fullClassList:
assignUserToTeam(gameClass, 0, team, userList[getAPlayer(gameClass)])
printTeams()
def captain(userName, params):
global teamA, teamB
if len(teamA) > 0 and len(teamB) < 6:
for user in getTeam(captainStageList[captainStage]):
if user['status'] == 'captain':
captainName = user['nick']
break
send("PRIVMSG " + config.channel + ' :\x030,01Captain picking turn is to ' + captainName + '.')
else:
send("PRIVMSG " + config.channel + ' :\x030,01Picking process has not been started yet.')
def checkConnection():
global connectTimer
if not server.is_connected():
connect()
server.join(config.channel)
def classCount(gameClass):
global userList
counter = 0
for i, j in userList.copy().iteritems():
for userClass in userList[i]['class']:
if userClass == gameClass:
counter += 1
return counter
def cleanUserCommand(command):
return re.escape(command)
def clearCaptainsFromTeam(team):
for user in getTeam(team):
if user['status'] == 'captain':
user['status'] = ''
def clearSubstitutes(ip, port):
global subList
i = 0
print subList
while i < len(subList):
if subList[i]['server'] == ip + ':' + port or subList[i]['server'] == getDNSFromIP(ip) + ':' + port:
del subList[i]
i = i + 1
if i > 20:
break
def countCaptains():
userListCopy = userList.copy()
counter = 0
for user in userListCopy:
if userListCopy[user]['status'] == 'captain':
counter = counter + 1
return counter
def countProtectedUsers():
protectedCounter = 0
userListCopy = userList.copy()
for user in userListCopy:
if userListCopy[user]['authorization'] == 2:
protectedCounter = protectedCounter + 1
return [protectedCounter]
def connect():
print [config.network, config.port, nick, name]
server.connect(config.network, config.port, nick, ircname = name)
def createUser(userName, userCommand, userAuthorizationLevel):
commandList = string.split(userCommand, ' ')
user = {'authorization': userAuthorizationLevel, 'command':'', 'class':[], 'id':0, 'last':0, 'late':0, 'nick':'', 'remove':0, 'status':'', 'team':''}
user['command'] = userCommand
user['id'] = getNextPlayerID()
user['last'] = time.time()
if (getUserCount() + 1) > 12:
user['late'] = 1
user['class'] = extractClasses(userCommand)
if re.search('captain', userCommand):
#if 'medic' not in user['class'] and getWinStats(userName)[1] < 20:
#send("NOTICE " + userName + " : " + "You don't meet the requirements to be a captain: minimum of 20 games played.")
#else:
user['status'] = 'captain'
user['nick'] = userName
if state == 'captain' or state == 'picking':
if len(user['class']) > 0:
send("NOTICE " + userName + " : " + "You sucessfully subscribed to the picking process as: " + ", ".join(user['class']) + "")
return user
def drop(connection, event):
userName = ''
if len(event.arguments()) > 1:
userName = event.arguments()[0]
else:
userName = extractUserName(event.source())
remove(userName)
def endGame(userName, params):
global gameServer, initTimer, state
initTimer.cancel()
updateLast(gameServer.split(':')[0], gameServer.split(':')[1], 0)
state = 'idle'
print 'PUG stopped.'
def automatic(userName, params):
"""sets the start mode to automatic"""
setStartMode("automatic")
def manual(userName, params):
"""sets the start mode to manual"""
setStartMode("manual")
def executeCommand(userName, command, params):
global commandMap
if command in commandMap:
return commandMap[command](userName, params)
if command == "!status":
thread.start_new_thread(status, ())
return 0
if command == "!whattimeisit":
send("PRIVMSG " + config.channel + " :\x038,01* \x039,01Hammertime \x038,01*")
return 0
def extractClasses(userCommand):
global classList
classes = []
commandList = string.split(userCommand, ' ')
for i in commandList:
for j in classList:
if i == j:
classes.append(j)
return classes
def extractUserName(user):
if user:
return string.split(user, '!')[0]
else:
return ''
def findAwayUsers():
global awayList, userList
if type(awayTimer).__name__ == 'float' and time.time() - awayTimer <= (5 * 60):
awayList = {}
elif len(awayList) == 0:
for user in userList:
if user in userList and userList[user]['last'] <= (time.time() - (7 * 60)):
awayList[user] = userList[user]
return awayList
def game(userName, userCommand):
global captainStageList, state
mode = userCommand.split(' ')
if len(mode) <= 1:
send("PRIVMSG " + config.channel + " :\x030,01The actual game mode is set to \"" + state + "\".")
return 0
elif not isAdmin(userName):
send("PRIVMSG " + config.channel + " :\x030,01Warning " + userName + ", you are trying an admin command as a normal user.")
return 0
if mode[1] == 'captain':
if state == 'scrim':
captainStageList = ['a', 'b', 'a', 'b', 'b', 'a', 'a', 'b', 'b', 'a']
state = 'captain'
else:
send("NOTICE " + userName + " :You can't switch the game mode in this bot state.")
elif mode[1] == 'scrim':
if state == 'captain':
captainStageList = ['a', 'a', 'a', 'a', 'a']
state = 'scrim'
else:
send("NOTICE " + userName + " :You can't switch the game mode in this bot state.")
def getAPlayer(playerType):
global userList
if playerType == 'captain':
medics = []
medicsCaptains = []
otherCaptains = []
userListCopy = userList.copy()
for user in userListCopy:
if re.search('medic', userListCopy[user]['command']):
if userListCopy[user]['status'] == 'captain':
medicsCaptains.append(userListCopy[user])
else:
medics.append(userListCopy[user])
elif userListCopy[user]['status'] == 'captain':
otherCaptains.append(userListCopy[user])
if len(medicsCaptains) > 0:
player = getRandomItemFromList(medicsCaptains)
player['class'] = ['medic']
elif len(otherCaptains) > 0:
maximum = 0
otherCaptainWithMaximumRatio = ''
for otherCaptain in otherCaptains:
winStats = getWinStats(otherCaptain['nick'])
if winStats[3] > maximum:
maximum = winStats[3]
otherCaptainWithMaximumRatio = otherCaptain['nick']
if maximum > 0:
player = userListCopy[otherCaptainWithMaximumRatio]
else:
player = getRandomItemFromList(otherCaptains)
if len(player['class']) > 0:
player['class'] = [player['class'][0]]
else:
player['class'] = ['scout']
else:
player = getRandomItemFromList(medics)
player['class'] = ['medic']
return player
else:
forcedList = []
candidateList = []
for user in userList.copy():
forcedList.append(user)
if len(userList[user]['class']) > 0 and playerType == userList[user]['class'][0]:
candidateList.append(user)
if len(candidateList) > 0:
return getRandomItemFromList(candidateList)
else:
return getRandomItemFromList(forcedList)
def getAuthorizationStatus(userName):
cursor = connection.cursor()
cursor.execute('SELECT * FROM authorizations WHERE nick ILIKE %s AND time = (select MAX(time) FROM authorizations WHERE nick ILIKE %s)', (userName, userName))
for row in cursor.fetchall():
return [userName, row[1], row[2], row[3], row[4]]
return [userName, 0, 0, 0, '']
def getAvailableClasses():
availableClasses = []
if userLimit == 12:
numberOfPlayersPerClass = {'demo':2, 'medic':2, 'scout':4, 'soldier':4}
elif userLimit == 24:
numberOfPlayersPerClass = {'demo':4, 'medic':4, 'scout':8, 'soldier':8}
if getTeamSize() == 9:
numberOfPlayersPerClass = {'demo':2, 'engineer':2, 'heavy':2, 'medic':2, 'pyro':2, 'scout':2, 'sniper':2, 'soldier':2, 'spy':2}
for gameClass in classList:
if classCount(gameClass) < numberOfPlayersPerClass[gameClass]:
availableClasses.append(gameClass)
return availableClasses
def getAvailableServer():
for server in getServerList():
if server['last'] >= 0 and (time.time() - server['last']) >= (60 * 75):
return {'ip':server['dns'], 'port':server['port']}
return 0
def getCaptainNameFromTeam(team):
for user in getTeam(team):
if user['status'] == 'captain':
return user['nick']
def getDNSFromIP(ip):
for server in getServerList():
if server['ip'] == ip:
return server['dns']
return ip
def getIPFromDNS(dns):
for server in getServerList():
if server['dns'] == dns:
return server['ip']
return dns
def getLastTimeMedic(userName):
cursor = connection.cursor()
cursor.execute('SELECT time FROM stats WHERE nick ILIKE %s AND class = \'medic\' ORDER BY time DESC LIMIT 1;', (userName,))
for row in cursor.fetchall():
return row[0]
return 0
def getMap():
global mapList
return mapList[random.randint(0, (len(mapList) - 1))]
def getMedicRatioColor(medicRatio):
if medicRatio >= 7:
return "\x039,01"
elif medicRatio >= 5:
return "\x038,01"
else:
return "\x034,01"
def getMedicStats(userName):
medicStats = {'totalGamesAsMedic':0, 'medicWinRatio':0}
cursor = connection.cursor()
cursor.execute('SELECT lower(nick), count(*), sum(result) FROM stats where nick ILIKE %s AND class = \'medic\' AND botID = %s GROUP BY lower(nick)', (userName, botID))
for row in cursor.fetchall():
medicStats['totalGamesAsMedic'] = row[1]
medicStats['medicWinRatio'] = float((float(row[2]) + float(row[1])) / float(row[1] * 2))
return medicStats
def getNextPlayerID():
global userList
largestID = 0
for user in userList.copy():
if userList[user]['id'] > largestID:
largestID = userList[user]['id']
return largestID + 1
def getNextSubID():
global subList
highestID = 0
for sub in subList:
if sub['id'] > highestID:
highestID = sub['id']
return highestID + 1
def getOppositeTeam(team):
if team == 'a':
return 'b'
else:
return 'a'
def getPlayerName(userNumber):
global userList
for user in userList.copy():
if userList[user]['id'] == userNumber:
return userList[user]['nick']
def getPlayerNumber(userName):
global userList
for user in userList.copy():
if user == userName:
return userList[user]['id']
def getPlayerTeam(userName):
for teamID in ['a', 'b']:
team = getTeam(teamID)
for user in team:
if user['nick'] == userName:
return teamID
def getRandomItemFromList(list):
listLength = len(list)
if listLength > 1:
return list[random.randint(0, listLength - 1)]
elif listLength == 1:
return list[0]
else:
return []
def getRemainingClasses():
global captainStage, captainStageList, formalTeam
remainingClasses = formalTeam[:]
team = getTeam(captainStageList[captainStage])
for user in team:
if user['class'][0] in remainingClasses:
remainingClasses.remove(user['class'][0])
uniqueRemainingClasses = {}
for gameClass in remainingClasses:
uniqueRemainingClasses[gameClass] = gameClass
return uniqueRemainingClasses
def getServerList():
serverList = []
cursor = connection.cursor()
cursor.execute('SELECT * FROM servers')
for row in cursor.fetchall():
serverList.append({'dns':row[0], 'ip':row[1], 'last':row[2], 'port':row[3], 'botID':row[4]})
return serverList
def getSubIndex(id):
global subList
counter = 0
for sub in subList:
if sub['id'] == int(id):
return counter
counter += 1
return -1
def getTeam(team):
global teamA, teamB
if team == 'a':
return teamA
else:
return teamB
def getTeamSize():
teamSize = 6
if len(classList) == 9:
teamSize = 9
return teamSize
def getUserCount():
global teamA, teamB, userList
teams = [teamA, teamB]
counter = len(userList)
teamCounter = 0
for team in teams:
for user in teams[teamCounter]:
counter += 1
teamCounter += 1
return counter
def getWinStats(userName):
cursor = connection.cursor()
cursor.execute('SELECT lower(nick) AS nick, count(*), sum(result), (SELECT count(*) FROM stats WHERE nick ILIKE %s AND botID = %s) AS total FROM (SELECT * FROM stats WHERE nick ILIKE %s AND botID = %s ORDER BY TIME DESC LIMIT 20) AS stats GROUP BY lower(nick)', (userName, botID, userName, botID))
for row in cursor.fetchall():
return [row[0], row[1], row[2], float((float(row[2]) + float(row[1])) / float(row[1] * 2)), row[3]]
return [userName, 0, 0, 0, 0]
def help(userName, params):
global adminCommands, userCommands
send("PRIVMSG " + config.channel + " : \x0311,01User related commands:\x030,01 !add, !game, !ip, !last, !limit, !list, !man, !mumble, !need, !needsub, !players, !remove, !scramble, !stats, !status, !sub")
send("PRIVMSG " + config.channel + " : \x0311,01Captain related commands:\x030,01 !captain, !pick")
if isAdmin(userName):
send("PRIVMSG %s : \x0311,01Admin related commands:\x030,01 %s" % (config.channel, ", ".join(adminCommands)))
def ip(userName, userCommand):
global gameServer
commandList = string.split(userCommand, ' ')
if len(commandList) < 2:
if gameServer != '':
message = "\x030,01Server IP: \"connect " + gameServer + "; password " + password + "\". Servers are provided by Command Channel: \x0307,01https://commandchannel.com/"
send("PRIVMSG " + config.channel + " :" + message)
return 0
setIP(userName, userCommand)
def isAdmin(userName):
global adminList
server.send_raw("PRIVMSG ChanServ :" + config.channel + " a " + userName)
counter = 0
while not userName in adminList and counter < 20:
irc.process_once(0.2)
counter += 1
print adminList
if userName in adminList:
return adminList[userName]
else:
return 0
def isAdminCommand(userName, userCommand):
global adminCommands
userCommand = string.split(userCommand, ' ')[0]
userCommand = removeLastEscapeCharacter(userCommand)
for command in adminCommands:
if command == userCommand:
return 1
return 0
def isAuthorizedCaptain(userName):
global captainStage, captainStageList, teamA, teamB
team = getTeam(captainStageList[captainStage])
for user in team:
if user['status'] == 'captain' and user['nick'] == userName:
return 1
return 0
def isAuthorizedToAdd(userName):
authorizationStatus = getAuthorizationStatus(userName)
winStats = getWinStats(userName)
if authorizationStatus[1] > 0:
return authorizationStatus[1]
elif winStats[1] and authorizationStatus[2] == 0:
return 1
else:
return 0
def isGamesurgeCommand(userCommand):
global gamesurgeCommands
for command in gamesurgeCommands:
if command == userCommand:
return 1
return 0
def isMatch():
for server in getServerList():
if server['last'] > 0 and server['botID'] == botID:
return 1
return 0
def isMedic(userCommand):
if 'medic' in userCommand.split():
return 1
else:
return 0
def isUser(userName):
if userName in userList:
return 1
else:
return 0
def isUserCommand(userName, command):
global userCommands
if command in userCommands:
return True
send("NOTICE " + userName + " : Invalid command: \"" + command + "\". Type \"!man\" for usage commands.")
return False
def isUserCountOverLimit():
global teamA, teamB, userLimit, userList
teams = [teamA, teamB]
userCount = getUserCount()
if userCount < userLimit:
return 0
else:
return 1
def initGame():
global gameServer, initTime, initTimer, nick, pastGames, scrambleList, startGameTimer, state, teamA, teamB
if state == 'building' or state == 'picking':
return 0
initTime = int(time.time())
pastGames.append({'players':[], 'server':gameServer, 'time':initTime})
if state == "normal" or state == "highlander":
scrambleList = []
send("PRIVMSG " + config.channel + " :\x038,01Teams are being drafted, please wait in the channel until this process is over.")
send("PRIVMSG " + config.channel + " :\x037,01If you find teams unfair you can type \"!scramble\" and they will be adjusted.")
state = 'building'
initTimer = threading.Timer(15, buildTeams)
initTimer.start()
startGameTimer = threading.Timer(45, startGame)
startGameTimer.start()
elif state == "captain":
if countCaptains() < 2:
return 0
send("PRIVMSG " + config.channel + " :\x038,01Teams are being drafted, please wait in the channel until this process is over.")
state = 'picking'
initTimer = threading.Timer(45, assignCaptains, ['captain'])
initTimer.start()
players(nick, '')
elif state == "scrim":
send("PRIVMSG " + config.channel + " :\x038,01Team is being drafted, please wait in the channel until this process is over.")
state = 'picking'
initTimer = threading.Timer(45, assignCaptains, ['scrim'])
initTimer.start()
players(nick, '')
def initServer():
global gameServer, lastGame
try:
lastGame = time.time()
TF2Server = SRCDS.SRCDS(string.split(gameServer, ':')[0], int(string.split(gameServer, ':')[1]), config.rconPassword, 10)
TF2Server.rcon_command('changelevel ' + getMap())
except:
return 0
def isInATeam(userName):
teamList = ['a', 'b']
for teamName in teamList:
team = getTeam(teamName)
for user in team:
if user['nick'] == userName:
return 1
return 0
def last(userName, params):
global lastGame
if lastGame == 0:
send("PRIVMSG " + config.channel + " :\x030,010 matches have been played since the bot was restarted.")
return 0
message = "PRIVMSG " + config.channel + " :\x030,01"
if isMatch():
message += "A game is currently being played. "
lastTime = (time.time() - lastGame) / 3600
hours = math.floor(lastTime)
minutes = math.floor((lastTime - hours) * 60)
if hours != 0:
message += str(int(hours)) + " hour(s) "
message += str(int(minutes)) + " minute(s) "
send(message + "have elapsed since the last pug started.")
def limit(userName, userCommand):
global userLimit
commandList = string.split(userCommand, ' ')
if len(commandList) < 2:
send("PRIVMSG " + config.channel + " :\x030,01The PUG's user limit is set to \"" + str(userLimit) + "\".")
return 0
try:
if not isAdmin(userName):
send("PRIVMSG " + config.channel + " :\x030,01Warning " + userName + ", you are trying an admin command as a normal user.")
return 0
if int(commandList[1]) < 12:
send("NOTICE " + userName + " : The limit value must be equal or above 12.")
return 0
if int(commandList[1]) > maximumUserLimit:
send("NOTICE " + userName + " : The maximum limit is at " + str(maximumUserLimit))
userLimit = 24
return 0
except:
return 0
userLimit = int(commandList[1])
def listeningTF2Servers():
global connection, pastGames
cursor = connection.cursor()
while 1:
time.sleep(1)
cursor.execute('SELECT * FROM srcds')
try:
queryData = cursor.fetchall()
except:
queryData = []
for i in range(0, len(queryData)):
srcdsData = queryData[i][0].split()
server = srcdsData[len(srcdsData) - 1]
ip = string.split(server, ':')[0]
port = string.split(server, ':')[1]
if re.search('^!needsub', srcdsData[0]):
needsub('', queryData[i][0])
cursor.execute('DELETE FROM srcds WHERE time = %s', (queryData[i][1],))
cursor.execute('COMMIT;')
for pastGame in pastGames:
if pastGame['server'] == server or pastGame['server'] == getDNSFromIP(ip) + ':' + port:
if re.search('^!gameover', srcdsData[0]):
score = srcdsData[1]
clearSubstitutes(ip, port)
updateLast(ip, port, 0)
updateStats(ip, port, score)
send("PRIVMSG " + config.channel + " :\x030,01Game over on server \"" + getDNSFromIP(ip) + ":" + port + "\", final score is: \x0311,01" + score.split(':')[0] + "\x030,01 to \x034,01" + score.split(':')[1] + "\x030,01.")
cursor.execute('DELETE FROM srcds WHERE time = %s', (queryData[i][1],))
cursor.execute('COMMIT;')
if time.time() - queryData[i][1] >= 20:
cursor.execute('DELETE FROM srcds WHERE time = %s', (queryData[i][1],))
cursor.execute('COMMIT;')
def mumble(userName, params):
global voiceServer
message = "\x030,01Voice server IP: " + voiceServer['ip'] + ":" + voiceServer['port'] + " Password: " + password + " Download: http://download.mumble.com/en/mumble-1.2.3a.msi"
send("PRIVMSG " + config.channel + " :" + message)
def needsub(userName, userCommand):
global classList, subList
commandList = string.split(userCommand, ' ')
sub = {'class':'unspecified', 'id':getNextSubID(), 'server':'', 'steamid':'', 'team':'unspecified'}
for command in commandList:
# Set the server IP.
if re.search("[0-9a-z]*\.[0-9a-z]*:[0-9][0-9][0-9][0-9][0-9]$", command):
sub['server'] = re.findall("[0-9a-z]*\..*:[0-9][0-9][0-9][0-9][0-9]", command)[0]
sub['server'] = getDNSFromIP(sub['server'].split(':')[0]) + ':' + sub['server'].split(':')[1]
# Set the Steam ID.
if re.search("STEAM", command):
sub['steamid'] = command
if sub['server'] == '':
send("NOTICE " + userName + " : You must enter the information like so: !needsub chicago1.tf2pug.com:27015 red medic")
return 0
# Set the team.
if 'blue' in commandList:
sub['team'] = '\x0311,01Blue\x030,01'
elif 'red' in commandList:
sub['team'] = '\x034,01Red\x030,01'
# Set the class.
for argument in commandList:
if argument in classList:
sub['class'] = argument
subList.append(sub)
printSubs()
def nickchange(connection, event):
global userList
oldUserName = extractUserName(event.source())
newUserName = event.target()
if oldUserName in userList:
userList[newUserName] = userList[oldUserName]
userList[newUserName]['nick'] = newUserName
del userList[oldUserName]
def pick(userName, userCommand):
global captainStage, captainStageList, classList, state, teamA, teamB, userList
if (len(captainStageList) >= 10 and (not len(teamA) or not len(teamB))) or (len(captainStageList) == 5 and not len(teamA)):
send("NOTICE " + userName + " : The selection is not started yet.")
return 0
commandList = string.split(userCommand, ' ')
if len(commandList) < 2:
send("NOTICE " + userName + " : Error, your command has too few arguments. Here is an example of a valid \"!pick\" command: \"!pick 13 scout\".")
return 0
assignToCaptain = 0
commandsToDelete = []
counter = 0
gameClass = ''
medicsRemaining = 0
for command in commandList:
if command in classList:
gameClass = command
commandsToDelete.append(counter)
elif command == 'captain':
assignToCaptain = 1
commandsToDelete.append(counter)
counter += 1
for i in reversed(commandsToDelete):
del commandList[i]
userFound = 0
if re.search('^[0-9][0-9]*$', commandList[0]) and getPlayerName(int(commandList[0])):
commandList[0] = getPlayerName(int(commandList[0]))
userFound = 1
else:
# Check if this nickname exists in the player list.
for user in userList.copy():
if userList[user]['nick'] == commandList[0]:
userFound = 1
break
team = getTeam(getOppositeTeam(captainStageList[captainStage]))
oppositeTeamHasMedic = 0
for i in range(len(team)):
if 'medic' in team[i]['class']:
oppositeTeamHasMedic = 1
for user in userList.copy():
if 'medic' in userList[user]['class']:
medicsRemaining = medicsRemaining + 1
if not assignToCaptain and counter == 3:
send("NOTICE " + userName + " : Error, your command has 3 parameters but doesn't contain the word \"captain\". Did you try to set your pick as a captain?")
return 0
if not userFound:
send("NOTICE " + userName + " : Error, this user doesn\'t exist.")
return 0
if lastGameType != 'scrim' and not oppositeTeamHasMedic and medicsRemaining == 1 and 'medic' in userList[commandList[0]]['class']:
send("NOTICE " + userName + " : Error, you can't pick the last medic if you already have one.")
return 0
if gameClass == '':
send("NOTICE " + userName + " : Error, you must specify a class from this list: " + ', '.join(getRemainingClasses()) + ".")
return 0
if gameClass not in userList[commandList[0]]['class']:
send("NOTICE " + userName + " : You must pick the user as the class he added.")
return 0
if gameClass not in getRemainingClasses():
send("NOTICE " + userName + " : This class is full, pick another one from this list: " + ', '.join(getRemainingClasses()))
return 0
if isAuthorizedCaptain(userName):
send("NOTICE " + userName + " : You selected \"" + commandList[0] + "\" as \"" + gameClass + "\".")
userList[commandList[0]]['status'] = ''
if assignToCaptain:
clearCaptainsFromTeam(getPlayerTeam(userName))
userList[commandList[0]]['status'] = 'captain'
send("NOTICE " + commandList[0] + " : " + getCaptainNameFromTeam(getPlayerTeam(userName)) + " picked you as " + gameClass)
send("NOTICE " + getCaptainNameFromTeam(getOppositeTeam(getPlayerTeam(userName))) + " : \x037" + userName + " picked " + commandList[0] + " as " + gameClass)
assignUserToTeam(gameClass, 0, getPlayerTeam(userName), userList[commandList[0]])
if captainStage < (len(captainStageList) - 1):
captainStage += 1
printCaptainChoices()
else:
startGame()
else:
send("NOTICE " + userName + " : It is not your turn.")
def players(userName, params):
printCaptainChoices('channel')
def pubmsg(connection, event):
analyseIRCText(connection, event)
def printCaptainChoices(printType = 'private'):
global classList, captainStage, captainStageList, userList
if printType == 'private':
captainName = getCaptainNameFromTeam(captainStageList[captainStage])
captainColor = '\x0312'
followingColor = '\x035'
protectedColor = '\x033'
dataPrefix = "NOTICE " + captainName + " : "
send(dataPrefix + captainName + ", you are captain of a team and it's your turn to pick a player. Type \"!pick # class\" to pick somebody for your team.")
send(dataPrefix + "Remaining classes: " + ', '.join(getRemainingClasses()))
else:
captainColor = '\x038,01'
followingColor = '\x030,01'
protectedColor = '\x039,01'
dataPrefix = "PRIVMSG " + config.channel + " :\x030,01"
for gameClass in classList:
choiceList = []
for userName in userList.copy():
if gameClass in userList[userName]['class']:
protected = ''
"""if userList[userName]['authorization'] > 1 and printType == 'private':
protected = protectedColor + 'P' + followingColor"""