-
Notifications
You must be signed in to change notification settings - Fork 24
/
spunky.py
4268 lines (3866 loc) · 230 KB
/
spunky.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/env python
# -*- coding: utf-8 -*-
"""
Spunky Bot - An automated game server bot
http://github.com/spunkybot/spunkybot
Author: Alexander Kress
This program is released under the MIT License. See LICENSE for more details.
## About ##
Spunky Bot is a lightweight game server administration bot and RCON tool,
inspired by the eb2k9 bot by Shawn Haggard.
The purpose of Spunky Bot is to administrate an Urban Terror 4.1 / 4.2 / 4.3
server and provide statistics data for players.
## Configuration ##
Modify the UrT server config as follows:
* seta g_logsync "1"
* seta g_loghits "1"
* seta g_friendlyfire "2"
Modify the files '/conf/settings.conf' and '/conf/rules.conf'
Run the bot: python spunky.py
"""
__version__ = '1.13.0'
### IMPORTS
import os
import time
import sqlite3
import math
import textwrap
import random
import ConfigParser
import logging.handlers
from Queue import Queue
from threading import Thread
from threading import RLock
import lib.pygeoip as pygeoip
import lib.schedule as schedule
from lib.pyquake3 import PyQuake3
# Get an instance of a logger
logger = logging.getLogger('spunkybot')
logger.setLevel(logging.DEBUG)
logger.propagate = False
# Bot player number
BOT_PLAYER_NUM = 1022
# RCON Delay in seconds, recommended range: 0.18 - 0.33
RCON_DELAY = 0.3
COMMANDS = {'help': {'desc': 'display all available commands', 'syntax': '^7Usage: ^2!help', 'level': 0, 'short': 'h'},
'forgive': {'desc': 'forgive a player for team killing', 'syntax': '^7Usage: ^2!forgive ^7[<name>]', 'level': 0, 'short': 'f'},
'forgiveall': {'desc': 'forgive all team kills', 'syntax': '^7Usage: ^2!forgiveall', 'level': 0, 'short': 'fa'},
'forgivelist': {'desc': 'list all players who killed you', 'syntax': '^7Usage: ^2!forgivelist', 'level': 0, 'short': 'fl'},
'forgiveprev': {'desc': 'forgive last team kill', 'syntax': '^7Usage: ^2!forgiveprev', 'level': 0, 'short': 'fp'},
'grudge': {'desc': 'grudge a player for team killing, a grudged player will not be forgiven', 'syntax': '^7Usage: ^2!grudge ^7[<name>]', 'level': 0},
'bombstats': {'desc': 'display Bomb stats', 'syntax': '^7Usage: ^2!bombstats', 'level': 0},
'ctfstats': {'desc': 'display Capture the Flag stats', 'syntax': '^7Usage: ^2!ctfstats', 'level': 0},
'freezestats': {'desc': 'display freeze/thawout stats', 'syntax': '^7Usage: ^2!freezestats', 'level': 0},
'hestats': {'desc': 'display HE grenade kill stats', 'syntax': '^7Usage: ^2!hestats', 'level': 0},
'hits': {'desc': 'display hit stats', 'syntax': '^7Usage: ^2!hits', 'level': 0},
'hs': {'desc': 'display headshot counter', 'syntax': '^7Usage: ^2!hs', 'level': 0},
'knife': {'desc': 'display knife kill stats', 'syntax': '^7Usage: ^2!knife', 'level': 0},
'register': {'desc': 'register yourself as a basic user', 'syntax': '^7Usage: ^2!register', 'level': 0},
'spree': {'desc': 'display current kill streak', 'syntax': '^7Usage: ^2!spree', 'level': 0},
'stats': {'desc': 'display current map stats', 'syntax': '^7Usage: ^2!stats', 'level': 0},
'teams': {'desc': 'balance teams', 'syntax': '^7Usage: ^2!teams', 'level': 0},
'time': {'desc': 'display the current server time', 'syntax': '^7Usage: ^2!time', 'level': 0},
# user commands, level 1
'regtest': {'desc': 'display current user status', 'syntax': '^7Usage: ^2!regtest', 'level': 1},
'xlrstats': {'desc': 'display full player statistics', 'syntax': '^7Usage: ^2!xlrstats ^7[<name>]', 'level': 1},
'xlrtopstats': {'desc': 'display the top players', 'syntax': '^7Usage: ^2!xlrtopstats', 'level': 1, 'short': 'topstats'},
# moderator commands, level 20
'admintest': {'desc': 'display current admin status', 'syntax': '^7Usage: ^2!admintest', 'level': 20},
'country': {'desc': 'get the country of a player', 'syntax': '^7Usage: ^2!country ^7<name>', 'level': 20},
'lastmaps': {'desc': 'list the last played maps', 'syntax': '^7Usage: ^2!lastmaps', 'level': 20},
'lastvote': {'desc': 'display information about the last called vote', 'syntax': '^7Usage: ^2!lastvote', 'level': 20},
'leveltest': {'desc': 'get the admin level for a given player or myself', 'syntax': '^7Usage: ^2!leveltest ^7[<name>]', 'level': 20, 'short': 'lt'},
'list': {'desc': 'list all connected players', 'syntax': '^7Usage: ^2!list', 'level': 20},
'locate': {'desc': 'display geolocation info of a player', 'syntax': '^7Usage: ^2!locate ^7<name>', 'level': 20, 'short': 'lc'},
'mute': {'desc': 'mute or un-mute a player', 'syntax': '^7Usage: ^2!mute ^7<name> [<duration>]', 'level': 20},
'nextmap': {'desc': 'display the next map in rotation', 'syntax': '^7Usage: ^2!nextmap', 'level': 20},
'poke': {'desc': 'notify a player that he needs to move', 'syntax': '^7Usage: ^2!poke ^7<name>', 'level': 20},
'seen': {'desc': 'display when a player was last seen', 'syntax': '^7Usage: ^2!seen ^7<name>', 'level': 20},
'shuffleteams': {'desc': 'shuffle the teams', 'syntax': '^7Usage: ^2!shuffleteams', 'level': 20, 'short': 'shuffle'},
'spec': {'desc': 'move yourself to spectator', 'syntax': '^7Usage: ^2!spec', 'level': 20, 'short': 'sp'},
'startdemo': {'desc': 'start recording of serverside demo', 'syntax': '^7Usage: ^2!startdemo ^7<name>', 'level': 20},
'stopdemo': {'desc': 'stop recording of serverside demo', 'syntax': '^7Usage: ^2!stopdemo ^7<name>', 'level': 20},
'warn': {'desc': 'warn player', 'syntax': '^7Usage: ^2!warn ^7<name> [<reason>]', 'level': 20, 'short': 'w'},
'warninfo': {'desc': 'display how many warnings a player has', 'syntax': '^7Usage: ^2!warninfo ^7<name>', 'level': 20, 'short': 'wi'},
'warnremove': {'desc': "remove a player's last warning", 'syntax': '^7Usage: ^2!warnremove ^7<name>', 'level': 20, 'short': 'wr'},
'warns': {'desc': 'list the warnings', 'syntax': '^7Usage: ^2!warns', 'level': 20},
'warntest': {'desc': 'test a warning', 'syntax': '^7Usage: ^2!warntest ^7<warning>', 'level': 20},
# admin commands, level 40
'admins': {'desc': 'list all the online admins', 'syntax': '^7Usage: ^2!admins', 'level': 40},
'afk': {'desc': 'force a player to spec, because he is away from keyboard', 'syntax': '^7Usage: ^2!afk ^7<name>', 'level': 40},
'aliases': {'desc': 'list the aliases of a player', 'syntax': '^7Usage: ^2!aliases ^7<name>', 'level': 40, 'short': 'alias'},
'bigtext': {'desc': 'display big message on screen', 'syntax': '^7Usage: ^2!bigtext ^7<text>', 'level': 40},
'exit': {'desc': 'display last disconnected player', 'syntax': '^7Usage: ^2!exit', 'level': 40},
'find': {'desc': 'display the slot number of a player', 'syntax': '^7Usage: ^2!find ^7<name>', 'level': 40},
'force': {'desc': 'force a player to the given team', 'syntax': '^7Usage: ^2!force ^7<name> <blue/red/spec> [<lock>]', 'level': 40},
'kick': {'desc': 'kick a player', 'syntax': '^7Usage: ^2!kick ^7<name> <reason>', 'level': 40, 'short': 'k'},
'nuke': {'desc': 'nuke a player', 'syntax': '^7Usage: ^2!nuke ^7<name>', 'level': 40},
'regulars': {'desc': 'display the regular players online', 'syntax': '^7Usage: ^2!regulars', 'level': 40, 'short': 'regs'},
'say': {'desc': 'say a message to all players', 'syntax': '^7Usage: ^2!say ^7<text>', 'level': 40, 'short': '!!'},
'tell': {'desc': 'tell a message to a specific player', 'syntax': '^7Usage: ^2!tell ^7<name> <text>', 'level': 40},
'tempban': {'desc': 'ban a player temporary for the given period of 1 sec to 3 days', 'syntax': '^7Usage: ^2!tempban ^7<name> <duration> [<reason>]', 'level': 40, 'short': 'tb'},
'warnclear': {'desc': 'clear the player warnings', 'syntax': '^7Usage: ^2!warnclear ^7<name>', 'level': 40, 'short': 'wc'},
# fulladmin commands, level 60
'ban': {'desc': 'ban a player for several days', 'syntax': '^7Usage: ^2!ban ^7<name> <reason>', 'level': 60, 'short': 'b'},
'baninfo': {'desc': 'display active bans of a player', 'syntax': '^7Usage: ^2!baninfo ^7<name>', 'level': 60, 'short': 'bi'},
'ci': {'desc': 'kick player with connection interrupt', 'syntax': '^7Usage: ^2!ci ^7<name>', 'level': 60},
'forgiveclear': {'desc': "clear a player's team kills", 'syntax': '^7Usage: ^2!forgiveclear ^7[<name>]', 'level': 60, 'short': 'fc'},
'forgiveinfo': {'desc': "display a player's team kills", 'syntax': '^7Usage: ^2!forgiveinfo ^7<name>', 'level': 60, 'short': 'fi'},
'ping': {'desc': 'display the ping of a player', 'syntax': '^7Usage: ^2!ping ^7<name>', 'level': 60},
'id': {'desc': 'show the IP, guid and authname of a player', 'syntax': '^7Usage: ^2!id ^7<name>', 'level': 60},
'kickbots': {'desc': 'kick all bots', 'syntax': '^7Usage: ^2!kickbots', 'level': 60, 'short': 'kb'},
'rain': {'desc': 'enables or disables rain', 'syntax': '^7Usage: ^2!rain ^7<on/off>', 'level': 60},
'scream': {'desc': 'scream a message in different colors to all players', 'syntax': '^7Usage: ^2!scream ^7<text>', 'level': 60},
'slap': {'desc': 'slap a player (a number of times)', 'syntax': '^7Usage: ^2!slap ^7<name> [<amount>]', 'level': 60},
'status': {'desc': 'report the status of the bot', 'syntax': '^7Usage: ^2!status', 'level': 60},
'swap': {'desc': 'swap teams for player A and B', 'syntax': '^7Usage: ^2!swap ^7<name1> [<name2>]', 'level': 60},
'version': {'desc': 'display the version of the bot', 'syntax': '^7Usage: ^2!version', 'level': 60},
'veto': {'desc': 'stop voting process', 'syntax': '^7Usage: ^2!veto', 'level': 60},
# senioradmin commands, level 80
'addbots': {'desc': 'add up to 4 bots to the game', 'syntax': '^7Usage: ^2!addbots', 'level': 80},
'banall': {'desc': 'ban all players matching pattern', 'syntax': '^7Usage: ^2!banall ^7<pattern> [<reason>]', 'level': 80, 'short': 'ball'},
'banlist': {'desc': 'display the last active 10 bans', 'syntax': '^7Usage: ^2!banlist', 'level': 80},
'bots': {'desc': 'enables or disables bot support', 'syntax': '^7Usage: ^2!bots ^7<on/off>', 'level': 80},
'cyclemap': {'desc': 'cycle to the next map', 'syntax': '^7Usage: ^2!cyclemap', 'level': 80},
'exec': {'desc': 'execute given config file', 'syntax': '^7Usage: ^2!exec ^7<filename>', 'level': 80},
'gear': {'desc': 'set allowed weapons', 'syntax': '^7Usage: ^2!gear ^7<default/all/knife/pistol/shotgun/sniper/magnum/mac>', 'level': 80},
'instagib': {'desc': 'set Instagib mode', 'syntax': '^7Usage: ^2!instagib ^7<on/off>', 'level': 80},
'kickall': {'desc': 'kick all players matching pattern', 'syntax': '^7Usage: ^2!kickall ^7<pattern> [<reason>]', 'level': 80, 'short': 'kall'},
'kill': {'desc': 'kill a player', 'syntax': '^7Usage: ^2!kill ^7<name>', 'level': 80},
'clear': {'desc': 'clear all player warnings', 'syntax': '^7Usage: ^2!clear', 'level': 80, 'short': 'kiss'},
'lastadmin': {'desc': 'display the last disconnected admin', 'syntax': '^7Usage: ^2!lastadmin', 'level': 80},
'lastbans': {'desc': 'list the last 4 bans', 'syntax': '^7Usage: ^2!lastbans', 'level': 80, 'short': 'bans'},
'lookup': {'desc': 'search for a player in the database', 'syntax': '^7Usage: ^2!lookup ^7<name>', 'level': 80, 'short': 'l'},
'makereg': {'desc': 'make a player a regular (Level 2) user', 'syntax': '^7Usage: ^2!makereg ^7<name>', 'level': 80, 'short': 'mr'},
'map': {'desc': 'load given map', 'syntax': '^7Usage: ^2!map ^7<ut4_name>', 'level': 80},
'mapcycle': {'desc': 'list the map rotation', 'syntax': '^7Usage: ^2!mapcycle', 'level': 80},
'maps': {'desc': 'display all available maps', 'syntax': '^7Usage: ^2!maps', 'level': 80},
'maprestart': {'desc': 'restart the map', 'syntax': '^7Usage: ^2!maprestart', 'level': 80, 'short': 'restart'},
'moon': {'desc': 'activate low gravity mode (Moon mode)', 'syntax': '^7Usage: ^2!moon ^7<on/off>', 'level': 80, 'short': 'lowgravity'},
'permban': {'desc': 'ban a player permanent', 'syntax': '^7Usage: ^2!permban ^7<name> <reason>', 'level': 80, 'short': 'pb'},
'putgroup': {'desc': 'add a client to a group', 'syntax': '^7Usage: ^2!putgroup ^7<name> <group>', 'level': 80},
'rebuild': {'desc': 'sync up all available maps', 'syntax': '^7Usage: ^2!rebuild', 'level': 80},
'setgravity': {'desc': 'set the gravity (default: 800)', 'syntax': '^7Usage: ^2!setgravity ^7<value>', 'level': 80},
'setnextmap': {'desc': 'set the next map', 'syntax': '^7Usage: ^2!setnextmap ^7<ut4_name>', 'level': 80},
'swapteams': {'desc': 'swap the current teams', 'syntax': '^7Usage: ^2!swapteams', 'level': 80},
'unban': {'desc': 'unban a player from the database', 'syntax': '^7Usage: ^2!unban ^7<@ID>', 'level': 80},
'unreg': {'desc': 'remove a player from the regular group', 'syntax': '^7Usage: ^2!unreg ^7<name>', 'level': 80},
# superadmin commands, level 90
'bomb': {'desc': 'change gametype to Bomb', 'syntax': '^7Usage: ^2!bomb', 'level': 90},
'ctf': {'desc': 'change gametype to Capture the Flag', 'syntax': '^7Usage: ^2!ctf', 'level': 90},
'ffa': {'desc': 'change gametype to Free For All', 'syntax': '^7Usage: ^2!ffa', 'level': 90},
'gametype': {'desc': 'set game type', 'syntax': '^7Usage: ^2!gametype ^7<bomb/ctf/ffa/tdm/ts>', 'level': 90},
'gungame': {'desc': 'change gametype to Gun Game', 'syntax': '^7Usage: ^2!gungame', 'level': 90},
'jump': {'desc': 'change gametype to Jump', 'syntax': '^7Usage: ^2!jump', 'level': 90},
'lms': {'desc': 'change gametype to Last Man Standing', 'syntax': '^7Usage: ^2!lms', 'level': 90},
'tdm': {'desc': 'change gametype to Team Deathmatch', 'syntax': '^7Usage: ^2!tdm', 'level': 90},
'ts': {'desc': 'change gametype to Team Survivor', 'syntax': '^7Usage: ^2!ts', 'level': 90},
'ungroup': {'desc': 'remove admin level from a player', 'syntax': '^7Usage: ^2!ungroup ^7<name>', 'level': 90},
'password': {'desc': 'set private server password', 'syntax': '^7Usage: ^2!password ^7[<password>]', 'level': 90},
'reload': {'desc': 'reload map', 'syntax': '^7Usage: ^2!reload', 'level': 90}}
REASONS = {'obj': 'go for objective',
'camp': 'stop camping',
'spam': 'do not spam, shut-up!',
'lang': 'bad language',
'racism': 'racism is not tolerated',
'ping': 'fix your ping',
'afk': 'away from keyboard',
'tk': 'stop team killing',
'sk': 'stop spawn killing',
'spec': 'spectator too long on full server',
'score': 'score too low for this server',
'ci': 'connection interrupted',
'999': 'connection interrupted',
'whiner': 'stop complaining all the time',
'skill': 'skill too low for this server',
'name': 'do not use offensive names',
'wh': 'wallhack',
'insult': 'stop insulting',
'autojoin': 'use auto-join',
'abuse': 'stop abusing others',
'teams': 'keep the teams even'}
### CLASS Log Parser ###
class LogParser(object):
"""
log file parser
"""
def __init__(self):
"""
create a new instance of LogParser
"""
# hit zone support for UrT > 4.2.013
self.hit_points = {0: "HEAD", 1: "HEAD", 2: "HELMET", 3: "TORSO", 4: "VEST", 5: "LEFT_ARM", 6: "RIGHT_ARM",
7: "GROIN", 8: "BUTT", 9: "LEFT_UPPER_LEG", 10: "RIGHT_UPPER_LEG", 11: "LEFT_LOWER_LEG",
12: "RIGHT_LOWER_LEG", 13: "LEFT_FOOT", 14: "RIGHT_FOOT"}
self.hit_item = {1: "UT_MOD_KNIFE", 2: "UT_MOD_BERETTA", 3: "UT_MOD_DEAGLE", 4: "UT_MOD_SPAS", 5: "UT_MOD_MP5K",
6: "UT_MOD_UMP45", 8: "UT_MOD_LR300", 9: "UT_MOD_G36", 10: "UT_MOD_PSG1", 14: "UT_MOD_SR8",
15: "UT_MOD_AK103", 17: "UT_MOD_NEGEV", 19: "UT_MOD_M4", 20: "UT_MOD_GLOCK", 21: "UT_MOD_COLT1911",
22: "UT_MOD_MAC11", 23: "UT_MOD_BLED"}
self.death_cause = {1: "MOD_WATER", 3: "MOD_LAVA", 5: "UT_MOD_TELEFRAG", 6: "MOD_FALLING", 7: "UT_MOD_SUICIDE",
9: "MOD_TRIGGER_HURT", 10: "MOD_CHANGE_TEAM", 12: "UT_MOD_KNIFE", 13: "UT_MOD_KNIFE_THROWN",
14: "UT_MOD_BERETTA", 15: "UT_MOD_DEAGLE", 16: "UT_MOD_SPAS", 17: "UT_MOD_UMP45", 18: "UT_MOD_MP5K",
19: "UT_MOD_LR300", 20: "UT_MOD_G36", 21: "UT_MOD_PSG1", 22: "UT_MOD_HK69", 23: "UT_MOD_BLED",
24: "UT_MOD_KICKED", 25: "UT_MOD_HEGRENADE", 28: "UT_MOD_SR8", 30: "UT_MOD_AK103",
31: "UT_MOD_SPLODED", 32: "UT_MOD_SLAPPED", 33: "UT_MOD_SMITED", 34: "UT_MOD_BOMBED",
35: "UT_MOD_NUKED", 36: "UT_MOD_NEGEV", 37: "UT_MOD_HK69_HIT", 38: "UT_MOD_M4",
39: "UT_MOD_GLOCK", 40: "UT_MOD_COLT1911", 41: "UT_MOD_MAC11"}
# RCON commands for the different admin roles
self.user_cmds = []
self.mod_cmds = []
self.admin_cmds = []
self.fulladmin_cmds = []
self.senioradmin_cmds = []
self.superadmin_cmds = []
# dictionary of shortcut commands
self.shortcut_cmd = {}
for key, value in COMMANDS.iteritems():
if 'short' in value:
self.shortcut_cmd[value['short']] = key
if value['level'] == 20:
self.mod_cmds.append(key)
self.admin_cmds.append(key)
self.fulladmin_cmds.append(key)
self.senioradmin_cmds.append(key)
self.superadmin_cmds.append(key)
elif value['level'] == 40:
self.admin_cmds.append(key)
self.fulladmin_cmds.append(key)
self.senioradmin_cmds.append(key)
self.superadmin_cmds.append(key)
elif value['level'] == 60:
self.fulladmin_cmds.append(key)
self.senioradmin_cmds.append(key)
self.superadmin_cmds.append(key)
elif value['level'] == 80:
self.senioradmin_cmds.append(key)
self.superadmin_cmds.append(key)
elif value['level'] >= 90:
self.superadmin_cmds.append(key)
else:
self.user_cmds.append(key)
self.mod_cmds.append(key)
self.admin_cmds.append(key)
self.fulladmin_cmds.append(key)
self.senioradmin_cmds.append(key)
self.superadmin_cmds.append(key)
# alphabetic sort of the commands
self.user_cmds.sort()
self.mod_cmds.sort()
self.admin_cmds.sort()
self.fulladmin_cmds.sort()
self.senioradmin_cmds.sort()
self.superadmin_cmds.sort()
logger.info("Starting logging : OK")
games_log = CONFIG.get('server', 'log_file')
self.ffa_lms_gametype = False
self.ctf_gametype = False
self.ts_gametype = False
self.tdm_gametype = False
self.bomb_gametype = False
self.freeze_gametype = False
self.ts_do_team_balance = False
self.allow_cmd_teams = True
self.urt_modversion = None
self.game = None
self.players_lock = RLock()
self.firstblood = False
self.firstnadekill = False
self.firstknifekill = False
self.firstteamkill = False
self.last_disconnected_player = None
self.last_admin = None
self.allow_nextmap_vote = True
self.failed_vote_timer = 0
self.last_vote = ''
self.default_gear = ''
# enable/disable autokick for team killing
self.tk_autokick = CONFIG.getboolean('bot', 'teamkill_autokick') if CONFIG.has_option('bot', 'teamkill_autokick') else True
self.allow_tk_bots = CONFIG.getboolean('bot', 'allow_teamkill_bots') if CONFIG.has_option('bot', 'allow_teamkill_bots') else False
# enable/disable autokick of players with low score
self.noob_autokick = CONFIG.getboolean('bot', 'noob_autokick') if CONFIG.has_option('bot', 'noob_autokick') else False
self.spawnkill_autokick = CONFIG.getboolean('bot', 'spawnkill_autokick') if CONFIG.has_option('bot', 'spawnkill_autokick') else False
self.kill_spawnkiller = CONFIG.getboolean('bot', 'instant_kill_spawnkiller') if CONFIG.has_option('bot', 'instant_kill_spawnkiller') else False
self.spawnkill_warn_time = CONFIG.getint('bot', 'spawnkill_warn_time') if CONFIG.has_option('bot', 'spawnkill_warn_time') else 3
self.admin_immunity = CONFIG.getint('bot', 'admin_immunity') if CONFIG.has_option('bot', 'admin_immunity') else 40
# set the maximum allowed ping
self.max_ping = CONFIG.getint('bot', 'max_ping') if CONFIG.has_option('bot', 'max_ping') else 200
# kick spectator on full server
self.num_kick_specs = CONFIG.getint('bot', 'kick_spec_full_server') if CONFIG.has_option('bot', 'kick_spec_full_server') else 10
# set task frequency
self.task_frequency = CONFIG.getint('bot', 'task_frequency') if CONFIG.has_option('bot', 'task_frequency') else 60
self.warn_expiration = CONFIG.getint('bot', 'warn_expiration') if CONFIG.has_option('bot', 'warn_expiration') else 240
self.bad_words_autokick = CONFIG.getint('bot', 'bad_words_autokick') if CONFIG.has_option('bot', 'bad_words_autokick') else 0
# enable/disable message 'Player connected from...'
self.show_country_on_connect = CONFIG.getboolean('bot', 'show_country_on_connect') if CONFIG.has_option('bot', 'show_country_on_connect') else True
# enable/disable message 'Firstblood / first nade kill...'
self.show_first_kill_msg = CONFIG.getboolean('bot', 'show_first_kill') if CONFIG.has_option('bot', 'show_first_kill') else True
self.show_hit_stats_msg = CONFIG.getboolean('bot', 'show_hit_stats_respawn') if CONFIG.has_option('bot', 'show_hit_stats_respawn') else True
self.show_multikill_msg = CONFIG.getboolean('bot', 'show_multi_kill') if CONFIG.has_option('bot', 'show_multi_kill') else True
# set teams autobalancer
self.teams_autobalancer = CONFIG.getboolean('bot', 'autobalancer') if CONFIG.has_option('bot', 'autobalancer') else False
self.allow_cmd_teams_round_end = CONFIG.getboolean('bot', 'allow_teams_round_end') if CONFIG.has_option('bot', 'allow_teams_round_end') else False
self.limit_nextmap_votes = CONFIG.getboolean('bot', 'limit_nextmap_votes') if CONFIG.has_option('bot', 'limit_nextmap_votes') else False
self.vote_delay = CONFIG.getint('bot', 'vote_delay') if CONFIG.has_option('bot', 'vote_delay') else 0
self.spam_bomb_planted_msg = CONFIG.getboolean('bot', 'spam_bomb_planted') if CONFIG.has_option('bot', 'spam_bomb_planted') else False
self.kill_survived_opponents = CONFIG.getboolean('bot', 'kill_survived_opponents') if CONFIG.has_option('bot', 'kill_survived_opponents') else False
self.spam_knife_kills_msg = CONFIG.getboolean('bot', 'spam_knife_kills') if CONFIG.has_option('bot', 'spam_knife_kills') else False
self.spam_nade_kills_msg = CONFIG.getboolean('bot', 'spam_nade_kills') if CONFIG.has_option('bot', 'spam_nade_kills') else False
self.spam_headshot_hits_msg = CONFIG.getboolean('bot', 'spam_headshot_hits') if CONFIG.has_option('bot', 'spam_headshot_hits') else False
self.reset_headshot_hits_mapcycle = CONFIG.getboolean('bot', 'reset_headshot_hits_mapcycle') if CONFIG.has_option('bot', 'reset_headshot_hits_mapcycle') else True
self.reset_kill_spree_mapcycle = CONFIG.getboolean('bot', 'reset_kill_spree_mapcycle') if CONFIG.has_option('bot', 'reset_kill_spree_mapcycle') else True
ban_duration = CONFIG.getint('bot', 'ban_duration') if CONFIG.has_option('bot', 'ban_duration') else 7
self.ban_duration = ban_duration if ban_duration > 0 else 1
# support for low gravity server
self.support_lowgravity = CONFIG.getboolean('lowgrav', 'support_lowgravity') if CONFIG.has_option('lowgrav', 'support_lowgravity') else False
self.gravity = CONFIG.getint('lowgrav', 'gravity') if CONFIG.has_option('lowgrav', 'gravity') else 800
self.explode_time = "40"
# log that the configuration file has been loaded
logger.info("Configuration loaded : OK")
# enable/disable option to get Head Admin by checking existence of head admin in database
curs.execute("SELECT COUNT(*) FROM `xlrstats` WHERE `admin_role` = 100")
self.iamgod = True if int(curs.fetchone()[0]) < 1 else False
logger.info("Connecting to Database: OK")
logger.debug("Cmd !iamgod available : %s", self.iamgod)
self.uptime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
# Rotating Messages and Rules
if CONFIG.has_option('rules', 'show_rules') and CONFIG.getboolean('rules', 'show_rules'):
self.output_rules = CONFIG.get('rules', 'display') if CONFIG.has_option('rules', 'display') else "chat"
rules_frequency = CONFIG.getint('rules', 'rules_frequency') if CONFIG.has_option('rules', 'rules_frequency') else 90
self.rules_file = os.path.join(HOME, 'conf', 'rules.conf')
self.rules_frequency = rules_frequency if rules_frequency > 0 else 10
if os.path.isfile(self.rules_file):
self.thread_rotate()
logger.info("Load rotating messages: OK")
else:
logger.error("ERROR: Rotating messages will be ignored, file '%s' has not been found", self.rules_file)
# Parse Game log file
try:
# open game log file
self.log_file = open(games_log, 'r')
except IOError:
logger.error("ERROR: The Gamelog file '%s' has not been found", games_log)
logger.error("*** Aborting Spunky Bot ***")
else:
# go to the end of the file
self.log_file.seek(0, 2)
# start parsing the games logfile
logger.info("Parsing Gamelog file : %s", games_log)
self.read_log()
def thread_rotate(self):
"""
Thread process for starting method rotate_messages
"""
processor = Thread(target=self.rotating_messages)
processor.setDaemon(True)
processor.start()
def rotating_messages(self):
"""
display rotating messages and rules
"""
# initial wait
time.sleep(30)
while 1:
with open(self.rules_file, 'r') as filehandle:
rotation_msg = filehandle.readlines()
if not rotation_msg:
break
for line in rotation_msg:
# display rule
with self.players_lock:
if "@admins" in line:
self.game.rcon_say(self.get_admins_online())
elif "@admincount" in line:
self.game.rcon_say(self.get_admin_count())
elif "@nextmap" in line:
self.game.rcon_say(self.get_nextmap())
elif "@time" in line:
self.game.rcon_say("^7Time: %s" % time.strftime("%H:%M", time.localtime(time.time())))
elif "@bigtext" in line:
self.game.rcon_bigtext("^7%s" % line.split('@bigtext')[-1].strip())
else:
if self.output_rules == 'chat':
self.game.rcon_say("^2%s" % line.strip())
elif self.output_rules == 'bigtext':
self.game.rcon_bigtext("^2%s" % line.strip())
else:
self.game.send_rcon("^2%s" % line.strip())
# wait for given delay in the config file
time.sleep(self.rules_frequency)
def find_game_start(self):
"""
find InitGame start
"""
seek_amount = 768
# search within the specified range for the InitGame message
start_pos = self.log_file.tell() - seek_amount
end_pos = start_pos + seek_amount
try:
self.log_file.seek(start_pos)
except IOError:
logger.error("ERROR: The games.log file is empty, ignoring game type and start")
# go to the end of the file
self.log_file.seek(0, 2)
game_start = True
else:
game_start = False
while not game_start:
while self.log_file:
line = self.log_file.readline()
tmp = line.split()
if len(tmp) > 1 and tmp[1] == "InitGame:":
game_start = True
if 'g_modversion\\4.3' in line:
self.hit_item.update({23: "UT_MOD_FRF1", 24: "UT_MOD_BENELLI", 25: "UT_MOD_P90",
26: "UT_MOD_MAGNUM", 29: "UT_MOD_KICKED", 30: "UT_MOD_KNIFE_THROWN"})
self.death_cause.update({42: "UT_MOD_FRF1", 43: "UT_MOD_BENELLI", 44: "UT_MOD_P90", 45: "UT_MOD_MAGNUM",
46: "UT_MOD_TOD50", 47: "UT_MOD_FLAG", 48: "UT_MOD_GOOMBA"})
self.urt_modversion = 43
logger.info("Game modversion : 4.3")
elif 'g_modversion\\4.2' in line:
self.hit_item.update({23: "UT_MOD_BLED", 24: "UT_MOD_KICKED", 25: "UT_MOD_KNIFE_THROWN"})
self.death_cause.update({42: "UT_MOD_FLAG", 43: "UT_MOD_GOOMBA"})
self.urt_modversion = 42
logger.info("Game modversion : 4.2")
elif 'g_modversion\\4.1' in line:
# hit zone support for UrT 4.1
self.hit_points = {0: "HEAD", 1: "HELMET", 2: "TORSO", 3: "KEVLAR", 4: "ARMS", 5: "LEGS", 6: "BODY"}
self.hit_item.update({21: "UT_MOD_KICKED", 22: "UT_MOD_KNIFE_THROWN"})
self.death_cause.update({33: "UT_MOD_BOMBED", 34: "UT_MOD_NUKED", 35: "UT_MOD_NEGEV",
39: "UT_MOD_FLAG", 40: "UT_MOD_GOOMBA"})
self.urt_modversion = 41
logger.info("Game modversion : 4.1")
if 'g_gametype\\0\\' in line or 'g_gametype\\1\\' in line or 'g_gametype\\9\\' in line or 'g_gametype\\11\\' in line:
# disable teamkill event and some commands for FFA (0), LMS (1), Jump (9), Gun (11)
self.ffa_lms_gametype = True
elif 'g_gametype\\7\\' in line:
self.ctf_gametype = True
elif 'g_gametype\\4\\' in line or 'g_gametype\\5\\' in line:
self.ts_gametype = True
elif 'g_gametype\\3\\' in line:
self.tdm_gametype = True
elif 'g_gametype\\8\\' in line:
self.bomb_gametype = True
elif 'g_gametype\\10\\' in line:
self.freeze_gametype = True
# get default g_gear value
self.default_gear = line.split('g_gear\\')[-1].split('\\')[0] if 'g_gear\\' in line else "%s" % '' if self.urt_modversion > 41 else '0'
if self.log_file.tell() > end_pos:
break
elif not line:
break
if self.log_file.tell() < seek_amount:
self.log_file.seek(0, 0)
else:
cur_pos = start_pos - seek_amount
end_pos = start_pos
start_pos = cur_pos
start_pos = max(start_pos, 0)
self.log_file.seek(start_pos)
def read_log(self):
"""
read the logfile
"""
if self.task_frequency > 0:
# schedule the task
if self.task_frequency < 10:
# avoid flooding with too less delay
schedule.every(10).seconds.do(self.taskmanager)
else:
schedule.every(self.task_frequency).seconds.do(self.taskmanager)
# schedule the task
schedule.every(2).hours.do(self.remove_expired_db_entries)
self.find_game_start()
# create instance of Game
self.game = Game(self.urt_modversion)
self.log_file.seek(0, 2)
while self.log_file:
schedule.run_pending()
line = self.log_file.readline()
if line:
self.parse_line(line)
else:
if not self.game.live:
self.game.go_live()
time.sleep(.125)
def remove_expired_db_entries(self):
"""
delete expired ban points
"""
# remove expired ban_points
curs.execute("DELETE FROM `ban_points` WHERE `expires` < '{}'".format(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))))
conn.commit()
def taskmanager(self):
"""
- check warnings and kick players with too many warnings
- check for spectators and set warning
- check for players with low score and set warning
"""
try:
with self.players_lock:
# get number of connected players
counter = self.game.get_number_players()
# check amount of warnings and kick player if needed
for player in self.game.players.itervalues():
player_num = player.get_player_num()
if player_num == BOT_PLAYER_NUM:
continue
player_name = player.get_name()
player_admin_role = player.get_admin_role()
# clear expired warnings
if self.warn_expiration > 0 and player.get_warning() > 0 and player.get_last_warn_time() and player.get_last_warn_time() + self.warn_expiration < time.time():
player.clear_warning()
# kick player with 3 or more warnings, Admins will never get kicked
if player.get_warning() > 2 and player_admin_role < 40:
if 'spectator' in player.get_last_warn_msg():
kick_msg = reason = "spectator too long on full server"
elif 'ping' in player.get_last_warn_msg():
kick_msg = "ping too high for this server ^7[^4%s^7]" % player.get_ping_value()
reason = "fix your ping"
elif 'score' in player.get_last_warn_msg():
kick_msg = reason = "score too low for this server"
elif 'team killing' in player.get_last_warn_msg():
kick_msg = reason = "team killing over limit"
player.add_ban_point('auto-kick for team killing', 600)
else:
kick_msg = reason = "too many warnings"
self.game.rcon_say("^2%s ^7was kicked, %s" % (player_name, kick_msg))
self.game.kick_player(player_num, reason=reason)
continue
# check for spectators and set warning
if self.num_kick_specs > 0 and player_admin_role < 20:
# ignore player with name prefix GTV-
if 'GTV-' in player_name:
continue
# if player is spectator on full server, inform player and increase warn counter
# GTV or Moderator or higher levels will not get the warning
elif counter > self.num_kick_specs and player.get_team() == 3 and player.get_time_joined() < (time.time() - 30):
player.add_warning(warning='spectator too long on full server', timer=False)
logger.debug("%s is spectator too long on full server", player_name)
warnmsg = "^1WARNING ^7[^3%d^7]: You are spectator too long on full server" % player.get_warning()
self.game.rcon_tell(player_num, warnmsg, False)
# reset spec warning
else:
player.clear_specific_warning('spectator too long on full server')
# check for players with low score and set warning
if self.noob_autokick and player_admin_role < 2 and player.get_ip_address() != '0.0.0.0':
kills = player.get_kills()
deaths = player.get_deaths()
ratio = round(float(kills) / float(deaths), 2) if deaths > 0 else 1.0
# if player ratio is too low, inform player and increase warn counter
# Regulars or higher levels will not get the warning
if kills > 0 and ratio < 0.33:
player.add_warning(warning='score too low for this server', timer=False)
logger.debug("Score of %s is too low, ratio: %s", player_name, ratio)
warnmsg = "^1WARNING ^7[^3%d^7]: Your score is too low for this server" % player.get_warning()
self.game.rcon_tell(player_num, warnmsg, False)
else:
player.clear_specific_warning('score too low for this server')
# warn player with 3 warnings, Admins will never get the alert warning
if player.get_warning() == 3 and player_admin_role < 40:
self.game.rcon_say("^1ALERT: ^2%s ^7auto-kick from warnings if not cleared" % player_name)
# check for player with high ping
self.check_player_ping()
except Exception as err:
logger.error(err, exc_info=True)
def check_player_ping(self):
"""
check ping of all players and set warning for high ping user
"""
if self.max_ping > 0:
# rcon update status
self.game.quake.rcon_update()
for player in self.game.quake.players or []:
# if ping is too high, increase warn counter, Admins or higher levels will not get the warning
try:
ping_value = player.ping
gameplayer = self.game.players[player.num]
except KeyError:
continue
else:
if self.max_ping < ping_value < 999 and gameplayer.get_admin_role() < self.admin_immunity:
gameplayer.add_high_ping(ping_value)
self.game.rcon_tell(player.num, "^1WARNING ^7[^3%d^7]: Your ping is too high [^4%d^7]. ^3The maximum allowed ping is %d." % (gameplayer.get_warning(), ping_value, self.max_ping), False)
else:
gameplayer.clear_specific_warning('fix your ping')
def parse_line(self, string):
"""
parse the logfile and search for specific action
"""
line = string[7:]
tmp = line.split(":", 1)
line = tmp[1].strip() if len(tmp) > 1 else tmp[0].strip()
option = {'InitGame': self.new_game, 'Warmup': self.handle_warmup, 'InitRound': self.handle_initround,
'Exit': self.handle_exit, 'say': self.handle_say, 'sayteam': self.handle_say, 'saytell': self.handle_saytell,
'ClientUserinfo': self.handle_userinfo, 'ClientUserinfoChanged': self.handle_userinfo_changed,
'ClientBegin': self.handle_begin, 'ClientDisconnect': self.handle_disconnect,
'SurvivorWinner': self.handle_teams_ts_mode, 'Kill': self.handle_kill, 'Hit': self.handle_hit,
'Freeze': self.handle_freeze, 'ThawOutFinished': self.handle_thawout, 'ClientSpawn': self.handle_spawn,
'Flag': self.handle_flag, 'FlagCaptureTime': self.handle_flagcapturetime,
'VotePassed': self.handle_vote_passed, 'VoteFailed': self.handle_vote_failed, 'Callvote': self.handle_callvote}
try:
action = tmp[0].strip()
if action in option:
option[action](line)
elif 'Bomb' in action:
self.handle_bomb(line)
elif 'Pop' in action:
self.handle_bomb_exploded()
except (IndexError, KeyError):
pass
except Exception as err:
logger.error(err, exc_info=True)
def explode_line(self, line):
"""
explode line
"""
arr = line.lstrip().lstrip('\\').split('\\')
key = True
key_val = None
values = {}
for item in arr:
if key:
key_val = item
key = False
else:
values[key_val.rstrip()] = item.rstrip()
key_val = None
key = True
return values
def handle_vote_passed(self, line):
"""
handle vote passed
"""
# nextmap vote
if "g_nextmap" in line:
self.game.next_mapname = line.split("g_nextmap")[-1].strip('"').strip()
self.game.rcon_say("^7Vote to set next map to '%s' ^2passed" % self.game.next_mapname)
self.allow_nextmap_vote = False
# cyclemap vote
elif "cyclemap" in line:
self.game.rcon_say("^7Vote to cycle map ^2passed")
# kick vote
elif "clientkickreason" in line:
self.game.rcon_say("^7Vote to kick %s ^2passed" % self.game.players[int(line.split('"clientkickreason "')[-1].strip('"'))].get_name())
def handle_vote_failed(self, line):
"""
handle vote failed
"""
# nextmap vote
if "g_nextmap" in line:
self.game.rcon_say("^7Vote to set next map to '%s' ^1failed" % line.split("g_nextmap")[-1].strip('"').strip())
if self.vote_delay:
self.failed_vote_timer = time.time() + self.vote_delay
# cyclemap vote
elif "cyclemap" in line:
self.game.rcon_say("^7Vote to cycle map ^1failed")
# kick vote
elif "clientkickreason" in line:
self.game.rcon_say("^7Vote to kick %s ^1failed" % self.game.players[int(line.split('"clientkickreason "')[-1].strip('"'))].get_name())
def handle_callvote(self, line):
"""
handle callvote
"""
if "g_nextmap" in line:
self.last_vote = "nextmap"
elif "cyclemap" in line:
self.last_vote = "cyclemap"
elif "clientkickreason" in line:
self.last_vote = "kick"
spam_msg = True
now = time.time()
if "g_nextmap" in line and self.limit_nextmap_votes and not self.allow_nextmap_vote:
self.game.send_rcon('veto')
self.game.rcon_say("^7Voting for Next Map is disabled until the end of this map")
spam_msg = False
if "map" in line and self.failed_vote_timer > now:
remaining_time = int(self.failed_vote_timer - now)
self.game.send_rcon('veto')
self.game.rcon_say("^7Map voting is disabled for ^2%d ^7seconds" % remaining_time)
if spam_msg:
self.game.rcon_bigtext("^7Press ^2F1 ^7or ^1F2 ^7to vote!")
if self.game.get_last_maps() and ('"g_nextmap' in line or '"map' in line):
self.game.rcon_say("^7Last Maps: ^3%s" % ", ".join(self.game.get_last_maps()))
def new_game(self, line):
"""
set-up a new game
"""
self.ffa_lms_gametype = True if ('g_gametype\\0\\' in line or 'g_gametype\\1\\' in line or 'g_gametype\\9\\' in line or 'g_gametype\\11\\' in line) else False
self.ctf_gametype = True if 'g_gametype\\7\\' in line else False
self.ts_gametype = True if ('g_gametype\\4\\' in line or 'g_gametype\\5\\' in line) else False
self.tdm_gametype = True if 'g_gametype\\3\\' in line else False
self.bomb_gametype = True if 'g_gametype\\8\\' in line else False
self.freeze_gametype = True if 'g_gametype\\10\\' in line else False
logger.debug("InitGame: Starting game...")
self.game.rcon_clear()
# reset the player stats
self.stats_reset()
# set the current map
self.game.set_current_map()
# load all available maps
self.game.set_all_maps()
# support for low gravity server
if self.support_lowgravity:
self.game.send_rcon("set g_gravity %d" % self.gravity)
# detonation timer
if self.bomb_gametype:
# bomb detonation timer
detonation_timer = self.game.get_cvar('g_bombexplodetime')
self.explode_time = detonation_timer or "40"
# reset list of player who left server
self.last_disconnected_player = None
# allow nextmap votes
self.allow_nextmap_vote = True
self.failed_vote_timer = 0
def handle_spawn(self, line):
"""
handle client spawn
"""
player_num = int(line)
with self.players_lock:
self.game.players[player_num].set_alive(True)
def handle_flagcapturetime(self, line):
"""
handle flag capture time
"""
tmp = line.split(": ", 1)
player_num = int(tmp[0])
action = tmp[1]
if action.isdigit():
cap_time = round(float(action) / 1000, 2)
logger.debug("Player %d captured the flag in %s seconds", player_num, cap_time)
with self.players_lock:
self.game.players[player_num].set_flag_capture_time(cap_time)
def handle_warmup(self, line):
"""
handle warmup
"""
logger.debug("Warmup... %s", line)
self.allow_cmd_teams = True
def handle_initround(self, _):
"""
handle Init Round
"""
logger.debug("InitRound: Round started...")
if self.ctf_gametype:
with self.players_lock:
for player in self.game.players.itervalues():
player.reset_flag_stats()
elif self.ts_gametype or self.bomb_gametype or self.freeze_gametype:
if self.allow_cmd_teams_round_end:
self.allow_cmd_teams = False
def handle_exit(self, line):
"""
handle Exit of a match, show Awards, store user score in database and reset statistics
"""
logger.debug("Exit: %s", line)
self.handle_awards()
self.allow_cmd_teams = True
self.stats_reset(store_score=True)
def stats_reset(self, store_score=False):
"""
store user score in database if needed and reset the player statistics
"""
with self.players_lock:
for player in self.game.players.itervalues():
if store_score:
# store score in database
player.save_info()
# reset player statistics
player.reset(self.reset_headshot_hits_mapcycle, self.reset_kill_spree_mapcycle)
# reset team lock
player.set_team_lock(None)
# set first kill trigger
if self.show_first_kill_msg and not self.ffa_lms_gametype:
self.firstblood = True
self.firstnadekill = True
self.firstknifekill = True
self.firstteamkill = True
else:
self.firstblood = False
self.firstnadekill = False
self.firstknifekill = False
self.firstteamkill = False
def handle_userinfo(self, line):
"""
handle player user information, auto-kick known cheater ports or guids
"""
with self.players_lock:
player_num = int(line[:2].strip())
line = line[2:].lstrip("\\").lstrip()
values = self.explode_line(line)
challenge = 'challenge' in values
name = values['name'] if 'name' in values else "UnnamedPlayer"
ip_port = values['ip'] if 'ip' in values else "0.0.0.0:0"
auth = values['authl'] if 'authl' in values else ""
if 'cl_guid' in values:
guid = values['cl_guid']
elif 'skill' in values:
# bot connecting
guid = "BOT%d" % player_num
else:
guid = "None"
self.kick_player_reason(reason="Player with invalid GUID kicked", player_num=player_num)
try:
ip_address = ip_port.split(":")[0].strip()
port = ip_port.split(":")[1].strip()
except IndexError:
ip_address = ip_port.strip()
port = "27960"
# convert loopback/localhost address
if ip_address in ('loopback', 'localhost'):
ip_address = '127.0.0.1'
if player_num not in self.game.players:
player = Player(player_num, ip_address, guid, name, auth)
self.game.add_player(player)
# kick banned player
if player.get_ban_id():
self.kick_player_reason("^7%s ^1banned ^7(ID @%s): %s" % (player.get_name(), player.get_ban_id(), player.get_ban_msg()), player_num)
else:
if self.show_country_on_connect and player.get_country():
self.game.rcon_say("^7%s ^7connected from %s" % (player.get_name(), player.get_country()))
if self.game.players[player_num].get_guid() != guid:
self.game.players[player_num].set_guid(guid)
if self.game.players[player_num].get_authname() != auth:
self.game.players[player_num].set_authname(auth)
# kick player with hax guid 'kemfew'
if "KEMFEW" in guid.upper():
self.kick_player_reason("Cheater GUID detected for %s -> Player kicked" % name, player_num)
if "WORLD" in guid.upper() or "UNKNOWN" in guid.upper():
self.kick_player_reason("Invalid GUID detected for %s -> Player kicked" % name, player_num)
if challenge:
logger.debug("ClientUserinfo: Player %d %s is challenging the server and has the guid %s", player_num, self.game.players[player_num].get_name(), guid)
# kick player with hax port 1337
invalid_port_range = ["1337"]
if port in invalid_port_range:
self.kick_player_reason("Cheater Port detected for %s -> Player kicked" % name, player_num)
if self.last_disconnected_player and self.last_disconnected_player.get_guid() == self.game.players[player_num].get_guid():
self.last_disconnected_player = None
def kick_player_reason(self, reason, player_num):
"""
kick player for specific reason
"""
if self.urt_modversion > 41:
self.game.send_rcon('kick %d "%s"' % (player_num, reason))
else:
self.game.send_rcon("kick %d" % player_num)
self.game.send_rcon(reason)
def handle_userinfo_changed(self, line):
"""
handle player changes
"""
with self.players_lock:
player_num = int(line[:2].strip())
player = self.game.players[player_num]
line = line[2:].lstrip("\\")
try:
values = self.explode_line(line)
team_num = int(values['t'])
player.set_team(team_num)
name = values['n']
except KeyError:
team_num = 3
player.set_team(team_num)
name = self.game.players[player_num].get_name()
# set new name, if player changed name
if self.game.players[player_num].get_name() != name:
self.game.players[player_num].set_name(name)
# move locked player to the defined team, if player tries to change teams
team_lock = self.game.players[player_num].get_team_lock()
if team_lock and Player.teams[team_num] != team_lock:
self.game.rcon_forceteam(player_num, team_lock)
self.game.rcon_tell(player_num, "^3You are forced to: ^7%s" % team_lock)
logger.debug("ClientUserinfoChanged: Player %d %s joined team %s", player_num, name, Player.teams[team_num])
def handle_begin(self, line):
"""
handle player entering game
"""
with self.players_lock:
player_num = int(line)
player = self.game.players[player_num]
player_name = player.get_name()
player_auth = player.get_authname()
player_name = "%s [^5%s^7]" % (player_name, player_auth) if player_auth else player_name
player_id = player.get_player_id()
# Welcome message for registered players
if player.get_registered_user() and player.get_welcome_msg():
self.game.rcon_say("^3Everyone welcome back ^7%s^3, player number ^7#%s^3, to this server" % (player_name, player_id))
self.game.rcon_tell(player_num, "^7[^2Authed^7] Welcome back %s, you are ^2%s^7, last visit %s, you played %s times" % (player_name, player.roles[player.get_admin_role()], player.get_last_visit(), player.get_num_played()), False)
# disable welcome message for next rounds
player.disable_welcome_msg()
elif not player.get_registered_user() and not player.get_first_time() and player.get_welcome_msg():
self.game.rcon_tell(player_num, "^7Welcome back %s, you are player ^3#%s^7. ^3Type ^2!register ^3in chat to register and save your stats" % (player_name, player_id))
player.disable_welcome_msg()
elif player.get_first_time() and player.get_welcome_msg():
self.game.rcon_tell(player_num, "^7Welcome %s, this must be your first visit, you are player ^3#%s^7. ^3Type ^2!help ^3in chat for help" % (player_name, player_id))
player.disable_welcome_msg()
logger.debug("ClientBegin: Player %d %s has entered the game", player_num, player_name)
def handle_disconnect(self, line):
"""
handle player disconnect
"""
with self.players_lock:
player_num = int(line)
player = self.game.players[player_num]
player_name = player.get_name()
player.save_info()
player.reset()
self.last_disconnected_player = player
if player.get_admin_role() >= 40:
self.last_admin = player
del self.game.players[player_num]
for player in self.game.players.itervalues():
player.clear_tk(player_num)
player.clear_grudged_player(player_num)
logger.debug("ClientDisconnect: Player %d %s has left the game", player_num, player_name)
def handle_hit(self, line):
"""
handle all kind of hits
"""
with self.players_lock:
info = line.split(":", 1)[0].split()
hitter_id = int(info[1])
victim_id = int(info[0])
hitter = self.game.players[hitter_id]