-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathircloggerd
executable file
·365 lines (311 loc) · 12.2 KB
/
ircloggerd
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
#!/usr/bin/python2
VERSION = """IRC Logger python bot v1.15, http://colas.nahaboo.net/Software/IrcLogger"""
# irclogger server nickname logsdir url [start_channels...]
# if args are "." they are replaced by default values
#=============================================================================
# Main config stuff
NickNameDef = '[LOGGER]'
_logsdirDef = "/var/log/irclogger"
_urlDef = "http://localhost"
# help texts
_doc = VERSION + """
Author: Colas Nahaboo, 2003. License GPL 2.
Bot adapted from code by Sean B. Palmer, deltab
Uses ircAsyncD.py by Dan Connolly
This simple bot aims to do only one thing: log in MIRC-format various channels
on a server. Bot can be controlled by users.
Usage: irclogger server[:port] nickname logsdir url [start_channels...]
if args are "." they are replaced by default values
"""
_help = """<HELP>
""" + VERSION + """
* Invite bot to log a channel by inviting it
e.g.: in the channel you want to log: /INVITE LOGGER
or talk directly to it, and give command:
LOG #CHANNEL [KEY]
LOG can be also GO, ON, START (case insensitive)
* [off] at the start of a line prevents the line to be logged
* To stop logging a channel, type in it: LOGGER: OFF or LOGGER, OFF
OFF can be also QUIT, STOP, EXIT (case insensitive)
* Logs are at: LOGSURL
</HELP>"""
_on = """| Starting logging this channel %s - See logs at %s - Lines beginning with "[off]" will not be logged - You can stop logging by typing LOGGER: off"""
_off = """| Stopping logging this channel %s - See logs at %s - You can re-enable log by inviting me back, e.g: /INVITE LOGGER - or telling me in a private message: LOG #CHANNEL [KEY]"""
_logAck = """Ok, joining channel %s to log it."""
#-----------------------------------------------------------------------------
# no need to modify below
TimeStamp = 1 # 1 for yes, 0 for no
_text = "<%s> %s"
_action = "* %s %s"
_join = "*** %s has joined %s"
_part = "*** %s has left %s"
_kick = "*** %s was kicked by %s (%s)"
_mode = "*** %s sets mode: %s"
_topic = "*** %s changes topic to: %s"
_quit = "*** %s has quit IRC (%s)"
_nick = "*** %s is now known as %s"
_session = "*** %s %s logging %s at %s"
_logfilename = "%Y-%m-%d,%a.log"
_logchannels = "CHANNELS.last"
_channelsallow = "CHANNELS.allow"
_pingDelay = 60
_loopDelay = 30.0
# End of main config stuff
#=============================================================================
import ircAsyncD
from ircAsyncD import debug
import signal
import re, os, os.path, sys, base64, socket, urllib, time, asyncore, string
from re import match
from ircAsyncD import PRIVMSG, NOTICE, PING, PONG, USER
from ircAsyncD import NICK, JOIN, PART, INVITE, QUIT
from ircAsyncD import SPC, CR, LF, CRLF, RPL_WELCOME
def ctcp(s): return '\x01%s\x01' % s
def me(s): return ctcp('ACTION %s' % s)
global people
people = {}
global channels
channels = [] # channels that this bot's on
global directories, commandRe, nicknameRe, offRe, onRe
directories = []
offRe = re.compile(" *(off|quit|stop|exit)", re.I)
onRe = re.compile(" *(log|go|on|start) +((#?[^ ]+)( *([^ ]+))?)", re.I)
offPrefix = re.compile("^[^ ]+ [[]off[]]", re.I)
#-----------------------------------------------------------------------------
def log(channelname, text):
fn = time.strftime(_logfilename, time.gmtime(time.time()))
# some bogus server messages may end with bot name as channel, ignore
if channelname == NickName:
return
# channels are #-prefixed, but we store in dirs without the prefix
channel = channelname.lower()
if channel not in directories:
# if it fails, the exception may as well be raised
os.mkdir(os.path.join(_logsdir, channel[1:]))
directories.append(channel)
if TimeStamp:
t = time.strftime('[%H:%M]', time.gmtime(time.time()))
text = t + ' ' + text
text += '\n'
open(os.path.join(_logsdir, channel[1:], fn), 'a').write(text)
# must be called after each change to var channels
def logChannels():
if len(channels) > 0:
channelslist = reduce(spaceConcat, map(trimSharp, channels)).lower()
else:
channelslist = ''
open(os.path.join(_logsdir, _logchannels), 'w').write(channelslist)
def allowedChannel(channel):
try:
allowed = open(_channelsallow, 'r')
if channel not in allowed.read().split(' '):
return 0
else: return 1
except IOError: pass
return 0
def globalsubstitute(input_string,from_string,to_string):
splitlist = string.splitfields(input_string,from_string)
return string.joinfields(splitlist,to_string)
def interpretMsg(m, origin, args, text, c):
on = re.match(onRe, text)
if on: # we are told to join a channel
help = string.replace(_logAck, 'LOGGER', NickName) % on.group(3)
for line in help.split('\n'):
c.todo([PRIVMSG, origin, ":", line])
newchan = on.group(2)
if re.match("[^#]", newchan): newchan = "#" + newchan
c.todo([JOIN, newchan])
else:
help = string.replace(_help, 'LOGGER', NickName)
help = string.replace(help, 'LOGSURL', _url)
for line in help.split('\n'):
c.todo([PRIVMSG, origin, ":", line])
def logOnMsg(channel, c):
on = string.replace(_on % (channel, _url), 'LOGGER', NickName)
for line in on.split('\n'):
c.todo([PRIVMSG, channel, ":", line])
def logOffMsg(channel, c):
off = string.replace(_off % (channel, _url), 'LOGGER', NickName)
for line in off.split('\n'):
c.todo([PRIVMSG, channel, ":", line])
def channelCommand(channel, command, c):
if re.match(offRe, command):
partChannel(channel, c)
def partChannel(channel, c):
logOffMsg(channel, c)
c.todo([PART, channel])
def tick(c):
if time.time() > (c.lastTickTime + _pingDelay):
c.lastTickTime = time.time()
c.todo([PING, NickName])
# we redefine here asyncore's loop to fire a timer on tick
def loop (c):
map=asyncore.socket_map
while map:
asyncore.poll (_loopDelay, map)
tick(c)
def exit_handler(signal, frame):
t = time.strftime('%a %b %d %H:%M:%S %Y', time.gmtime(time.time()))
for channel in channels:
log(channel, _session % (NickName, 'stops', channel, t))
sys.exit(0)
def spaceConcat(string1, string2):
return string1 + ' ' + string2
def trimSharp(string): return string[1:]
#-----------------------------------------------------------------------------
def main(hostName, port, chan):
c = ircAsyncD.T()
c.startChannels(chan)
c.nick = NickName
c.userid = 'logger'
c.lastTickTime = time.time()
# Put any new functions here
def hi(m, origin, args, text, c=c):
c.tell(args[1], 'hi, %s' % origin.split('!')[0])
c.bind(hi, PRIVMSG, r"(?i)^(Hi|Hey|welcome)(,)? %s(\!)?$" % NickName)
def logText(m, origin, args, text, c=c):
channel = args[1]
nick = origin
if '!' in origin: nick = origin.split('!')[0]
if re.match(nicknameRe, channel):
interpretMsg(m, nick, args, text, c)
return
else:
mo = re.match(commandRe, text)
if mo: channelCommand(channel, mo.group(1), c)
if not (text.startswith('\x01ACTION ') and text.endswith('\x01')):
text = _text % (nick, text)
else: text = _action % (nick, text[8:-1])
try:
if not re.match(offPrefix, text):
log(channel, text)
except ValueError: log(channel, text)
c.bind(logText, PRIVMSG, r"(.*)")
def logTopic(m, origin, args, text, c=c):
channel = args[1]
nick = origin
if '!' in origin: nick = origin.split('!')[0]
topic = _topic % (nick, text)
log(channel, topic)
c.bind(logTopic, 'TOPIC', r"(.*)")
def logMode(m, origin, args, text, c=c):
channel = args[1]
nick = origin
if '!' in origin: nick = origin.split('!')[0]
mode = _mode % (nick, ' '.join(args[2:]))
log(channel, mode)
c.bind(logMode, 'MODE', r"(.*)")
def logJoin(m, origin, args, text, c=c):
channel = text
nick = origin
if '!' in origin: nick = origin.split('!')[0]
if nick == NickName:
if channel not in channels:
if allowedChannel(channel):
channels.append(channel)
logChannels()
t = time.strftime('%a %b %d %H:%M:%S %Y', time.gmtime(time.time()))
log(channel, _session % (NickName, 'starts', channel, t))
logOnMsg(channel, c)
join = _join % (nick, channel)
log(channel, join)
if people.has_key(nick):
if channel not in people[nick]:
people[nick].append(channel)
else: people[nick] = [channel]
c.bind(logJoin, 'JOIN', r"(.*)")
def logNames(m, origin, args, text, c=c):
channel = args[3]
raw_nicks = text.split(' ')
for nick in raw_nicks:
if nick.startswith('@') or nick.startswith('+'):
nick = nick[1:]
if people.has_key(nick):
if channel not in people[nick]:
people[nick].append(channel)
else: people[nick] = [channel]
c.bind(logNames, '353', r"(.*)")
def logPart(m, origin, args, text, c=c):
if len(args) > 1:
channel = args[1]
else:
channel = text
nick = origin
if '!' in origin: nick = origin.split('!')[0]
part = _part % (nick, text)
log(channel, part)
if nick == NickName:
if channel in channels:
channels.remove(channel)
logChannels()
try: people[nick].remove(channel)
except:
print >> sys.stderr, "Something messed up, but it doesn't matter, for ", nick, " parting from ", channel
c.bind(logPart, 'PART', r"(.*)")
def logQuit(m, origin, args, text, c=c):
nick = origin
if '!' in origin: nick = origin.split('!')[0]
quit = _quit % (nick, text)
if people.has_key(nick):
for channel in people[nick]: log(channel, quit)
del people[nick]
c.bind(logQuit, 'QUIT', r"(.*)")
def logKick(m, origin, args, text, c=c):
channel = args[1]
nick = origin
if '!' in origin: nick = origin.split('!')[0]
kickee = args[2]
kick = _kick % (kickee, nick, text)
log(channel, kick)
if kickee == NickName:
if channel in channels:
channels.remove(channel)
logChannels()
try: people[kickee].remove(channel)
except:
print >> sys.stderr, "Something messed up, but it doesn't matter, for ", kickee, " kicked from ", channel
c.bind(logKick, 'KICK', r"(.*)")
def logNick(m, origin, args, text, c=c):
old = origin
if '!' in origin: old = origin.split('!')[0]
new = text
nick = _nick % (old, new)
if people.has_key(old):
for channel in people[old]: log(channel, nick)
people[new] = people[old]
del people[old]
c.bind(logNick, 'NICK', r"(.*)")
def logInvite(m, origin, args, text, c=c):
c.todo([JOIN, text])
c.bind(logInvite, 'INVITE', r"(.*)")
# inits
if not os.access(_logsdir, os.W_OK): os.makedirs(_logsdir)
for entry in os.listdir(_logsdir):
if os.path.isdir(os.path.join(_logsdir, entry)):
lentry = entry.lower()
if lentry == entry: # ignore non-lowercase dirs
if lentry not in directories:
directories.append('#' + lentry)
c.makeConn(hostName, port)
try: loop(c)
except:
exit_handler(signal.SIGHUP, 0)
signal.signal(signal.SIGTERM, exit_handler)
signal.signal(signal.SIGINT, exit_handler)
#-----------------------------------------------------------------------------
if __name__=='__main__':
if len(sys.argv) > 4:
server, NickName, _logsdir, _url, chans = sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5:]
if server == '.': server = 'localhost'
if NickName == '.': NickName = NickNameDef
if _logsdir == '.': _logsdir = _logsdirDef
if _url == '.': _url = _urlDef
chans = [('#%s' % c, c)[c.startswith('#')] for c in chans]
if ':' in server: server, port = server.split(':')
else: port = '6667'
# NickNameQ is the re-quoted form of NickName for comparisons
NickNameQ = re.sub("([][*+])", '[\\1]', NickName)
nicknameRe = re.compile(NickNameQ, re.I)
commandRe = re.compile(NickNameQ + '[,:]? *(.*)', re.I)
main(server, int(port), chans)
else: print sys.argv; print _doc