Python 3 Start

This commit is contained in:
Luke Rogers 2014-03-06 11:45:00 +13:00
parent 9f029c8ceb
commit 141fe8d80c
67 changed files with 264 additions and 274 deletions

View file

@ -2,7 +2,7 @@ import time
import logging
import re
import os
import Queue
import queue
import collections
import threading
@ -60,11 +60,11 @@ class Bot(threading.Thread):
# start IRC connections
self.connect()
print self.connections
print(self.connections)
for conn in self.connections:
conn.permissions = PermissionManager(self, conn)
print conn
print(conn)
# run plugin loader
self.plugins = collections.defaultdict(list)
@ -82,11 +82,11 @@ class Bot(threading.Thread):
try:
incoming = conn.parsed_queue.get_nowait()
if incoming == StopIteration:
print "StopIteration"
print("StopIteration")
# IRC engine has signalled timeout, so reconnect (ugly)
conn.connection.reconnect()
main.main(self, conn, incoming)
except Queue.Empty:
except queue.Empty:
pass
# if no messages are in the incoming queue, sleep

View file

@ -26,9 +26,9 @@ class Config(dict):
if not os.path.exists(self.path):
# if there is no config, show an error and die
self.logger.critical("No config file found, bot shutting down!")
print "No config file found! Bot shutting down in five seconds."
print "Copy 'config.default' to 'config.json' for defaults."
print "For help, see http://git.io/cloudbotirc. Thank you for using CloudBot!"
print("No config file found! Bot shutting down in five seconds.")
print("Copy 'config.default' to 'config.json' for defaults.")
print("For help, see http://git.io/cloudbotirc. Thank you for using CloudBot!")
time.sleep(5)
sys.exit()

View file

@ -1,6 +1,6 @@
import os
import sqlite3
import thread
import _thread
threaddbs = {}
@ -11,7 +11,7 @@ def get_db_connection(conn, name=''):
if not name:
name = '{}.db'.format(conn.name)
threadid = thread.get_ident()
threadid = _thread.get_ident()
if name in threaddbs and threadid in threaddbs[name]:
return threaddbs[name][threadid]
filename = os.path.join(bot.data_dir, name)

View file

@ -2,7 +2,7 @@ import re
import socket
import time
import threading
import Queue
import queue
from core import permissions
@ -30,7 +30,7 @@ def censor(text):
class ReceiveThread(threading.Thread):
"""receives messages from IRC and puts them in the input_queue"""
def __init__(self, sock, input_queue, timeout):
self.input_buffer = ""
self.input_buffer = b""
self.input_queue = input_queue
self.socket = sock
self.timeout = timeout
@ -70,8 +70,9 @@ class ReceiveThread(threading.Thread):
return
continue
while '\r\n' in self.input_buffer:
line, self.input_buffer = self.input_buffer.split('\r\n', 1)
while b'\r\n' in self.input_buffer:
line, self.input_buffer = self.input_buffer.split(b'\r\n', 1)
print(decode(line))
self.input_queue.put(decode(line))
@ -95,7 +96,7 @@ class SSLReceiveThread(ReceiveThread):
class SendThread(threading.Thread):
"""sends messages from output_queue to IRC"""
def __init__(self, sock, conn_name, output_queue):
self.output_buffer = ""
self.output_buffer = b""
self.output_queue = output_queue
self.conn_name = conn_name
self.socket = sock
@ -106,7 +107,7 @@ class SendThread(threading.Thread):
def run(self):
while not self.shutdown:
line = self.output_queue.get().splitlines()[0][:500]
self.output_buffer += line.encode('utf-8', 'replace') + '\r\n'
self.output_buffer += line.encode('utf-8', 'replace') + b'\r\n'
while self.output_buffer:
sent = self.socket.send(self.output_buffer)
self.output_buffer = self.output_buffer[sent:]
@ -215,13 +216,13 @@ class IRC(object):
self.vars = {}
self.history = {}
self.parsed_queue = Queue.Queue() # responses from the server are placed here
self.parsed_queue = queue.Queue() # responses from the server are placed here
# format: [rawline, prefix, command, params,
# nick, user, host, paramlist, msg]
self.parsed_queue = Queue.Queue()
self.input_queue = Queue.Queue()
self.output_queue = Queue.Queue()
self.parsed_queue = queue.Queue()
self.input_queue = queue.Queue()
self.output_queue = queue.Queue()
# create the IRC connection and connect
self.connection = self.create_connection()
@ -270,19 +271,19 @@ class IRC(object):
def ctcp(self, target, ctcp_type, text):
""" makes the bot send a PRIVMSG CTCP to a target """
out = u"\x01{} {}\x01".format(ctcp_type, text)
out = "\x01{} {}\x01".format(ctcp_type, text)
self.cmd("PRIVMSG", [target, out])
def cmd(self, command, params=None):
if params:
params[-1] = u':' + params[-1]
self.send(u"{} {}".format(command, ' '.join(params)))
params[-1] = ':' + params[-1]
self.send("{} {}".format(command, ' '.join(params)))
else:
self.send(command)
def send(self, string):
try:
self.logger.info(u"{} >> {}".format(self.name.upper(), string))
self.logger.info("{} >> {}".format(self.name.upper(), string))
except:
# if this doesn't work, no big deal
pass

