]> jfr.im git - erebus.git/blame - bot.py
bugfix foo.py
[erebus.git] / bot.py
CommitLineData
b25d4368 1#!/usr/bin/python
2
931c88a4 3# Erebus IRC bot - Author: John Runyon
4# "Bot" and "BotConnection" classes (handling a specific "arm")
5
b25d4368 6#TODO: error checking
7
49a455aa 8import socket, sys
b25d4368 9
10#bots = {'erebus': bot.Bot(nick='Erebus', user='erebus', bind='', server='irc.quakenet.org', port=6667, realname='Erebus')}
11class Bot(object):
5477b368 12 def __init__(self, parent, nick, user, bind, server, port, realname):
b25d4368 13 self.parent = parent
14 self.nick = nick
a12f7519 15 self.user = user
16 self.realname = realname
5477b368 17
586997a7 18 curs = self.parent.db.cursor()
19 curs.execute("SELECT chname FROM chans WHERE bot = %s AND active = 1", (self.nick,))
20 chansres = curs.fetchall()
21 curs.close()
5477b368 22
586997a7 23 self.chans = [self.parent.newchannel(self, row['chname']) for row in chansres]
b25d4368 24
a12f7519 25 self.conn = BotConnection(self, bind, server, port)
b25d4368 26 def connect(self):
b2a896c8 27 if self.conn.connect():
49a455aa 28 self.parent.newfd(self, self.conn.socket.fileno())
29
b25d4368 30 def getdata(self):
d1ea2946 31 return self.conn.read()
a4eacae2 32
b25d4368 33 def parse(self, line):
34 pieces = line.split()
a4eacae2 35
d1ea2946 36 if not self.conn.registered() and pieces[0] == "NOTICE":
e4a4c762 37 self.conn.register()
38 return
d1ea2946 39
e4a4c762 40 if self.parent.hasnumhook(pieces[1]):
41 hooks = self.parent.getnumhook(pieces[1])
42 for callback in hooks:
43 callback(self, line)
44
45 if pieces[1] == "001":
d1ea2946 46 self.conn.registered(True)
47 for c in self.chans:
5477b368 48 self.join(c.name)
d1ea2946 49
50 elif pieces[1] == "PRIVMSG":
49a455aa 51 nick = pieces[0].split('!')[0][1:]
52 user = self.parent.user(nick)
839d2b35 53 target = pieces[2]
49a455aa 54 msg = ' '.join(pieces[3:])[1:]
839d2b35 55 self.parsemsg(user, target, msg)
a4eacae2 56
49a455aa 57 elif pieces[0] == "PING":
58 self.conn.send("PONG %s" % (pieces[1]))
a4eacae2 59
b2a896c8 60 elif pieces[1] == "354": # WHOX
61 qt = pieces[3]
62 nick = pieces[4]
63 auth = pieces[5]
64 if auth != '0':
65 self.parent.user(nick).authed(auth)
66
49a455aa 67 elif pieces[1] == "JOIN":
68 nick = pieces[0].split('!')[0][1:]
b2a896c8 69 chan = self.parent.channel(pieces[2])
70
71 if nick == self.nick:
72 self.conn.send("WHO %s %%ant,1" % (chan))
73 else:
8af0407d 74 user = self.parent.user(nick, justjoined=True)
5477b368 75 chan.userjoin(user)
76 user.join(chan)
49a455aa 77
839d2b35 78 def parsemsg(self, user, target, msg):
79 chan = None
877cd61d 80 if len(msg) == 0:
81 return
82
83 triggerused = msg[0] == self.parent.trigger
839d2b35 84 if triggerused: msg = msg[1:]
49a455aa 85 pieces = msg.split()
839d2b35 86
87 if target == self.nick:
d1ea2946 88 if len(pieces) > 1:
89 chanword = pieces[1]
90 if chanword[0] == '#':
91 chan = self.parent.channel(chanword)
92 pieces.pop(1)
839d2b35 93
94 else: # message was sent to a channel
95 chan = self.parent.channel(target) #TODO check if bot's on channel --- in Erebus.channel() maybe?
90b64dc0
CS
96 try:
97 if msg[0] == '*': # message may be addressed to bot by "*BOTNICK" trigger?
98 if pieces[0][1:].lower() == self.nick.lower():
99 pieces.pop(0) # command actually starts with next word
100 msg = ' '.join(pieces) # command actually starts with next word
101 elif not triggerused:
102 return # not to bot, don't process!
103 except IndexError:
104 return # Fix if you feel like it /BiohZn
839d2b35 105
db50981b 106 cmd = pieces[0].lower()
a4eacae2 107
db50981b 108 if self.parent.hashook(cmd):
e4a4c762 109 for callback in self.parent.gethook(cmd):
110 if chan is None and callback.needchan:
111 self.msg(user, "You need to specify a channel for that command.")
586997a7 112 elif user.glevel >= callback.reqglevel and (not callback.needchan or chan.levelof(user.auth) >= callback.reqclevel):
e4a4c762 113 cbret = callback(self, user, chan, target, *pieces[1:])
114 if cbret is NotImplemented:
115 self.msg(user, "Command not implemented.")
6b2c681d 116 else:
586997a7 117 self.msg(user, "No such command.")
49a455aa 118
119 def msg(self, target, msg):
120 if isinstance(target, self.parent.User): self.conn.send("NOTICE %s :%s" % (target.nick, msg))
121 elif isinstance(target, self.parent.Channel): self.conn.send("PRIVMSG %s :%s" % (target.name, msg))
122 elif isinstance(target, basestring):
123 if target[0] == '#': self.conn.send("PRIVMSG %s :%s" % (target, msg))
124 else: self.conn.send("NOTICE %s :%s" % (target, msg))
125 else: raise TypeError('Bot.msg() "target" must be Erebus.User, Erebus.Channel, or string')
a4eacae2 126
49a455aa 127 def join(self, chan):
128 self.conn.send("JOIN %s" % (chan))
a4eacae2 129
49a455aa 130 def part(self, chan):
131 self.conn.send("PART %s" % (chan))
a4eacae2 132
49a455aa 133 def quit(self, reason="Shutdown"):
134 self.conn.send("QUIT :%s" % (reason))
b25d4368 135
a12f7519 136 def __str__(self): return self.nick
137 def __repr__(self): return "<Bot %r>" % (self.nick)
138
b25d4368 139class BotConnection(object):
140 state = 0 # 0=disconnected, 1=registering, 2=connected
141
a12f7519 142 def __init__(self, parent, bind, server, port):
b25d4368 143 self.parent = parent
144 self.buffer = ''
145 self.socket = None
146
b25d4368 147 self.bind = bind
148 self.server = server
149 self.port = int(port)
b25d4368 150
151 def connect(self):
152 self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
153 self.socket.bind((self.bind, 0))
154 self.socket.connect((self.server, self.port))
d1ea2946 155 return True
156 def register(self):
157 if self.state == 0:
158 self.send("NICK %s" % (self.parent.nick))
159 self.send("USER %s 0 * :%s" % (self.parent.user, self.parent.realname))
160 self.state = 1
49a455aa 161 return True
b25d4368 162
163 def registered(self, done=False):
164 if done: self.state = 2
165 return self.state == 2
166
b25d4368 167 #TODO: rewrite send() to queue
168 def send(self, line):
381f9fc4 169 print self.parent.nick, '[O]', str(line)
b25d4368 170 self.write(line)
a4eacae2 171
b25d4368 172 def write(self, line):
b25d4368 173 self.socket.sendall(line+"\r\n")
a4eacae2 174
b25d4368 175 def read(self):
176 self.buffer += self.socket.recv(8192)
177 lines = []
a4eacae2 178
b25d4368 179 while '\r\n' in self.buffer:
180 pieces = self.buffer.split('\r\n', 1)
d1ea2946 181 print self.parent.nick, '[I]', pieces[0]
b25d4368 182 lines.append(pieces[0])
183 self.buffer = pieces[1]
a4eacae2 184
b25d4368 185 return lines
a12f7519 186
187 def __str__(self): return self.nick
188 def __repr__(self): return "<BotConnection %r (%r)>" % (self.socket.fileno(), self.parent.nick)