-
Notifications
You must be signed in to change notification settings - Fork 0
/
ircbot.bak.2.py
1527 lines (1354 loc) · 58.8 KB
/
ircbot.bak.2.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
# -*- coding: latin-1 -*-
#this program requires a slightly modified twisted irc.py that returns
#nick!ident@host instead of nick for joins, parts and quits.
#todo: users[nick] instead of users[ih]
#todo: draw rules http://www.chessvariants.com/fidelaws.html
#todo: better timing for reconnect tryings
#todo: chess takebacks?
#todo: a decimal expansion from .base that's too long will quit with flood. and why doesn't anti-flood work there?
#todo: add passwords to servers/networks?
#todo: fingerresponse and versionresponse
#bug: chad did aq and it added mine not his most recent
from twisted.words.protocols import irc
from twisted.internet import reactor, protocol
from twisted.python import log
import time, sys, os.path, re, random, string, StringIO
import pysqlite2.dbapi2 as sql
import twisted.internet.task, WConio
import pythonica2, factor3, math
ircrowwidth = 80
finterval = .1
fwindow = 10
logfilename = "zebot.log"
id = "zebot"
realname = "[][=][]=[][=][]=[][=][]=[][=][]"
quitmessage = '"yields falsehood when appended to its own quotation,"'
fingerresponse = "i do not want to go to the N th power of a matrix: is the number of a man: and a Woman a woman is a Woman. Une Femme est Une femme. A Woman Is a Woman. who is not a good Idea. by the way) is a solid result and weƒ ll be in the way of a Pilgrim, And the Pilgrim Continues HIS Way. Translated By RM French. New York: Harper and Row, Publishers. Inc. New York. NY."
versionresponse = "Python IRC bot by inhahe using Twisted IRC. Python 2.5/Win XP"
class network: pass
networks = []
#n = network()
#n.name = "freenode"
#n.joins = ["#JesusBot"]
#n.nicks = ["JesusBot"]
#n.hosts = [("irc.freenode.net",6667)]
#n.onconnect = lambda c: c.msg("nickserv", "identify a0a9oeuhu")
#networks.append(n)
n = network()
n.name = "dalnet"
n.joins = ["#prometheus", "#freethinkers"]
#n.joins = ["#mytest"]
n.nicks = ["PyBot", "PyBot_", "PyBot__"]
n.hosts = [("irc.dal.net",6667)]
networks += [n]
n = network()
n.name = "undernet"
n.joins = ["#thinkers"]
n.nicks = ["PyBot","PyBot_", "PyBot__"]
n.hosts = [("irc.undernet.org",6667)]
networks += [n]
#n = network()
#n.name="local"
#n.joins = ["test"]
#n.nicks = ["Jesusbot"]
#n.hosts = [("localhost",6667)]
#networks += [n]
#n = network()
#n.name = "efnet"
#n.joins = ["#JesusBot"]
#n.nicks = ["JesusBot"]
#n.hosts = [("irc.efnet.net",6667)]
#networks += [n]
#n = network()
#n.name = "organelle"
#n.joins = ["#organelle"]
#n.hosts = [("irc.organelle.org", 6667)]
#n.nicks = ["JesusBot"]
#networks += [n]
chesscs = [ [0,1,10,10,4,4], [0,1,3,3,13,13], [0,15,12,12,3,3],
[0,15,12,12,6,6], [0,15,3,3,6,6], [0,15,12,12,4,4],
[0,15,12,12,6,6], [0,15,12,12,1,1], [0,15,10,10,4,4],
[0,15,6,6,1,1], [0,15,3,3,1,1], [0,14,4,4,1,1],
[2,3,11,11,13,13], [2,3,0,0,13,13],
[0,8,3,3,1,1], [0,8,4,4,1,1], [10,3,0,0,1,1],
[10,3,8,8,1,1], [4,1,0,0,12,12], [15,14,4,4,1,1],
[15,14,12,12,1,1], [15,14,12,12,4,4], [0,14,12,12,1,1],
[0,14,14,0,1,1], [10,12,0,0,4,4] ]
numerals = string.digits + string.uppercase
def insertseen(nick, ih):
cursor.execute("update seen
def seen(botinstance, target, parameter):
botinstance.msg(target, "Not implemented yet.")
def getanswer(number, frombase, tobase):
number, fraction = (number+".").split(".",1)
fraction = fraction.replace(".","")
result = 0
answer = ""
if number:
value = int(number, frombase)
scratchvalue = value
for place in range(math.log(value, tobase),-1,-1):
answer += numerals[scratchvalue / tobase**place]
scratchvalue -= scratchvalue / tobase**place * tobase**place
vinculum=0
if fraction != "":
answer += "."
num = int(fraction, frombase)*tobase
den = frombase**len(fraction)
nums = []
while num>0:
v = num/den
if v < tobase:
answer += numerals[v]
num = (num-den*v)*tobase
if num in nums:
return answer, len(nums)-nums.index(num)
nums += [num]
return answer, 0
return answer, 0
def cmdbase(conn, target, params):
if len(params)<2:
conn.msg(target, "Must specify a number and a base to convert to.")
return
params[0]=params[0].upper()
if len(params)==2: params.insert(1, "10")
try:
tobase = int(params[2])
frombase = int(params[1])
assert 2 <= tobase <= 36 and 2 <= frombase <= 36
except:
conn.msg(target, "Bases must be integers between 2 and 36.")
return
try:
map((numerals[:frombase]+".").index, params[0])
except:
conn.msg(target, "Valid numerals for base %d are: %s" % (frombase, numerals[:frombase]))
return
answer1, vin1 = getanswer(params[0], frombase, 10)
answer2, vin2 = getanswer(params[0], frombase, tobase)
middle = " in base %d is " % tobase
string2 = answer1 + middle + answer2
if vin1 or vin2:
string1=("_"*vin1).rjust(len(answer1))+" "*len(middle)+("_"*vin2).rjust(len(answer2))
conn.msg(target, ''.join(["" + x + "\n" + y +"\n" for (x, y) in zip(re.findall(".{1,100}",string1), re.findall(".{1,100}",string2))]))
else:
for x in re.findall(".{1,100}",(answer1+middle+answer2)):
conn.msg(target, x)
def shutdown():
print "[Shutting down]"
db.commit()
cursor.close()
db.close()
for b in botinstances:
b.quit(quitmessage)
class chanmsg:
def __init__(self, type=None, text=None, nick=None, ident=None, host=None, time=None,
nick2=None, server1=None,
server2=None, userid=None, username=None):
self.text=text
self.nick=nick
self.ident=ident
self.host=host
self.time=time
self.type=type
self.nick2=nick2
self.server1=server1
self.server2=server2
self.userid=userid
self.username=username
def cplace(x1,y1,x2=None,y2=None):
a=chr(ord('a')+x1)+str(8-y1)
if x2 is not None: a+=chr(ord('a')+x2)+str(8-y2)
return a
def dict_factory(cursor, row):
d = {}
for idx, col in enumerate(cursor.description):
d[col[0]] = row[idx]
return d
class DictCursor(sql.Cursor):
def __init__(self, *args, **kwargs):
sql.Cursor.__init__(self, *args, **kwargs)
self.row_factory = lambda cur, row: dict_factory(self, row)
class DictConnection(sql.Connection):
def __init__(self, *args, **kwargs):
sql.Connection.__init__(self, *args, **kwargs)
def cursor(self):
return DictCursor(self)
#[4,1,0,0,8,8], [0,3,12,12,1,1], [10,3,0,0,12,12],[10,3,12,12,1,1],
chessct = dict(R="#",N=chr(167),B="x",Q="*",K="+",P="i")
chessct["K"] = chr(177)
chessct[" "]=" "
db = sql.connect("zebot.db", factory=DictConnection)
cursor = db.cursor()
cursor.execute("""CREATE TABLE IF NOT EXISTS users (userid integer primary key
autoincrement,
username char(30), password char(30), cchessid int)""")
cursor.execute("""create table if not exists quotes (time datetime,
text varchar(500), sbnick varchar(70), sbuserid int,
sbident varchar(70), sbhost varchar(70),
qbnih varchar(212), qbuserid int, type varchar(10),
channel varchar(100), network varchar(50), quoteid integer
primary key autoincrement, cchessid int)""")
cursor.execute("""create table if not exists chess (chessid integer primary
key autoincrement,
wuserid int, buserid int, board char(64), turn int, won int,
stalemate int, draw int, forfeit int, moves text,
wscolor int, bscolor int, wpwscolor int, wpbscolor int,
bpwscolor int, bpbscolor int, wcheck int, bcheck int)""")
cursor.execute("""create table if not exists convo (text varchar(500),
sbident varchar(70))""")
cursor.execute("""create table if not exists lastseen (nick varchar(100),
identhost varchar(100), network varchar(100),
channel varchar(100), time timestamp)""")
class chan:
backbuffer = []
users = {}
class usr: pass
def fix(a):
return a.replace("\\","\\\\").replace("'","\\'")
def clr(piece):
return [piece==piece.lower(), None][piece==" "]
def pc(piece):
return piece.upper(), clr(piece)
def checkline(p1x,p1y,p2x,p2y,board):
dx = (p2x>p1x)*2-1
dy = (p2y>p1y)*2-1
if p1x==p2x:
return not ''.join([board[y*8+p1x] for y in range(p1y+dy, p2y, dy)]).strip()
elif p1y==p2y:
return not ''.join([board[p1y*8+x] for x in range(p1x+dx, p2x, dx)]).strip()
else:
return not ''.join([board[(p1y+n*dy+dy)*8+p1x+n*dx+dx] for n in range(abs(p2y-p1y)-1)]).strip()
def updateseen(nick, identhost, network, channel):
cursor.execute("update lastseen where nick=? and identhost=? and network=?"
" and channel=?", (nick, identhost, network, channel))
if cursor.rowcount==0:
insertdict(lastseen, nick=nick, nicklower=nick.lower(),
identhost=identhost, network=network, channel=channel)
#def insertdict(table, **dict):
## cursor.execute("begin")
# cursor.execute("insert into %s (%s) values (%s)" % (table,
# fix(",".join([str(x[0]) for x in dict.items() if not x[1] is None])),
# ",".join(["'%s'" % fix(str(x)) for x in dict.values() if not x is None])))
## cursor.execute("end")
def insertdict(table, **dict):
cursor.execute("insert into %s (%s) values (%s)" % (table,
",".join(dict.keys()), ",".join(["?"]*len(dict))), dict.values())
users = {}
def getid(ident, host):
try: return users[ident+"@"+host].userid
except: return None
def getuname(ident, host):
try: return users[ident+"@"+host].username
except: return None
class MessageLogger:
"""
An independant logger class (because separation of application
and protocol logic is a good thing).
"""
def __init__(self, file):
self.file = file
def log(self, message):
"""Write a message to the file."""
timestamp = time.strftime("[%H:%M:%S]", time.localtime(time.time()))
self.file.write('%s %s\n' % (timestamp, message))
self.file.flush()
print message
def close(self):
self.file.close()
class bot(irc.IRCClient):
def showboard2(self, nick, params): #debug
params += ["0"]*(6-len(params))
board = ("rnbqkbnr"
"pppppppp"
" "
" "
" "
" "
"PPPPPPPP"
"RNBQKBNR")
for x in range(8):
m = str(8-x) + " "
for y in range(8):
piece = board[x*8+y]
bp = piece.lower() == piece
piece = piece.upper()
m += chr(3) + params[2+bp*2+(x+y)%2] + "," + params[(x+y)%2] + \
" " + chessct[piece] + " "
self.msg(nick, m)
self.msg(nick, " a b c d e f g h ")
def docommandq(self):
if self.commandqueue:
cmd, args = self.commandqueue.pop(0)
cmd(*args)
self.lctime = time.time()
else:
if self.penalty>0: self.penalty -= 1
def __init__(self, *args, **kwargs):
global botinstances
botinstances += [self]
self.channels = {}
self.commandqueue = []
# self.cmdtimes = []
self.penalty = 0
# self.lctime = None
self.pmcbonce={}
self.looper = twisted.internet.task.LoopingCall(self.docommandq)
self.looper.start(finterval)
def docommand(self, cmd, *args):
#sliding window method
# self.cmdtimes = [t for t in self.cmdtimes
# if not t < time.time()-finterval] + time.time()
# if len(self.cmdtimes) > 1:
if self.penalty > fwindow:
self.commandqueue += [(cmd, args)]
else:
self.penalty += 1
cmd(*args)
# self.lctime = time.time()
# self.looper.stop()
# self.looper.start(finterval) #todo: synchronize looper with this message
def msg(self, target, text):
msgs = text.split("\n")
for m in msgs:
self.docommand(self.msg2, target, m)
def msg2(self, target, text):
irc.IRCClient.msg(self, target, str(text))
logger.log("privmsg to <%s> <%s> %s" % (self.net, target, text))
def userJoined(self, user, channel):
nick, rest = user.split("!",1)
ident, host = rest.split("@",1)
n = nick.lower()
self.channels[channel.lower()].users[n]=usr()
self.channels[channel.lower()].users[n].ident = ident
self.channels[channel.lower()].users[n].host = host
logger.log("<%s> <%s> joined: %s" % (self.net, channel, user))
updateseen(nick, rest, self.net, channel)
def userLeft(self, user, channel):
nick, ih = user.split("!",1)
del self.channels[channel.lower()].users[nick.lower()]
if ih in users:
if nick not in (x.users for y in self.channels for x in y):
del users[ih]
logger.log("<%s> <%s> parted: %s" % (self.net, channel, user))
updateseen(nick, ih, self.net, channel)
def userQuit(self, user, message):
nick, ih = user.split("!",1)
logger.log("<%s> quit: %s (%s)" % (self.net, user, message))
if ih in users: del users[ih]
for ch in self.channels.values():
if nick.lower() in ch.users: del ch.users[nick.lower()]
updateseen(nick, ih, self.net)
def userKicked(self, kickee, channel, kicker, message):
nick, ih = user.split("!",1)
logger.log("<%s> <%s> %s kicked by %s" %
(self.net, channel, kickee, kicker))
if ih in users:
if nick not in (x.users for y in self.channels for x in y):
del users[ih]
updateseen(nick, ih, self.net, channel)
def userRenamed(self, nih, newname):
oldname, ih = nih.split("!",1)
for ch in self.channels.values():
try:
ch.users[newname.lower()]=ch.users[oldname.lower()]
del ch.users[oldname.lower()]
except: pass
for x in users.values():
if x.nick==oldname: x.nick=newname
updateseen(nick, ih, self.net)
def irc_RPL_NAMREPLY(self, prefix, params):
for nick in params[3].split():
nick = nick.lower()
if nick[0] not in string.ascii_lowercase+"\|`^_": nick=nick[1:]
self.channels[params[2].lower()].users[nick.lower()]=usr()
updateseen(nick, None, self.net)
def irc_ERR_NICKNAMEINUSE(self, prefix, params):
o = self.factory.nickcycle
self.factory.nickcycle = (self.factory.nickcycle+1) % len(self.factory.network.nicks)
self.register(self.factory.network.nicks[self.factory.nickcycle])
logger.log("<%s> [%s nick taken, trying %s]" % \
(self.factory.network.name, self.factory.network.nicks[o],
self.factory.network.nicks[self.factory.nickcycle]))
def connectionMade(self):
self.net = self.factory.network.name
irc.IRCClient.connectionMade(self)
logger.log("[Connected to %s]" % self.net)
if hasattr(self.factory.network, "onconnect"):
self.factory.network.onconnect(self)
def connectionLost(self, reason):
irc.IRCClient.connectionLost(self, reason)
logger.log("[Disconnected from %s]" % self.net)
#todo: loop through all users on network and updateseen
# callbacks for events
def signedOn(self):
"""Called when bot has succesfully signed on to server."""
for c in self.factory.network.joins: self.join(c)
def joined(self, channel):
logger.log("<%s> [I have joined %s]" % (self.net,channel))
self.channels[channel.lower()] = chan()
def left(self, channel):
ou = self.channels[channel.lower()].users
del self.channels[channel.lower()]
for n in ou:
if ou[n].ident+"@"+ou[n].nick in users:
if n not in (x for x in self.channels for y in x.users):
del users[ou[n].ident+"@"+ou[n].nick]
logger.log("<%s> [I have left %s]" % (self.net, channel))
def kicked(self, channel, kicker, message):
ou = self.channels[channel.lower()].users
del self.channels[channel.lower()]
for n in ou:
if ou[n].ident+"@"+ou[n].nick in users:
if n not in (x for x in self.channels for y in x.users):
del users[ou[n].ident+"@"+ou[n].nick]
logger.log("<%s> I was kicked from %s by %s (%s)" %
(self.net, channel, kicker, message))
def noticed(self, user, channel, message):
nick, ih = user.split("!",1)
if channel in self.channels:
logger.log("notice from <%s> <%s> <%s> %s" %
(self.net, nick, channel, message))
else:
logger.log("notice from <%s> %s %s" %
(self.net, ["","<"+nick+">"][bool(user)], message))
updateseen(nick, ih, None, self.net)
def help(self, target, params):
if len(params)==0:
self.msg(target, "Usage: .help [topic]\n"
"Help topics: accounts, chess, quotes, math, seen")
elif len(params)==1:
if params[0].lower()=="chess":
self.msg(target,
".cn or .chessnew [colorscheme] <opponent> <user to play white>\n"
"Creates a new chess game with the specified color scheme (or"
" the default color scheme if none specified) against the user"
" <opponent>. <user to play white> must be either your"
" username or your opponent's\n"
"\n"
".csc or .chessshowcolors\n"
"Shows available chess color schemes\n"
"\n"
".cs or .chessshow [game number]\n"
"Shows the game of the specified game number. If"
" no game number is specified, it shows the last game you "
" created, viewed or moved in.\n"
"\n"
".cm or .chessmove [gamenumber] <origin square> <destination square>\n"
"Moves your piece from <origin square> to <destinatio square>. A square is notated"
" by its column lettered a-h followed by its row numbered 8-1.\n"
" if gamenumber is omitted, the last game you created, viewed, or"
" moved in is assumed.\n"
"Ex.: .cm e2 e4\n"
"(moves the king's pawn up two squares)\n"
"\n"
".cl or .chesslist [user1] [user2]\n"
"If one user is specified, lists all games in which that user"
" is playing. If two users are specified, lists all games in"
" which both users are playing (order independent). If no users"
" are specified, lists all games.\n"
"\n"
".cla or .chesslistactive [user1] [user2]\n"
"Like .cl but lists only active games.\n"
"\n"
".css or .chesssavestate [gamenumber]\n"
"Saves the current game state to a new board.\n"
"If no game number is specified, it saves the last game you"
" created, viewed, or moved in.\n"
"Will not work on a finished game.\n"
"--End help--")
elif params[0].lower()=="math":
self.msg(target,
".calc <expression>\n"
"Solves <expression>\n"
"Valid functions are: Sqrt, Root, Exp, Abs, Mod, Round, Sin, Cos, Tan, ASin, ACos, ATan, Rad2Deg, Deg2Rad, and Complex\n"
"Function parameters are enclosed by square brackets ([]).\n"
"Valid symbols are: \n"
"'(', ')'\n"
"'[', ']'\n"
"'+', '-', '*', '/'\n"
"'^', '**' (Exponent)\n"
"'=' (Set)\n"
"'=;' (Unset)\n"
"'==' (Compare)\n"
"'->' (Rule)\n"
"'j' (denotes an imaginary number)\n"
"any arbitrary string of letters and/or numbers starting with a letter (Variable name)\n"
"Lists are encased in square brackets ([]).\n"
"A slice is written as [[args]] right after an expression and returns the component of the expression described by args. The first arg acts on the expression, the second arg acts on the result of the first, etc. \n"
"A value of 0 returns a symbol for the head of the expression, a positive integer returns that component of the expression (as if the expression was a 1-based list) and a negative number returns the component that number from the end of the expression.\n"
"\n"
".factor <number>\n"
"Factors the given number\n"
"\n"
".base <number> [base to convert from] <base to convert to>\n"
"Converts a number from one base to another base. Will convert "
"non-integers. If [base to convert from] is omitted, base 10 is "
"assumed. Bases must be in the range 2-36.\n"
"--End help--")
elif params[0].lower()=="quotes":
self.msg(target,
".aq [nick|ident|username][one or more words]\n"
"With no parameters, adds the most recent action or message to the"
" quotes database.\n"
"With one paramater, adds the most recent action or message whose"
" sender's nick, ident or username matches the parameter or whose"
" text contains the parameter.\n"
"With two or more parameters, adds the most recent action or message"
" whose text contains all the parameters given in the same order or"
" whose sender's nick, ident or username matches the first parameter"
" and whose text contains all parameters after the first parameter in"
" the same order.\n"
"\n"
".rq [quote id|nick|ident|username|two or more words]\n"
"With no parameters, retrieves a random quote.\n"
"With one parameter, retrieves a random quote whose quote id matches"
" the parameter or whose sender's nick, ident or username matches the"
" parameter.\n"
"With 2 or more parameters, retrieves a random quote containing all the"
" words in the same order.\n"
"\n"
".dq quoteid\n"
"Deletes the quote with the specified quote id.")
elif params[0].lower()=="accounts":
self.msg(target,
".login <username> <password>\n"
"Logs you in with the given username and password. Can only be done "
" via a private message. Will only work if you are in at least one"
" channel that I am in.\n"
".logout\n"
"\n"
"Logs you out.\n"
".register <username> <password>\n"
"\n"
"Creates a new account with the given username and password. Can"
" only be done via a private message.\n"
"--End help--")
elif params[0].lower()=="seen":
self.msg(target,
".seen <username|nick|nick!ident@hostmask>\s"
"Tells you when the person named by bot username, nick, "
"or nick!ident@hostmask was last seen. The latter may contain "
"asterisks (wildcards)." )
else:
self.msg(target, "Sorry, I don't have any help on that topic.")
else:
self.msg(target, "Usage: .help [topic]")
def chessnew(self, u, target, params):
if u is None:
self.msg(target, "You must be logged in to create a new chess game.")
return
cs = None
if len(params)==3:
cs = params.pop(0)
if len(params) != 2:
self.msg(target, "Usage: .cn [colorscheme] opponent usertoplaywhite\n"
"(.csc to show available color schemes)")
return
cursor.execute("select * from users where lower(username) = '%s'" %
params[0])
d = cursor.fetchone()
if not d:
self.msg(target, "User %s not found." % params[0])
return
if cs:
try:
i = int(cs)
assert 0 < i <= len(chesscs)
except:
self.msg(target, "That is not a valid color scheme "
"index.\n.csc to show available color schemes")
return
v = chesscs[i-1]
else:
v = [15,14,12,12,4,4]
if params[1] not in [u.username.lower(), params[0]]:
self.msg(target, "White must be played by either you or your "
"opponent.\n(Usage: .cn or .chessnew [colorscheme] opponent usertoplaywhite)\n"
"(.csc to list color schemes)")
return
wuserid = u.userid
buserid = d["userid"]
if params[1] == params[0]: wuserid, buserid = buserid, wuserid
insertdict('chess',
board = ("rnbqkbnr"
"pppppppp"
" "
" "
" "
" "
"PPPPPPPP"
"RNBQKBNR"),
turn = 0, wuserid=wuserid, wscolor=v[0], buserid=buserid,
bscolor=v[1],wpwscolor=v[2],wpbscolor=v[3],bpwscolor=v[4],
bpbscolor=v[5],moves="",wcheck=0,bcheck=0)
chessid=cursor.lastrowid
cursor.execute("update users set cchessid='%d' where userid='%d'" %
(chessid, u.userid))
self.msg(target, "Chess game #%s has been created." % chessid)
self.msg(target, "")
self.showboard(target, chessid)
def showcolors(self, target):
self.msg(target, "Chess color schemes:")
for x in range(0, len(chesscs), ircrowwidth/14): #adjust for self nick len
self.msg(target, "")
msg = ""
P = chessct["P"]
for y, v in enumerate(chesscs[x:x+ircrowwidth/14]):
msg += '1,0 %2d: %s,%s %s %s,%s %s %s,%s %s ' % (y+x+1, v[5],
v[1], P, v[4], v[0], P, v[5], v[1], P)
self.msg(target, msg)
msg = ""
for v in chesscs[x:x+ircrowwidth/14]:
msg += '1,0 0,%s 0,%s 0,%s ' % (v[0], v[1], v[0])
self.msg(target, msg)
msg = ""
for v in chesscs[x:x+ircrowwidth/14]:
msg += '1,0 %s,%s %s %s,%s %s %s,%s %s ' % (v[3],
v[1], P, v[2], v[0], P, v[3], v[1], P)
self.msg(target, msg)
if len(chesscs) % (ircrowwidth/14) == 0:
self.msg(target, "\nFin.")
def showboard(self, target, chessid):
cursor.execute("select * from chess where chessid = '%d'" % chessid)
d = cursor.fetchone()
cursor.execute("select username from users where userid='%s'" %
d["wuserid"])
wusername=cursor.fetchone()["username"]
cursor.execute("select username from users where userid='%s'" %
d["buserid"])
busername=cursor.fetchone()["username"]
sc = d["wscolor"], d["bscolor"]
pc = d["wpwscolor"], d["wpbscolor"], d["bpwscolor"], d["bpbscolor"]
for x in range(8):
m = str(8-x) + " "
for y in range(8):
piece = d["board"][x*8+y]
bp = piece.lower() == piece
piece = piece.upper()
m += chr(3) + "%d,%d %s " % (pc[bp*2+(x+y)%2], sc[(x+y)%2],
str(chessct[piece]))
if x==3: m += "1,0 Game #%d between %s (white) and %s (black)" % \
(chessid, str(wusername), str(busername))
if x==4:
m += "1,0 "
if not d["won"] is None:
m += ["White","Black"][d["won"]] + " has won this game"
elif d["draw"]:
m += "The game was a draw"
elif d["forfeit"] is not None:
m += ["White","Black"][d["forfeit"]] + " has forfeited this game"
elif d["stalemate"]:
m += "This game is a stalemate"
elif d["turn"] is not None:
m += ["White", "Black"][d["turn"]] + "'s turn to move"
if x==5:
if d["wcheck"]:
m += "1,0 White is in check"
elif d["bcheck"]:
m += "1,0 Black is in check"
self.msg(target, m)
self.msg(target, " a b c d e f g h")
def showboard3(self, u, target, params):
usage = ("Usage: .cs [gamenumber]\n"
"You must be logged in and be in at least one"
" chess game to omit the game number.")
if len(params)>1:
self.msg(target, usage)
return
if len(params)==1:
if params[0][0]=="#": params[0] = params[0][1:]
try: chessid=int(params[0])
except:
self.msg(target, usage)
return
cursor.execute("select * from chess where chessid='%d'" % chessid)
if not cursor.fetchone():
self.msg(target, "There is no chess game by that number.")
return
else:
if u is None:
self.msg(target, usage)
return
cursor.execute("select cchessid from users where userid='%s'" %
u.userid)
chessid = cursor.fetchone()["cchessid"]
if chessid is None:
self.msg(target, usage)
return
self.showboard(target, chessid)
if u is not None:
cursor.execute("update users set cchessid='%d' where userid='%d'" %
(chessid, u.userid))
def chesslist(self, u, target, params, unf):
if len(params)==1:
cursor.execute("select * from chess, users where (buserid = userid"
" or wuserid = userid) and lower(username) = '%s'" % params[0])
d = cursor.fetchall()
if unf: d = [x for x in d if x["forfeit"] is None and x["won"] is None and
(not x["stalemate"]) and (not x["draw"])]
if not d:
self.msg(target, "No %schess games with %s as a player were found." % (
["","active "][unf], params[0]))
elif len(params)==2:
cursor.execute("select * from chess where"
" (wuserid in"
" (select userid from users where lower(username) = '%s')"
" and buserid in"
" (select userid from users where lower(username) = '%s'))"
" or"
" (wuserid in"
" (select userid from users where lower(username) = '%s')"
" and"
" buserid in"
" (select userid from users where lower(username) = '%s'))" % \
(params[0], params[1], params[1], params[0]))
d = cursor.fetchall()
if unf: d = [x for x in d if x["forfeit"] is None and x["won"] is None and
(not x["stalemate"]) and (not x["draw"])]
if not d:
self.msg(target, "No %schess games between %s and %s were found." % \
(["","active "][unf], params[0], params[1]))
elif len(params)==0:
cursor.execute("select * from chess")
d = cursor.fetchall()
if unf: d = [x for x in d if x["forfeit"] is None and x["won"] is None and
(not x["stalemate"]) and (not x["draw"])]
if not d:
self.msg(target, "No %schess games were found." % ["","active "][unf])
elif len(params)>2:
self.msg(target, "Usage: .cl [user1 user2]")
return
m = ""
for g in d:
cursor.execute("select username from users where userid = '%d'" \
% g["wuserid"])
wuser = cursor.fetchone()["username"]
cursor.execute("select username from users where userid = '%d'" \
% g["buserid"])
buser = cursor.fetchone()["username"]
n = "%d: %s vs. %s" % (g["chessid"], wuser, buser)
if g["stalemate"]:
n += " (stalemate)"
elif not g["won"] is None:
n += " (" + ["white","black"][g["won"]] + " won)"
elif not g["forfeit"] is None:
n += " (" + ["white","black"][g["forfeit"]] + " forfeited)"
elif g["stalemate"]:
n += " (stalemate)"
elif g["draw"]:
n += " (draw)"
else:
n += " (%s's turn)" % ["white","black"][g["turn"]]
if len(m)+len(n)+1 > ircrowwidth:
self.msg(target, m)
m = n
else:
if m: m += " "
m += n
self.msg(target, m)
def chesscopy(self, u, target, params):
if not u:
self.msg(target, "You must be logged in to do that.")
return
usage = "Usage: .css [gamenumber]"
if len(params)>1:
self.msg(target, usage)
return
elif len(params)==1:
if params[0][0]=="#":
params[0]=params[0][1:]
try:
chessid = int(params[0])
except:
self.msg(target, usage)
return
cursor.execute("select * from chess where chessid = '%d'" % chessid)
g = cursor.fetchone()
if not g:
self.msg(target, "Error: That chess game does not exist.")
return
if g["wuserid"] != u.userid and g["buserid"] != u.userid:
self.msg(target, "You can't copy that game because you're not in it.")
return
else:
cursor.execute("select cchessid from users where userid = '%d'"
% u.userid)
l = cursor.fetchone()
if not l:
self.msg(target, "Please include the gamenumber parameter.")
return
chessid = l["cchessid"]
cursor.execute("select * from chess where chessid = '%d'" % chessid)
g = cursor.fetchone()
if not g:
self.msg(target, "Sorry, the game you were playing has been deleted.")
return
if g["stalemate"] or g["won"] is not None or g["forfeit"] is not None or g["draw"]:
self.msg(target, "Error: Will not copy a finished game.")
return
del g["chessid"]
insertdict("chess",**g)
self.msg(target, "Chess game #%d has been saved as #%d." % (chessid,
cursor.lastrowid))
def domove(self, turn,p1x,p1y,p2x,p2y,recurse,do,b,moves,u=None,chessid=None,wcheck=False,bcheck=False):
reason = ""
piece = b[p1y*8+p1x]
if piece == " ":
return None, "There is no piece at square %s!" % cplace(p1x,p1y)
piece, color = pc(piece)
if color != turn:
return None, "You can't move that piece because it is not yours."
if not piece=="N":
if not checkline(p1x, p1y, p2x, p2y,b):
return None, "You can't move there."
if piece=="P":
b2 = b
p1x2, p1y2, p2x2, p2y2 = p1x, p1y, p2x, p2y
if turn:
b2 = b[::-1]
p1x2, p1y2, p2x2, p2y2 = 7-p1x, 7-p1y, 7-p2x, 7-p2y
if p1x2==p2x2:
if b2[p2x2+p2y2*8]!=" ":
return None, "You can't move there."
if p2y2==p1y2-2:
if p1y2!=6:
return None, "You can't move there. Pawns may only move two squares on their first move."
elif p2y2!=p1y2-1:
return None, "You can't move there."
else:
if not (abs(p2x2-p1x2)==1 and p1y2-p2y2)==1:
return None, "You can't move there."
if b2[p2y2*8+p2x2]==" ":
if moves[-2:]==cplace(
p2y+[-1,1][color],p2x,p2y+[1,-1][color],p2x) and \
place(p2y+[-1,1][color],p2x) not in moves[:-4]:
reason="En passant."
b[(p2y+[1,-1][color])*8+p2x]=" "
else:
return None, "You can't move there. Pawns can only move diagonally when taking a piece."
if p2y2==0:
def finishpawn(self, user, channel, msg, chessid=chessid,
color=color, p1x=p1x,p1y=p1y,p2x=p2x,p2y=p2y,board=b):
target = channel in self.channels and channel or user.split("!")[0]
try: piece=dict(rook="R",knight="N",bishop="B",
queen="Q")[msg.lower()]
except:
self.msg(target, "Invalid response.")
return
board = board[:p1y*8+p1x] + " " + board[p1y*8+p1x+1:]
board = board[:p2y*8+p2x] + [piece, piece.lower()][color] + \
board[p2y*8+p2x+1:]
self.chessmove2(target, chessid, turn, board, cplace(p1x,p1y,p2x,p2y)+piece, "Promotion.")
if do:
self.pmcbonce[u.ident+"@"+u.host]=finishpawn
return None, "What piece would you like to change your pawn to? Type rook, knight, bishop or queen."
else:
return True, ""
elif piece=="R":
if not (p1x==p2x or p1y==p2y):
return None, "You can't move there. Rooks can only move straight."
elif piece=="N":
if not (abs(p1x-p2x),abs(p1y-p2y)) in ((1,2),(2,1)):
return None, "You can't move there. Knights don't move that way."
elif piece=="B":
if not abs(p1x-p2x)==abs(p1y-p2y):
return None, "You can't move there. Bishops can only move diagonally."
elif piece=="Q":
if not (p1x==p2x or p1y==p2y or abs(p1x-p2x)==abs(p1y-p2y)):
return None, "You can't move there. Queens can only move straight or diagonally."
elif piece=="K":
if p1y==p2y and p2y==[7,0][turn] and abs(p2x-p1x)==2 and p1x==4:
if cplace(p1y,[0,7][p2x>4]) in moves or \
cplace(p1y,4) in moves:
return None, "You can't move there. Castling is only allowed when neither the king nor the rook has moved previously in the game."
if not checkline([0,7][p2x>4], p1y, p1x, p1y, b):
return None, "You can't move there. Castling is only allowed when there are no pieces between the king and the rook."
for px in range(8):
for py in range(8):
if domove(not turn,px, py, (p1x+p2x)/2,p2y,True,False,b,moves)[0]:
return None, "You can't move there. Castling is not allowed when the king would pass over an attacked square."
if domove(not turn,px, py, p1x+p1y,True,False,b,moves)[0]:
return None, "You can't move there. Castling is not allowed when the king is in check."
b = b[:p1y*8+[0,7][p2x>4]] + " " + b[p1y*8+[0,7][p2x>4]+1:]
b = b[:p1y*8+[3,5][p2x>4]] + ["R","r"][turn] + b[p1y*8+[3,5][p2x>4]+1:]
reason = "Castling."
else:
if not abs(p1x-p2x)+abs(p1y-p2y) in (1,2):
return None, "You can't move there. Kings aren't that agile."
if clr(b[p2y*8+p2x])==turn:
return None, "You can't move there. One of your pieces is on that square."
b = b[:p2y*8+p2x] + b[p1y*8+p1x] + b[p2y*8+p2x+1:]
b = b[:p1y*8+p1x] + " " + b[p1y*8+p1x+1:]
if recurse:
kp=b.index(["K","k"][turn])
for tp1x in range(8):
for tp1y in range(8):
if self.domove(not turn, tp1x,tp1y, kp%8,kp/8,False,False,b,
cplace(p1x,p1y,p2x,p2y))[0]:
if ((not turn) and wcheck) or (turn and bcheck):
return None, "You can't move there. Your king is in check."
else:
return None, "You can't move there. That move would put your king in check."
return b, reason
def chessmove2(self, target, chessid, turn, board, move, reason):
cursor.execute("select * from chess where chessid = '%d'" % chessid)
d = cursor.fetchone()
n = [x.nick for x in users.values() if x.userid ==
[d["wuserid"], d["buserid"]][not turn]]
if len(n):