Initial checkin
[people/stefanha/gpxebot.git] / utils.py
1 import smtplib
2 import tempfile
3 import time
4 import sys
5
6 import config
7
8 def dbg(msg):
9     if config.DEBUG:
10         sys.stderr.write(msg + '\n')
11
12 def nick_from_mask(mask):
13     return (mask.find('!') > -1 and mask.split('!', 1)[0]) or mask
14
15 def email_log(to_address, channel, logfile, aliases):
16     email_addresses = []
17     unrecognized = []
18     for a in to_address.split(','):
19         if '@' in a:
20             email_addresses.append(a)
21         elif a in aliases:
22             email_addresses.append(aliases[a])
23         else:
24             unrecognized.append(a)
25     if email_addresses:
26         header = '''From: %(from_address)s
27 To: %(to_address)s
28 Subject: irc %(channel)s log
29
30 ''' % {'from_address': config.FROM_ADDRESS,
31             'to_address': ','.join(email_addresses),
32             'channel': channel,
33             }
34         msg = header + open(logfile).read()
35         s = smtplib.SMTP(config.MTA)
36         s.sendmail(config.FROM_ADDRESS, email_addresses, msg)
37     return unrecognized
38
39 def get_time():
40     return '%s-%02d-%02d %02d:%02d' % time.gmtime()[:5]
41
42 def make_log(channel):
43     (year, month, day, hour, minute) = time.gmtime()[:5]
44     return tempfile.mkstemp(
45             suffix='.log',
46             prefix='%s-%s%02d%02d.%02d%02d-' % (channel, year, month, day, hour, minute),
47             dir=config.LOG_DIR)[1]
48
49 def do_log(logs, target, nick, msg):
50     if target in logs:
51         (name, f) = logs[target]
52         f.write('%s <%s> %s\n' % (get_time(), nick_from_mask(nick), msg))