View file

@ -10,7 +10,7 @@ from core import main
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):
@ -71,19 +71,19 @@ class PluginLoader(object):
return
# remove plugins already loaded from this file
for name, data in self.bot.plugins.iteritems():
for name, data in self.bot.plugins.items():
self.bot.plugins[name] = [x for x in data
if x[0]._filename != filename]
# stop all currently running instances of the plugins from this file
for func, handler in list(self.bot.threads.iteritems()):
for func, handler in list(self.bot.threads.items()):
if func._filename == filename:
handler.stop()
del self.bot.threads[func]
# find objects with hooks in the plugin namespace
# TODO: kill it with fire, kill it all
for obj in namespace.itervalues():
for obj in namespace.values():
if hasattr(obj, '_hook'): # check for magic
if obj._thread:
self.bot.threads[obj] = main.Handler(self.bot, obj)
@ -104,11 +104,11 @@ class PluginLoader(object):
self.bot.logger.info("Unloading plugins from: {}".format(filename))
# remove plugins loaded from this file
for plugin_type, plugins in self.bot.plugins.iteritems():
for plugin_type, plugins in self.bot.plugins.items():
self.bot.plugins[plugin_type] = [x for x in plugins if x[0]._filename != filename]
# stop all currently running instances of the plugins from this file
for func, handler in list(self.bot.threads.iteritems()):
for func, handler in list(self.bot.threads.items()):
if func._filename == filename:
handler.stop()
del self.bot.threads[func]

View file

@ -1,11 +1,11 @@
import thread
import _thread
import traceback
import Queue
import queue
import re
from sqlalchemy.orm import scoped_session
thread.stack_size(1024 * 512) # reduce vm size
_thread.stack_size(1024 * 512) # reduce vm size
class Input(dict):
@ -25,7 +25,7 @@ class Input(dict):
if target == nick:
conn.msg(target, message)
else:
conn.msg(target, u"({}) {}".format(nick, message))
conn.msg(target, "({}) {}".format(nick, message))
def action(message, target=chan):
"""sends an action to the current channel/user or a specific channel/user"""
@ -76,7 +76,7 @@ def run(bot, func, input):
return
finally:
if uses_db:
print "Close"
print("Close")
input.db.close()
else:
kw = dict((key, input[key]) for key in args if key in input)
@ -96,7 +96,7 @@ def run(bot, func, input):
bot.logger.exception("Error in plugin {}:".format(func._filename))
return
if out is not None:
input.reply(unicode(out))
input.reply(str(out))
def do_sieve(sieve, bot, input, func, type, args):
@ -113,8 +113,8 @@ class Handler(object):
def __init__(self, bot, func):
self.func = func
self.bot = bot
self.input_queue = Queue.Queue()
thread.start_new_thread(self.start, ())
self.input_queue = queue.Queue()
_thread.start_new_thread(self.start, ())
def start(self):
uses_db = 'db' in self.func._args
@ -157,14 +157,14 @@ def dispatch(bot, input, kind, func, args, autohelp=False):
if func._thread:
bot.threads[func].put(input)
else:
thread.start_new_thread(run, (bot, func, input))
_thread.start_new_thread(run, (bot, func, input))
def match_command(bot, 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:

View file

@ -24,7 +24,7 @@ class PermissionManager(object):
self.logger.info("Reloading permissions for {}.".format(self.conn.name))
groups = self.conn.config.get("permissions", [])
# work out the permissions and users each group has
for key, value in groups.iteritems():
for key, value in groups.items():
self.group_perms[key] = []
self.group_users[key] = []
for permission in value["perms"]:
@ -32,7 +32,7 @@ class PermissionManager(object):
for user in value["users"]:
self.group_users[key].append(user)
for group, users in self.group_users.iteritems():
for group, users in self.group_users.items():
group_perms = self.group_perms[group]
for perm in group_perms:
self.perm_users[perm] = []