Protect against empty privmsgs
[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 email_log(to_address, subject, logfile, aliases):
13     email_addresses = []
14     unrecognized = []
15     for a in to_address.split(','):
16         if '@' in a:
17             email_addresses.append(a)
18         elif a in aliases:
19             email_addresses.append(aliases[a])
20         elif a:
21             unrecognized.append(a)
22     if email_addresses:
23         header = '''From: %(from_address)s
24 To: %(to_address)s
25 Subject: %(subject)s
26
27 ''' % {
28     'from_address': config.FROM_ADDRESS,
29     'to_address': ','.join(email_addresses),
30     'subject': subject,
31 }
32         msg = header + open(logfile).read()
33         s = smtplib.SMTP(config.MTA)
34         s.sendmail(config.FROM_ADDRESS, email_addresses, msg)
35     return unrecognized
36
37 def get_time():
38     return '%s-%02d-%02d %02d:%02d' % time.gmtime()[:5]
39
40 def make_log(channel):
41     (year, month, day, hour, minute) = time.gmtime()[:5]
42     return tempfile.mkstemp(
43             suffix='.log',
44             prefix='%s-%s%02d%02d.%02d%02d-' % (channel, year, month, day, hour, minute),
45             dir=config.LOG_DIR)[1]
46
47 def do_log(logs, target, nick, msg):
48     if target in logs:
49         log = logs[target]
50         log['fileobj'].write('%s <%s> %s\n' % (get_time(), nick, msg))