Skip to content

Commit

Permalink
implement python 3 compatibility
Browse files Browse the repository at this point in the history
  • Loading branch information
imnotjames committed Aug 8, 2018
1 parent 19dc5ea commit 960e8b6
Show file tree
Hide file tree
Showing 32 changed files with 194 additions and 158 deletions.
18 changes: 9 additions & 9 deletions bot.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
#!/usr/bin/env python

import os
import Queue
import queue
import sys
import traceback
import time
Expand All @@ -21,38 +21,38 @@ def main():
sys.path += ['lib']
os.chdir(os.path.dirname(__file__) or '.') # do stuff relative to the install directory

print 'Loading plugins'
print('Loading plugins')

# bootstrap the reloader
eval(compile(open(os.path.join('core', 'reload.py'), 'U').read(),
os.path.join('core', 'reload.py'), 'exec'),
globals())
reload(init=True)

print 'Connecting to IRC'
print('Connecting to IRC')

try:
config()
if not hasattr(bot, 'config'):
exit()
except Exception, e:
print 'ERROR: malformed config file:', e
except Exception as e:
print('ERROR: malformed config file:', e)
traceback.print_exc()
sys.exit()

print 'Running main loop'
print('Running main loop')

while True:
reload() # these functions only do things
config() # if changes have occured

for conn in bot.conns.itervalues():
for conn in bot.conns.values():
try:
out = conn.out.get_nowait()
main(conn, out)
except Queue.Empty:
except queue.Empty:
pass
while all(conn.out.empty() for conn in bot.conns.itervalues()):
while all(conn.out.empty() for conn in iter(bot.conns.values())):
time.sleep(.1)

if __name__ == '__main__':
Expand Down
6 changes: 3 additions & 3 deletions core/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,16 +51,16 @@ def config():
try:
bot.config = json.load(open(find_config()))
bot._config_mtime = config_mtime
for name, conf in bot.config['connections'].iteritems():
for name, conf in bot.config['connections'].items():
if name in bot.conns:
bot.conns[name].set_conf(conf)
else:
if conf.get('ssl'):
bot.conns[name] = SSLIRC(conf)
else:
bot.conns[name] = IRC(conf)
except ValueError, e:
print 'ERROR: malformed config!', e
except ValueError as e:
print('ERROR: malformed config!', e)


bot._config_mtime = 0
30 changes: 15 additions & 15 deletions core/irc.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import re
import socket
import time
import thread
import Queue
import _thread
import queue

from ssl import wrap_socket, CERT_NONE, CERT_REQUIRED, SSLError

Expand All @@ -20,7 +20,7 @@ def censor(text):
text = text.replace('\n', '').replace('\r', '')
replacement = '[censored]'
if 'censored_strings' in bot.config:
words = map(re.escape, bot.config['censored_strings'])
words = list(map(re.escape, bot.config['censored_strings']))
regex = re.compile('(%s)' % "|".join(words))
text = regex.sub(replacement, text)
return text
Expand All @@ -33,8 +33,8 @@ class crlf_tcp(object):
def __init__(self, host, port, timeout=300):
self.ibuffer = ""
self.obuffer = ""
self.oqueue = Queue.Queue() # lines to be sent out
self.iqueue = Queue.Queue() # lines that were received
self.oqueue = queue.Queue() # lines to be sent out
self.iqueue = queue.Queue() # lines that were received
self.socket = self.create_socket()
self.host = host
self.port = port
Expand All @@ -48,12 +48,12 @@ def run(self):
try:
self.socket.connect((self.host, self.port))
except socket.timeout:
print 'timed out connecting to %s:%s' % (self.host, self.port)
print('timed out connecting to %s:%s' % (self.host, self.port))
time.sleep(60)
else:
break
thread.start_new_thread(self.recv_loop, ())
thread.start_new_thread(self.send_loop, ())
_thread.start_new_thread(self.recv_loop, ())
_thread.start_new_thread(self.send_loop, ())

