101 lines
2.8 KiB
Python
101 lines
2.8 KiB
Python
#!/usr/bin/env python3
|
|
|
|
import re
|
|
from subprocess import Popen, PIPE
|
|
import pickle
|
|
import pytz
|
|
from datetime import datetime
|
|
from sys import argv
|
|
|
|
def cmd(*args):
|
|
proc = Popen(args, stdout=PIPE)
|
|
while True:
|
|
line = proc.stdout.readline()
|
|
if line:
|
|
try:
|
|
yield str(line[:-1], 'utf-8', 'ignore')
|
|
except:
|
|
pass
|
|
else:
|
|
break
|
|
|
|
data_file = '/home/zgrep/offtopiabday/timezone-offtopia.pickle'
|
|
|
|
def get_data():
|
|
global data_file
|
|
with open(data_file, 'rb') as fh:
|
|
return pickle.load(fh)
|
|
|
|
def save_data(data):
|
|
global data_file
|
|
with open(data_file, 'wb') as fh:
|
|
return pickle.dump(data, fh)
|
|
|
|
def get_time(n):
|
|
nl = n.lower()
|
|
data = get_data()
|
|
if nl in data:
|
|
tz = data[nl]
|
|
return 'time(' + n + ') = ' + tz.fromutc(datetime.now()).strftime('%a, %Y-%m-%d %H:%M:%S %Z.')
|
|
return n + '.tz = undefined'
|
|
|
|
def set_tz(n, s):
|
|
data = get_data()
|
|
nl = n.lower()
|
|
try:
|
|
tz = pytz.timezone(s)
|
|
except pytz.exceptions.UnknownTimeZoneError:
|
|
if s.lower() in ('none', 'false', 'delete', '', 'undefined'):
|
|
if nl in data:
|
|
del data[nl]
|
|
save_data(data)
|
|
return n + '.tz = undefined'
|
|
return n + '.tz = undefined'
|
|
return 'tz(' + s + ') = InvalidTimezone'
|
|
except:
|
|
return 'ERR: NaN IS A NUMBER.'
|
|
data[nl] = tz
|
|
save_data(data)
|
|
return n + '.tz = ' + s + '; ' + get_time(n)
|
|
|
|
def main():
|
|
if len(argv) == 3:
|
|
print(get_time(argv[2]))
|
|
exit()
|
|
|
|
if len(argv) != 2:
|
|
print('Usage:', argv[0], '#channel')
|
|
exit(1)
|
|
|
|
chan = '/home/zgrep/offtopiabday/irc.freenode.net/' + argv[1]
|
|
|
|
for line in cmd('tail', '-n', '0', '-f', chan + '/out'):
|
|
date, time, nick, line = line.split(' ', 3)
|
|
nick = nick[1:-1]
|
|
if nick in ('happybot', 'hatebot', '!', '-!-'):
|
|
continue
|
|
m = re.match(r'(?:@?(?:happybot|hatebot)[:,]? )?tz ?= ?(.+)$', line)
|
|
if m:
|
|
reply = set_tz(nick, m.group(1))
|
|
with open(chan + '/in', 'w') as fh:
|
|
fh.write(reply + '\n')
|
|
continue
|
|
for i, (r, o) in enumerate((
|
|
(r'time\((\S+)\);?', True),
|
|
(r'\(time (\S+)\)', True),
|
|
(r'time\[(\S+)\];?', True),
|
|
(r'(\S+)\.time', True),
|
|
(r'time (\S+)', False)),
|
|
):
|
|
m = r'@?(?:happy|hate)(bot)[:,]? '
|
|
if o: m = r'(?:' + m + r')?'
|
|
m = re.match(m + r + r'$', line)
|
|
if m: break
|
|
if m:
|
|
reply = get_time(m.group(2))
|
|
with open(chan + '/in', 'w') as fh:
|
|
fh.write(nick + ': ' + reply + '\n')
|
|
continue
|
|
|
|
if __name__ == '__main__':
|
|
main()
|