-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathplugin.py
1177 lines (904 loc) · 45.5 KB
/
plugin.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
###
# Copyright (c) 2012, Matthias Meusburger
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions, and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions, and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the author of this software nor the name of
# contributors to this software may be used to endorse or promote products
# derived from this software without specific prior written consent.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
###
from supybot.commands import *
import supybot.plugins as plugins
import supybot.callbacks as callbacks
import supybot.schedule as schedule
import supybot.ircdb as ircdb
import supybot.ircmsgs as ircmsgs
import supybot.log as log
import supybot.conf as conf
import threading, random, pickle, os, time, datetime
class DuckHunt(callbacks.Plugin):
"""
A DuckHunt game for supybot. Use the "start" command to start a game.
The bot will randomly launch ducks. Whenever a duck is launched, the first
person to use the "bang" command wins a point. Using the "bang" command
when there is no duck launched costs a point.
"""
threaded = True
# Those parameters are per-channel parameters
started = {} # Has the hunt started?
duck = {} # Is there currently a duck to shoot?
shoots = {} # Number of successfull shoots in a hunt
scores = {} # Scores for the current hunt
times = {} # Elapsed time since the last duck was launched
channelscores = {} # Saved scores for the channel
toptimes = {} # Times for the current hunt
channeltimes = {} # Saved times for the channel
worsttimes = {} # Worst times for the current hunt
channelworsttimes = {} # Saved worst times for the channel
averagetime = {} # Average shooting time for the current hunt
fridayMode = {} # Are we on friday mode? (automatic)
manualFriday = {} # Are we on friday mode? (manual)
missprobability = {} # Probability to miss a duck when shooting
week = {} # Scores for the week
channelweek = {} # Saved scores for the week
leader = {} # Who is the leader for the week?
reloading = {} # Who is currently reloading?
reloadtime = {} # Time to reload after shooting (in seconds)
# Does a duck needs to be launched?
lastSpoke = {}
minthrottle = {}
maxthrottle = {}
throttle = {}
# Where to save scores?
fileprefix = "DuckHunt_"
path = conf.supybot.directories.data
# Enable the 'dbg' command, which launch a duck, if true
debug = 0
# Other params
perfectbonus = 5 # How many extra-points are given when someones does a perfect hunt?
toplist = 5 # How many high{scores|times} are displayed by default?
dow = int(time.strftime("%u")) # Day of week
woy = int(time.strftime("%V")) # Week of year
year = time.strftime("%Y")
dayname = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Caturday', 'Saturday', 'Sunday']
def _calc_scores(self, channel):
"""
Adds new scores and times to the already saved ones
"""
# scores
# Adding current scores to the channel scores
for player in list(self.scores[channel].keys()):
if not player in self.channelscores[channel]:
# It's a new player
self.channelscores[channel][player] = self.scores[channel][player]
else:
# It's a player that already has a saved score
self.channelscores[channel][player] += self.scores[channel][player]
# times
# Adding times scores to the channel scores
for player in list(self.toptimes[channel].keys()):
if not player in self.channeltimes[channel]:
# It's a new player
self.channeltimes[channel][player] = self.toptimes[channel][player]
else:
# It's a player that already has a saved score
# And we save the time of the current hunt if it's better than it's previous time
if(self.toptimes[channel][player] < self.channeltimes[channel][player]):
self.channeltimes[channel][player] = self.toptimes[channel][player]
# worst times
# Adding worst times scores to the channel scores
for player in list(self.worsttimes[channel].keys()):
if not player in self.channelworsttimes[channel]:
# It's a new player
self.channelworsttimes[channel][player] = self.worsttimes[channel][player]
else:
# It's a player that already has a saved score
# And we save the time of the current hunt if it's worst than it's previous time
if(self.worsttimes[channel][player] > self.channelworsttimes[channel][player]):
self.channelworsttimes[channel][player] = self.worsttimes[channel][player]
# week scores
for player in list(self.scores[channel].keys()):
#FIXME: If the hunt starts a day and ends the day after, this will produce an error:
if not player in self.channelweek[channel][self.woy][self.dow]:
# It's a new player
self.channelweek[channel][self.woy][self.dow][player] = self.scores[channel][player]
else:
# It's a player that already has a saved score
self.channelweek[channel][self.woy][self.dow][player] += self.scores[channel][player]
def _write_scores(self, channel):
"""
Write scores and times to the disk
"""
# scores
outputfile = open(self.path.dirize(self.fileprefix + channel + ".scores"), "wb")
pickle.dump(self.channelscores[channel], outputfile)
outputfile.close()
# times
outputfile = open(self.path.dirize(self.fileprefix + channel + ".times"), "wb")
pickle.dump(self.channeltimes[channel], outputfile)
outputfile.close()
# worst times
outputfile = open(self.path.dirize(self.fileprefix + channel + ".worsttimes"), "wb")
pickle.dump(self.channelworsttimes[channel], outputfile)
outputfile.close()
# week scores
outputfile = open(self.path.dirize(self.fileprefix + channel + self.year + ".weekscores"), "wb")
pickle.dump(self.channelweek[channel], outputfile)
outputfile.close()
def _read_scores(self, channel):
"""
Reads scores and times from disk
"""
filename = self.path.dirize(self.fileprefix + channel)
# scores
if not self.channelscores.get(channel):
if os.path.isfile(filename + ".scores"):
inputfile = open(filename + ".scores", "rb")
self.channelscores[channel] = pickle.load(inputfile)
inputfile.close()
# times
if not self.channeltimes.get(channel):
if os.path.isfile(filename + ".times"):
inputfile = open(filename + ".times", "rb")
self.channeltimes[channel] = pickle.load(inputfile)
inputfile.close()
# worst times
if not self.channelworsttimes.get(channel):
if os.path.isfile(filename + ".worsttimes"):
inputfile = open(filename + ".worsttimes", "rb")
self.channelworsttimes[channel] = pickle.load(inputfile)
inputfile.close()
# week scores
if not self.channelweek.get(channel):
if os.path.isfile(filename + self.year + ".weekscores"):
inputfile = open(filename + self.year + ".weekscores", "rb")
self.channelweek[channel] = pickle.load(inputfile)
inputfile.close()
def _initdayweekyear(self, channel):
self.dow = int(time.strftime("%u")) # Day of week
self.woy = int(time.strftime("%V")) # Week of year
year = time.strftime("%Y")
# Init week scores
try:
self.channelweek[channel]
except:
self.channelweek[channel] = {}
try:
self.channelweek[channel][self.woy]
except:
self.channelweek[channel][self.woy] = {}
try:
self.channelweek[channel][self.woy][self.dow]
except:
self.channelweek[channel][self.woy][self.dow] = {}
def _initthrottle(self, irc, msg, args, channel):
self._initdayweekyear(channel)
if not self.leader.get(channel):
self.leader[channel] = None
# autoFriday?
if (not self.fridayMode.get(channel)):
self.fridayMode[channel] = False
if (not self.manualFriday.get(channel)):
self.manualFriday[channel] = False
if self.registryValue('autoFriday', channel) == True:
if int(time.strftime("%w")) == 5 and int(time.strftime("%H")) > 8 and int(time.strftime("%H")) < 17:
self.fridayMode[channel] = True
else:
self.fridayMode[channel] = False
# Miss probability
if self.registryValue('missProbability', channel):
self.missprobability[channel] = self.registryValue('missProbability', channel)
else:
self.missprobability[channel] = 0.2
# Reload time
if self.registryValue('reloadTime', channel):
self.reloadtime[channel] = self.registryValue('reloadTime', channel)
else:
self.reloadtime[channel] = 5
if self.fridayMode[channel] == False and self.manualFriday[channel] == False:
# Init min throttle[currentChannel] and max throttle[currentChannel]
if self.registryValue('minthrottle', channel):
self.minthrottle[channel] = self.registryValue('minthrottle', channel)
else:
self.minthrottle[channel] = 30
if self.registryValue('maxthrottle', channel):
self.maxthrottle[channel] = self.registryValue('maxthrottle', channel)
else:
self.maxthrottle[channel] = 300
else:
self.minthrottle[channel] = 3
self.maxthrottle[channel] = 60
self.throttle[channel] = random.randint(self.minthrottle[channel], self.maxthrottle[channel])
def start(self, irc, msg, args):
"""
Starts the hunt
"""
currentChannel = msg.args[0]
if irc.isChannel(currentChannel):
if(self.started.get(currentChannel) == True):
irc.reply("There is already a hunt right now!")
else:
# First of all, let's read the score if needed
self._read_scores(currentChannel)
self._initthrottle(irc, msg, args, currentChannel)
# Init saved scores
try:
self.channelscores[currentChannel]
except:
self.channelscores[currentChannel] = {}
# Init saved times
try:
self.channeltimes[currentChannel]
except:
self.channeltimes[currentChannel] = {}
# Init saved times
try:
self.channelworsttimes[currentChannel]
except:
self.channelworsttimes[currentChannel] = {}
# Init times
self.toptimes[currentChannel] = {}
self.worsttimes[currentChannel] = {}
# Init bangdelay
self.times[currentChannel] = False
# Init lastSpoke
self.lastSpoke[currentChannel] = time.time()
# Reinit current hunt scores
if self.scores.get(currentChannel):
self.scores[currentChannel] = {}
# Reinit reloading
self.reloading[currentChannel] = {}
# No duck launched
self.duck[currentChannel] = False
# Hunt started
self.started[currentChannel] = True
# Init shoots
self.shoots[currentChannel] = 0
# Init averagetime
self.averagetime[currentChannel] = 0;
# Init schedule
# First of all, stop the scheduler if it was still running
try:
schedule.removeEvent('DuckHunt_' + currentChannel)
except KeyError:
pass
# Then restart it
def myEventCaller():
self._launchEvent(irc, msg)
try:
schedule.addPeriodicEvent(myEventCaller, 5, 'DuckHunt_' + currentChannel, False)
except AssertionError:
pass
irc.reply("The hunt starts now!")
else:
irc.error('You have to be on a channel')
start = wrap(start)
def _launchEvent(self, irc, msg):
currentChannel = msg.args[0]
now = time.time()
if irc.isChannel(currentChannel):
if(self.started.get(currentChannel) == True):
if (self.duck[currentChannel] == False):
if now > self.lastSpoke[currentChannel] + self.throttle[currentChannel]:
self._launch(irc, msg, '')
def stop(self, irc, msg, args):
"""
Stops the current hunt
"""
currentChannel = msg.args[0]
if irc.isChannel(currentChannel):
if (self.started.get(currentChannel) == True):
self._end(irc, msg, args)
# If someone uses the stop command,
# we stop the scheduler, even if autoRestart is enabled
try:
schedule.removeEvent('DuckHunt_' + currentChannel)
except KeyError:
irc.reply('Error: the spammer wasn\'t running! This is a bug.')
else:
irc.reply('Nothing to stop: there\'s no hunt right now.')
else:
irc.error('You have to be on a channel')
stop = wrap(stop)
def fridaymode(self, irc, msg, args, channel, status):
"""
[<status>]
Enable/disable friday mode! (there are lots of ducks on friday :))
"""
if irc.isChannel(channel):
if (status == 'status'):
irc.reply('Manual friday mode for ' + channel + ' is ' + str(self.manualFriday.get(channel)));
irc.reply('Auto friday mode for ' + channel + ' is ' + str(self.fridayMode.get(channel)));
else:
if (self.manualFriday.get(channel) == None or self.manualFriday[channel] == False):
self.manualFriday[channel] = True
irc.reply("Friday mode is now enabled! Shoot alllllllllllll the ducks!")
else:
self.manualFriday[channel] = False
irc.reply("Friday mode is now disabled.")
self._initthrottle(irc, msg, args, channel)
else:
irc.error('You have to be on a channel')
fridaymode = wrap(fridaymode, ['channel', 'admin', optional('anything')])
def launched(self, irc, msg, args):
"""
Is there a duck right now?
"""
currentChannel = msg.args[0]
if irc.isChannel(currentChannel):
if(self.started.get(currentChannel) == True):
if(self.duck[currentChannel] == True):
irc.reply("There is currently a duck! You can shoot it with the 'bang' command")
else:
irc.reply("There is no duck right now! Wait for one to be launched!")
else:
irc.reply("There is no hunt right now! You can start a hunt with the 'start' command")
else:
irc.error('You have to be on a channel')
launched = wrap(launched)
def score(self, irc, msg, args, nick):
"""
<nick>
Shows the score for a given nick
"""
currentChannel = msg.args[0]
if irc.isChannel(currentChannel):
self._read_scores(currentChannel)
try:
self.channelscores[currentChannel]
except:
self.channelscores[currentChannel] = {}
try:
irc.reply(self.channelscores[currentChannel][nick])
except:
irc.reply("There is no score for %s on %s" % (nick, currentChannel))
else:
irc.error('You have to be on a channel')
score = wrap(score, ['nick'])
def mergescores(self, irc, msg, args, channel, nickto, nickfrom):
"""
[<channel>] <nickto> <nickfrom>
nickto gets the points of nickfrom and nickfrom is removed from the scorelist
"""
if irc.isChannel(channel):
self._read_scores(channel)
# Total scores
try:
self.channelscores[channel][nickto] += self.channelscores[channel][nickfrom]
del self.channelscores[channel][nickfrom]
self._write_scores(channel)
irc.reply("Total scores merged")
except:
irc.error("Can't merge total scores")
# Day scores
try:
self._initdayweekyear(channel)
day = self.dow
week = self.woy
try:
self.channelweek[channel][week][day][nickto] += self.channelweek[channel][week][day][nickfrom]
except:
self.channelweek[channel][week][day][nickto] = self.channelweek[channel][week][day][nickfrom]
del self.channelweek[channel][week][day][nickfrom]
self._write_scores(channel)
irc.reply("Day scores merged")
except:
irc.error("Can't merge day scores")
else:
irc.error('You have to be on a channel')
mergescores = wrap(mergescores, ['channel', 'nick', 'nick', 'admin'])
def mergetimes(self, irc, msg, args, channel, nickto, nickfrom):
"""
[<channel>] <nickto> <nickfrom>
nickto gets the best time of nickfrom if nickfrom time is better than nickto time, and nickfrom is removed from the timelist. Also works with worst times.
"""
if irc.isChannel(channel):
try:
self._read_scores(channel)
# Merge best times
if self.channeltimes[channel][nickfrom] < self.channeltimes[channel][nickto]:
self.channeltimes[channel][nickto] = self.channeltimes[channel][nickfrom]
del self.channeltimes[channel][nickfrom]
# Merge worst times
if self.channelworsttimes[channel][nickfrom] > self.channelworsttimes[channel][nickto]:
self.channelworsttimes[channel][nickto] = self.channelworsttimes[channel][nickfrom]
del self.channelworsttimes[channel][nickfrom]
self._write_scores(channel)
irc.replySuccess()
except:
irc.replyError()
else:
irc.error('You have to be on a channel')
mergetimes = wrap(mergetimes, ['channel', 'nick', 'nick', 'admin'])
def rmtime(self, irc, msg, args, channel, nick):
"""
[<channel>] <nick>
Remove <nick>'s best time
"""
if irc.isChannel(channel):
self._read_scores(channel)
del self.channeltimes[channel][nick]
self._write_scores(channel)
irc.replySuccess()
else:
irc.error('Are you sure ' + str(channel) + ' is a channel?')
rmtime = wrap(rmtime, ['channel', 'nick', 'admin'])
def rmscore(self, irc, msg, args, channel, nick):
"""
[<channel>] <nick>
Remove <nick>'s score
"""
if irc.isChannel(channel):
try:
self._read_scores(channel)
del self.channelscores[channel][nick]
self._write_scores(channel)
irc.replySuccess()
except:
irc.replyError()
else:
irc.error('Are you sure this is a channel?')
rmscore = wrap(rmscore, ['channel', 'nick', 'admin'])
def dayscores(self, irc, msg, args, channel):
"""
[<channel>]
Shows the score list of the day for <channel>.
"""
if irc.isChannel(channel):
self._read_scores(channel)
self._initdayweekyear(channel)
day = self.dow
week = self.woy
if self.channelweek.get(channel):
if self.channelweek[channel].get(week):
if self.channelweek[channel][week].get(day):
# Getting all scores, to get the winner of the week
msgstring = ''
scores = sorted(iter(self.channelweek[channel][week][day].items()), key=lambda k_v2:(k_v2[1],k_v2[0]), reverse=True)
for item in scores:
msgstring += "x" + item[0] + "x: "+ str(item[1]) + " | "
if msgstring != "":
irc.reply("Scores for today: " + msgstring)
else:
irc.reply("There aren't any day scores for today yet.")
else:
irc.reply("There aren't any day scores for today yet.")
else:
irc.reply("There aren't any day scores for today yet.")
else:
irc.reply("There aren't any day scores for this channel yet.")
else:
irc.reply("Are you sure this is a channel?")
dayscores = wrap(dayscores, ['channel'])
def weekscores(self, irc, msg, args, week, nick, channel):
"""
[<week>] [<nick>] [<channel>]
Shows the score list of the week for <channel>. If <nick> is provided, it will only show <nick>'s scores.
"""
if irc.isChannel(channel):
self._read_scores(channel)
weekscores = {}
if (not week):
week = self.woy
if self.channelweek.get(channel):
if self.channelweek[channel].get(week):
# Showing the winner for each day
if not nick:
msgstring = ''
# for each day of week
for i in (1,2,3,4,5,6,7):
if self.channelweek[channel][week].get(i):
# Getting winner of the day
winnernick, winnerscore = max(iter(self.channelweek[channel][week][i].items()), key=lambda k_v:(k_v[1],k_v[0]))
msgstring += self.dayname[i - 1] + ": x" + winnernick + "x ("+ str(winnerscore) + ") | "
# Getting all scores, to get the winner of the week
for player in list(self.channelweek[channel][week][i].keys()):
try:
weekscores[player] += self.channelweek[channel][week][i][player]
except:
weekscores[player] = self.channelweek[channel][week][i][player]
if msgstring != "":
irc.reply("Scores for week " + str(week) + ": " + msgstring)
# Who's the winner at this point?
winnernick, winnerscore = max(iter(weekscores.items()), key=lambda k_v1:(k_v1[1],k_v1[0]))
irc.reply("Leader: x%sx with %i points." % (winnernick, winnerscore))
else:
irc.reply("There aren't any week scores for this week yet.")
else:
# Showing the scores of <nick>
msgstring = ''
total = 0
for i in (1,2,3,4,5,6,7):
if self.channelweek[channel][week].get(i):
if self.channelweek[channel][week][i].get(nick):
msgstring += self.dayname[i - 1] + ": "+ str(self.channelweek[channel][week][i].get(nick)) + " | "
total += self.channelweek[channel][week][i].get(nick)
if msgstring != "":
irc.reply(nick + " scores for week " + str(self.woy) + ": " + msgstring)
irc.reply("Total: " + str(total) + " points.")
else:
irc.reply("There aren't any week scores for this nick.")
else:
irc.reply("There aren't any week scores for this week yet.")
else:
irc.reply("There aren't any week scores for this channel yet.")
else:
irc.reply("Are you sure this is a channel?")
weekscores = wrap(weekscores, [optional('int'), optional('nick'), 'channel'])
def listscores(self, irc, msg, args, size, channel):
"""
[<size>] [<channel>]
Shows the <size>-sized score list for <channel> (or for the current channel if no channel is given)
"""
if irc.isChannel(channel):
try:
self.channelscores[channel]
except:
self.channelscores[channel] = {}
self._read_scores(channel)
# How many results do we display?
if (not size):
listsize = self.toplist
else:
listsize = size
# Sort the scores (reversed: the higher the better)
scores = sorted(iter(self.channelscores[channel].items()), key=lambda k_v9:(k_v9[1],k_v9[0]), reverse=True)
del scores[listsize:]
msgstring = ""
for item in scores:
# Why do we show the nicks as xnickx?
# Just to prevent everyone that has ever played a hunt in the channel to be pinged every time anyone asks for the score list
msgstring += "x" + item[0] + "x: "+ str(item[1]) + " | "
if msgstring != "":
irc.reply("\_o< ~ DuckHunt top-" + str(listsize) + " scores for " + channel + " ~ >o_/")
irc.reply(msgstring)
else:
irc.reply("There aren't any scores for this channel yet.")
else:
irc.reply("Are you sure this is a channel?")
listscores = wrap(listscores, [optional('int'), 'channel'])
def total(self, irc, msg, args, channel):
"""
Shows the total amount of ducks shot in <channel> (or in the current channel if no channel is given)
"""
if irc.isChannel(channel):
self._read_scores(channel)
if (self.channelscores.get(channel)):
scores = self.channelscores[channel]
total = 0
for player in list(scores.keys()):
total += scores[player]
irc.reply(str(total) + " ducks have been shot in " + channel + "!")
else:
irc.reply("There are no scores for this channel yet")
else:
irc.reply("Are you sure this is a channel?")
total = wrap(total, ['channel'])
def listtimes(self, irc, msg, args, size, channel):
"""
[<size>] [<channel>]
Shows the <size>-sized time list for <channel> (or for the current channel if no channel is given)
"""
if irc.isChannel(channel):
self._read_scores(channel)
try:
self.channeltimes[channel]
except:
self.channeltimes[channel] = {}
try:
self.channelworsttimes[channel]
except:
self.channelworsttimes[channel] = {}
# How many results do we display?
if (not size):
listsize = self.toplist
else:
listsize = size
# Sort the times (not reversed: the lower the better)
times = sorted(iter(self.channeltimes[channel].items()), key=lambda k_v10:(k_v10[1],k_v10[0]), reverse=False)
del times[listsize:]
msgstring = ""
for item in times:
# Same as in listscores for the xnickx
msgstring += "x" + item[0] + "x: "+ str(round(item[1],2)) + " | "
if msgstring != "":
irc.reply("\_o< ~ DuckHunt top-" + str(listsize) + " times for " + channel + " ~ >o_/")
irc.reply(msgstring)
else:
irc.reply("There aren't any best times for this channel yet.")
times = sorted(iter(self.channelworsttimes[channel].items()), key=lambda k_v11:(k_v11[1],k_v11[0]), reverse=True)
del times[listsize:]
msgstring = ""
for item in times:
# Same as in listscores for the xnickx
#msgstring += "x" + item[0] + "x: "+ time.strftime('%H:%M:%S', time.gmtime(item[1])) + ", "
roundseconds = round(item[1])
delta = datetime.timedelta(seconds=roundseconds)
msgstring += "x" + item[0] + "x: " + str(delta) + " | "
if msgstring != "":
irc.reply("\_o< ~ DuckHunt top-" + str(listsize) + " longest times for " + channel + " ~ >o_/")
irc.reply(msgstring)
else:
irc.reply("There aren't any longest times for this channel yet.")
else:
irc.reply("Are you sure this is a channel?")
listtimes = wrap(listtimes, [optional('int'), 'channel'])
def dbg(self, irc, msg, args):
"""
This is a debug command. If debug mode is not enabled, it won't do anything
"""
currentChannel = msg.args[0]
if (self.debug):
if irc.isChannel(currentChannel):
self._launch(irc, msg, '')
dbg = wrap(dbg)
def bang(self, irc, msg, args):
"""
Shoots the duck!
"""
currentChannel = msg.args[0]
if irc.isChannel(currentChannel):
if(self.started.get(currentChannel) == True):
# bangdelay: how much time between the duck was launched and this shot?
if self.times[currentChannel]:
bangdelay = time.time() - self.times[currentChannel]
else:
bangdelay = False
# Is the player reloading?
if (self.reloading[currentChannel].get(msg.nick) and time.time() - self.reloading[currentChannel][msg.nick] < self.reloadtime[currentChannel]):
irc.reply("%s, you are reloading... (Reloading takes %i seconds)" % (msg.nick, self.reloadtime[currentChannel]))
return 0
# This player is now reloading
self.reloading[currentChannel][msg.nick] = time.time();
# There was a duck
if (self.duck[currentChannel] == True):
# Did the player missed it?
if (random.random() < self.missprobability[currentChannel]):
irc.reply("%s, you missed the duck!" % (msg.nick))
else:
# Adds one point for the nick that shot the duck
try:
self.scores[currentChannel][msg.nick] += 1
except:
try:
self.scores[currentChannel][msg.nick] = 1
except:
self.scores[currentChannel] = {}
self.scores[currentChannel][msg.nick] = 1
irc.reply("\_x< %s: %i (%.2f seconds)" % (msg.nick, self.scores[currentChannel][msg.nick], bangdelay))
self.averagetime[currentChannel] += bangdelay
# Now save the bang delay for the player (if it's quicker than it's previous bangdelay)
try:
previoustime = self.toptimes[currentChannel][msg.nick]
if(bangdelay < previoustime):
self.toptimes[currentChannel][msg.nick] = bangdelay
except:
self.toptimes[currentChannel][msg.nick] = bangdelay
# Now save the bang delay for the player (if it's worst than it's previous bangdelay)
try:
previoustime = self.worsttimes[currentChannel][msg.nick]
if(bangdelay > previoustime):
self.worsttimes[currentChannel][msg.nick] = bangdelay
except:
self.worsttimes[currentChannel][msg.nick] = bangdelay
self.duck[currentChannel] = False
# Reset the basetime for the waiting time before the next duck
self.lastSpoke[currentChannel] = time.time()
if self.registryValue('ducks', currentChannel):
maxShoots = self.registryValue('ducks', currentChannel)
else:
maxShoots = 10
# End of Hunt
if (self.shoots[currentChannel] == maxShoots):
self._end(irc, msg, args)
# If autorestart is enabled, we restart a hunt automatically!
if self.registryValue('autoRestart', currentChannel):
# This code shouldn't be here
self.started[currentChannel] = True
self._initthrottle(irc, msg, args, currentChannel)
if self.scores.get(currentChannel):
self.scores[currentChannel] = {}
if self.reloading.get(currentChannel):
self.reloading[currentChannel] = {}
self.averagetime[currentChannel] = 0
# There was no duck or the duck has already been shot
else:
# Removes one point for the nick that shot
try:
self.scores[currentChannel][msg.nick] -= 1
except:
try:
self.scores[currentChannel][msg.nick] = -1
except:
self.scores[currentChannel] = {}
self.scores[currentChannel][msg.nick] = -1
# Base message
message = 'There was no duck!'
# Adding additional message if kick
if self.registryValue('kickMode', currentChannel) and irc.nick in irc.state.channels[currentChannel].ops:
message += ' You just shot yourself!'
# Adding nick and score
message += " %s: %i" % (msg.nick, self.scores[currentChannel][msg.nick])
# If we were able to have a bangdelay (ie: a duck was launched before someone did bang)
if (bangdelay):
# Adding time
message += " (" + str(round(bangdelay,2)) + " seconds)"
# If kickMode is enabled for this channel, and the bot have op capability, let's kick!
if self.registryValue('kickMode', currentChannel) and irc.nick in irc.state.channels[currentChannel].ops:
irc.queueMsg(ircmsgs.kick(currentChannel, msg.nick, message))
else:
# Else, just say it
irc.reply(message)
else:
irc.reply("There is no hunt right now! You can start a hunt with the 'start' command")
else:
irc.error('You have to be on a channel')
bang = wrap(bang)
def doPrivmsg(self, irc, msg):
currentChannel = msg.args[0]
if irc.isChannel(msg.args[0]):
if (msg.args[1] == '\_o< quack!'):
message = msg.nick + ", don't pretend to be me!";
# If kickMode is enabled for this channel, and the bot have op capability, let's kick!
if self.registryValue('kickMode', currentChannel) and irc.nick in irc.state.channels[currentChannel].ops:
irc.queueMsg(ircmsgs.kick(currentChannel, msg.nick, message))
else:
# Else, just say it
irc.reply(message)
def _end(self, irc, msg, args):