def recv_from_socket(self, nbytes):
return self.socket.recv(nbytes)
Expand Down Expand Up @@ -94,7 +94,7 @@ def recv_loop(self):
def send_loop(self):
while True:
line = self.oqueue.get().splitlines()[0][:500]
print ">>> %r" % line
print(">>> %s" % line)
self.obuffer += line.encode('utf-8', 'replace') + '\r\n'
while self.obuffer:
sent = self.socket.send(self.obuffer)
Expand Down Expand Up @@ -158,12 +158,12 @@ def __init__(self, conf):
self.conn = None
self.set_conf(conf)

self.out = Queue.Queue() # responses from the server are placed here
self.out = queue.Queue() # responses from the server are placed here
# format: [rawline, prefix, command, params,
# nick, user, host, paramlist, msg]
self.connect()

thread.start_new_thread(self.parse_loop, ())
_thread.start_new_thread(self.parse_loop, ())

def set_conf(self, conf):
self.conf = conf
Expand All @@ -177,7 +177,7 @@ def create_connection(self):

def connect(self):
self.conn = self.create_connection()
thread.start_new_thread(self.conn.run, ())
_thread.start_new_thread(self.conn.run, ())
self.cmd("NICK", [self.nick])
self.cmd("USER",
[self.conf.get('user', 'skybot'), "3", "*", self.conf.get('realname',
Expand Down Expand Up @@ -237,18 +237,18 @@ class FakeIRC(IRC):

def __init__(self, conf):
self.set_conf(conf)
self.out = Queue.Queue() # responses from the server are placed here
self.out = queue.Queue() # responses from the server are placed here

self.f = open(fn, 'rb')

thread.start_new_thread(self.parse_loop, ())
_thread.start_new_thread(self.parse_loop, ())

def parse_loop(self):
while True:
msg = decode(self.f.readline()[9:])

if msg == '':
print "!!!!DONE READING FILE!!!!"
print("!!!!DONE READING FILE!!!!")
return

if msg.startswith(":"): # has a prefix
Expand Down
22 changes: 12 additions & 10 deletions core/main.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
from __future__ import print_function
import re
import thread
import _thread
import traceback
from queue import Queue
from future.builtins import str


thread.stack_size(1024 * 512) # reduce vm size
_thread.stack_size(1024 * 512) # reduce vm size


class Input(dict):
Expand Down Expand Up @@ -80,14 +82,14 @@ def run(func, input):
else:
out = func(input.inp)
if out is not None:
input.reply(unicode(out))
input.reply(str(out))


def do_sieve(sieve, bot, input, func, type, args):
try:
return sieve(bot, input, func, type, args)
except Exception:
print 'sieve error',
print('sieve error', end=' ')
traceback.print_exc()
return None

Expand All @@ -98,8 +100,8 @@ class Handler(object):

def __init__(self, func):
self.func = func
self.input_queue = Queue.Queue()
thread.start_new_thread(self.start, ())
self.input_queue = Queue()
_thread.start_new_thread(self.start, ())

def start(self):
uses_db = 'db' in self.func._args
Expand Down Expand Up @@ -150,14 +152,14 @@ def dispatch(input, kind, func, args, autohelp=False):
if func._thread:
bot.threads[func].put(input)
else:
thread.start_new_thread(run, (func, input))
_thread.start_new_thread(run, (func, input))


def match_command(command):
commands = list(bot.commands)

# do some fuzzy matching
prefix = filter(lambda x: x.startswith(command), commands)
prefix = [x for x in commands if x.startswith(command)]
if len(prefix) == 1:
return prefix[0]
elif prefix and command not in prefix:
Expand All @@ -179,7 +181,7 @@ def test_make_command_re():
match = make_command_re('.', False, 'bot').match
assert not match('foo')
assert not match('bot foo')
for _ in xrange(2):
for _ in range(2):
assert match('.test').groups() == ('test', '')
assert match('bot: foo args').groups() == ('foo', 'args')
match = make_command_re('.', True, 'bot').match
Expand Down
44 changes: 23 additions & 21 deletions core/reload.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from __future__ import print_function

import collections
import glob
import os
Expand All @@ -14,7 +16,7 @@


def make_signature(f):
return f.func_code.co_filename, f.func_name, f.func_code.co_firstlineno
return f.__code__.co_filename, f.__name__, f.__code__.co_firstlineno


def format_plug(plug, kind='', lpad=0, width=40):
Expand Down Expand Up @@ -63,14 +65,14 @@ def reload(init=False):
fileset = set(glob.glob(os.path.join('plugins', '*.py')))

# remove deleted/moved plugins
for name, data in bot.plugs.iteritems():
for name, data in bot.plugs.items():
bot.plugs[name] = [x for x in data if x[0]._filename in fileset]

for filename in list(mtimes):
if filename not in fileset and filename not in core_fileset:
mtimes.pop(filename)

for func, handler in list(bot.threads.iteritems()):
for func, handler in list(bot.threads.items()):
if func._filename not in fileset:
handler.stop()
del bot.threads[func]
Expand All @@ -92,16 +94,16 @@ def reload(init=False):
continue

# remove plugins already loaded from this filename
for name, data in bot.plugs.iteritems():
for name, data in bot.plugs.items():
bot.plugs[name] = [x for x in data
if x[0]._filename != filename]

for func, handler in list(bot.threads.iteritems()):
for func, handler in list(bot.threads.items()):
if func._filename == filename:
handler.stop()
del bot.threads[func]

for obj in namespace.itervalues():
for obj in namespace.values():
if hasattr(obj, '_hook'): # check for magic
if obj._thread:
bot.threads[obj] = Handler(obj)
Expand All @@ -110,21 +112,21 @@ def reload(init=False):
bot.plugs[type] += [data]

if not init:
print '### new plugin (type: %s) loaded:' % \
type, format_plug(data)
print('### new plugin (type: %s) loaded:' % \
type, format_plug(data))

if changed:
bot.commands = {}
for plug in bot.plugs['command']:
name = plug[1]['name'].lower()
if not re.match(r'^\w+$', name):
print '### ERROR: invalid command name "%s" (%s)' % (name,
format_plug(plug))
print('### ERROR: invalid command name "%s" (%s)' % (name,
format_plug(plug)))
continue
if name in bot.commands:
print "### ERROR: command '%s' already registered (%s, %s)" % \
print("### ERROR: command '%s' already registered (%s, %s)" % \
(name, format_plug(bot.commands[name]),
format_plug(plug))
format_plug(plug)))
continue
bot.commands[name] = plug

Expand All @@ -134,28 +136,28 @@ def reload(init=False):
bot.events[event].append((func, args))

if init:
print ' plugin listing:'
print(' plugin listing:')

if bot.commands:
# hack to make commands with multiple aliases
# print nicely

print ' command:'
print(' command:')
commands = collections.defaultdict(list)

for name, (func, args) in bot.commands.iteritems():
for name, (func, args) in bot.commands.items():
commands[make_signature(func)].append(name)

for sig, names in sorted(commands.iteritems()):
for sig, names in sorted(commands.items()):
names.sort(key=lambda x: (-len(x), x)) # long names first
out = ' ' * 6 + '%s:%s:%s' % sig
out += ' ' * (50 - len(out)) + ', '.join(names)
print out
print(out)

for kind, plugs in sorted(bot.plugs.iteritems()):
for kind, plugs in sorted(bot.plugs.items()):
if kind == 'command':
continue
print ' %s:' % kind
print(' %s:' % kind)
for plug in plugs:
print format_plug(plug, kind=kind, lpad=6)
print
print(format_plug(plug, kind=kind, lpad=6))
print()
9 changes: 7 additions & 2 deletions plugins/crypto.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,11 @@ def crypto(inp, say=None):

values = price_response["DISPLAY"][fsym]["USD"]

say(u"USD/{FROMSYMBOL}: \x0307{PRICE}\x0f - High: \x0307{HIGHDAY}\x0f - Low: \x0307{LOWDAY}\x0f - Volume: {VOLUMEDAY}"
" ({VOLUMEDAYTO}) - Total Supply: {SUPPLY} - MktCap: {MKTCAP}".format(**values))
say(
(
u"USD/{FROMSYMBOL}: \x0307{PRICE}\x0f - High: \x0307{HIGHDAY}\x0f "
u"- Low: \x0307{LOWDAY}\x0f - Volume: {VOLUMEDAY}"
u" ({VOLUMEDAYTO}) - Total Supply: {SUPPLY} - MktCap: {MKTCAP}"
).format(**values)
)

Loading

0 comments on commit 960e8b6

Please sign in to comment.