Permalink
Browse files

inkblot to Python 3 (#718) - so far so good

git-svn-id: https://dev.upnl.org/svn/ircbot2/trunk@53 66f668a4-574d-4515-85ec-6e73d9c367eb
  • Loading branch information...
puzzlet committed Feb 24, 2010
1 parent a0d4377 commit b59be374968d2d7f574f943819a33897a0986f40
Showing with 339 additions and 289 deletions.
  1. +12 −6 BufferingBot.py
  2. +2 −2 config.py.sample
  3. +9 −9 inkblot.py
  4. +33 −36 ircbot.py
  5. +187 −142 irclib.py
  6. +44 −41 lib/whois.py
  7. +22 −24 plugins/interwiki.py
  8. +18 −17 plugins/ipw.py
  9. +12 −12 plugins/mathnet.py
View
@@ -23,8 +23,11 @@ def new_f(self, *args):
class Message():
def __init__(self, command, arguments, timestamp=None):
+ assert isinstance(command, str)
self.command = command
- self.arguments = arguments
+ self.arguments = []
+ for _ in arguments:
+ self.arguments.append(_ if isinstance(_, bytes) else _.encode('utf-8'))
self.timestamp = time.time() if timestamp is None else timestamp
def __repr__(self):
@@ -37,6 +40,9 @@ def __repr__(self):
def __cmp__(self, message):
return cmp(self.timestamp, message.timestamp)
+ def __lt__(self, message):
+ return self.timestamp < message.timestamp
+
def is_system_message(self):
if self.command in ['privmsg', 'privnotice']:
return self.arguments[1].startswith('--') # XXX
@@ -56,7 +62,7 @@ def __len__(self):
return len(self.heap)
def _dump(self):
- print self.heap
+ print(self.heap)
def peek(self):
return self.heap[0]
@@ -93,7 +99,7 @@ def purge(self):
return
if not self.is_system_message(message):
line_counts[target] += 1
- for target, line_count in line_counts.iteritems():
+ for target, line_count in line_counts.items():
message = "-- Message lags over %f seconds. Skipping %d line(s).." \
% (self.timeout, line_count)
message = Message(
@@ -148,7 +154,7 @@ def flood_control(self):
message = None
local = False
if len(self.buffer):
- print '--- buffer ---'
+ print('--- buffer ---')
self.buffer._dump()
self.pop_buffer(self.buffer)
@@ -171,8 +177,8 @@ def pop_buffer(self, buffer):
self.process_message(message)
message_ = buffer.pop()
if message != message_:
- print message
- print message_
+ print(message)
+ print(message_)
assert False
self.last_tick = tick
View
@@ -2,7 +2,7 @@
{
'version': 2010012605, # increment this and save to reload
- 'channels': ['#wikipedia-ko'],
+ 'channels': [b'#wikipedia-ko'],
'server': ('irc.freenode.net', 6666),
- 'nickname': 'inkblot',
+ 'nickname': b'inkblot',
}
View
@@ -7,7 +7,6 @@
import collections
import irclib
-irclib.DEBUG = 0
from BufferingBot import BufferingBot, Message
@@ -35,7 +34,7 @@ def __init__(self, config_file_name):
server = self.config['server']
nickname = self.config['nickname']
- BufferingBot.__init__(self, [server], nickname, 'bot')
+ BufferingBot.__init__(self, [server], nickname, b'inkblot')
self.plugins = []
@@ -80,15 +79,16 @@ def reply(self, event, message):
self.buffer.push(Message('privmsg', (reply_to, message)))
def reload(self):
- print "reloading..."
+ print("reloading...")
data = eval(open(self.config_file_name).read())
self.config = data
if self.version >= data['version']:
return
self.config_timestamp = os.stat(self.config_file_name).st_mtime
self.version = data['version']
+ irclib.DEBUG = data.get('debug', False)
self.reload_plugins()
- print "reloaded."
+ print("reloaded.")
def load_plugins(self):
import_path = os.path.join(INKBLOT_ROOT, 'plugins') # XXX
@@ -118,16 +118,16 @@ def handler(connection, event):
try:
getattr(plugin, 'on_'+action).__call__(self, connection, event)
except:
- reply = event.target() # XXX
+ reply = event.target() # XXX freenode only
tb = traceback.format_exc()
- print tb
+ print(tb)
self.buffer.push(Message('privmsg', (reply, tb.splitlines()[-1])))
self.handlers[action].append(handler)
self.connection.add_global_handler(action, handler, 0)
self.plugins.append(plugin)
def reload_plugins(self): # XXX
- for action, handlers in self.handlers.iteritems():
+ for action, handlers in self.handlers.items():
for handler in handlers:
self.connection.remove_global_handler(action, handler)
self.load_plugins()
@@ -139,10 +139,10 @@ def main():
profile = sys.argv[1]
if not profile:
profile = 'config'
- print "profile:", profile
+ print("profile:", profile)
config_file_name = os.path.join(INKBLOT_ROOT, '%s.py' % profile)
inkblot = Inkblot(config_file_name)
- print "Inkblot.start()"
+ print("Inkblot.start()")
inkblot.start()
if __name__ == '__main__':
View
@@ -25,7 +25,6 @@
"""
import sys
-from UserDict import UserDict
from irclib import SimpleIRCClient
from irclib import nm_to_n, irc_lower, all_events
@@ -128,12 +127,12 @@ def _on_kick(self, c, e):
def _on_mode(self, c, e):
"""[Internal]"""
- modes = parse_channel_modes(" ".join(e.arguments()))
+ modes = parse_channel_modes(b" ".join(e.arguments()))
t = e.target()
if is_channel(t):
ch = self.channels[t]
for mode in modes:
- if mode[0] == "+":
+ if mode[0] == b"+":
f = ch.set_mode
else:
f = ch.clear_mode
@@ -153,12 +152,12 @@ def _on_namreply(self, c, e):
ch = e.arguments()[1]
for nick in e.arguments()[2].split():
- if nick[0] == "@":
+ if nick[0] == b"@":
nick = nick[1:]
- self.channels[ch].set_mode("o", nick)
- elif nick[0] == "+":
+ self.channels[ch].set_mode(b"o", nick)
+ elif nick[0] == b"+":
nick = nick[1:]
- self.channels[ch].set_mode("v", nick)
+ self.channels[ch].set_mode(b"v", nick)
self.channels[ch].add_user(nick)
def _on_nick(self, c, e):
@@ -186,7 +185,7 @@ def _on_quit(self, c, e):
if ch.has_user(nick):
ch.remove_user(nick)
- def die(self, msg="Bye, cruel world!"):
+ def die(self, msg=b"Bye, cruel world!"):
"""Let the bot die.
Arguments:
@@ -197,7 +196,7 @@ def die(self, msg="Bye, cruel world!"):
self.connection.disconnect(msg)
sys.exit(0)
- def disconnect(self, msg="I'll be back!"):
+ def disconnect(self, msg=b"I'll be back!"):
"""Disconnect the bot.
The bot will try to reconnect after a while.
@@ -213,7 +212,7 @@ def get_version(self):
Used when answering a CTCP VERSION request.
"""
- return "ircbot.py by Joel Rosdahl <joel@rosdahl.net>"
+ return b"ircbot.py by Joel Rosdahl <joel@rosdahl.net>"
def jump_server(self, msg="Changing servers"):
"""Connect to a new server, possibly disconnecting from the current.
@@ -233,14 +232,14 @@ def on_ctcp(self, c, e):
Replies to VERSION and PING requests and relays DCC requests
to the on_dccchat method.
"""
- if e.arguments()[0] == "VERSION":
+ if e.arguments()[0] == b"VERSION":
c.ctcp_reply(nm_to_n(e.source()),
- "VERSION " + self.get_version())
- elif e.arguments()[0] == "PING":
+ b"VERSION " + self.get_version())
+ elif e.arguments()[0] == b"PING":
if len(e.arguments()) > 1:
c.ctcp_reply(nm_to_n(e.source()),
- "PING " + e.arguments()[1])
- elif e.arguments()[0] == "DCC" and e.arguments()[1].split(" ", 1)[0] == "CHAT":
+ b"PING " + e.arguments()[1])
+ elif e.arguments()[0] == b"DCC" and e.arguments()[1].split(b" ", 1)[0] == b"CHAT":
self.on_dccchat(c, e)
def on_dccchat(self, c, e):
@@ -289,13 +288,11 @@ def __delitem__(self, key):
def __iter__(self):
return iter(self.data)
def __contains__(self, key):
- return self.has_key(key)
+ return key in self.data
def clear(self):
self.data.clear()
self.canon_keys.clear()
def copy(self):
- if self.__class__ is UserDict:
- return UserDict(self.data)
import copy
return copy.copy(self)
def keys(self):
@@ -326,15 +323,15 @@ def __init__(self):
self.modes = {}
def users(self):
- """Returns an unsorted list of the channel's users."""
+ """Returns a dictview representing the channel's users."""
return self.userdict.keys()
def opers(self):
- """Returns an unsorted list of the channel's operators."""
+ """Returns a dictview representing the channel's operators."""
return self.operdict.keys()
def voiced(self):
- """Returns an unsorted list of the persons that have voice
+ """Returns a dictview representing the persons that have voice
mode set in the channel."""
return self.voiceddict.keys()
@@ -373,13 +370,13 @@ def set_mode(self, mode, value=None):
Arguments:
- mode -- The mode (a single-character string).
+ mode -- The mode (a single-character byte).
value -- Value
"""
- if mode == "o":
+ if mode == b"o":
self.operdict[value] = 1
- elif mode == "v":
+ elif mode == b"v":
self.voiceddict[value] = 1
else:
self.modes[mode] = value
@@ -389,14 +386,14 @@ def clear_mode(self, mode, value=None):
Arguments:
- mode -- The mode (a single-character string).
+ mode -- The mode (a single-character byte).
value -- Value
"""
try:
- if mode == "o":
+ if mode == b"o":
del self.operdict[value]
- elif mode == "v":
+ elif mode == b"v":
del self.voiceddict[value]
else:
del self.modes[mode]
@@ -407,25 +404,25 @@ def has_mode(self, mode):
return mode in self.modes
def is_moderated(self):
- return self.has_mode("m")
+ return self.has_mode(b"m")
def is_secret(self):
- return self.has_mode("s")
+ return self.has_mode(b"s")
def is_protected(self):
- return self.has_mode("p")
+ return self.has_mode(b"p")
def has_topic_lock(self):
- return self.has_mode("t")
+ return self.has_mode(b"t")
def is_invite_only(self):
- return self.has_mode("i")
+ return self.has_mode(b"i")
def has_allow_external_messages(self):
- return self.has_mode("n")
+ return self.has_mode(b"n")
def has_limit(self):
- return self.has_mode("l")
+ return self.has_mode(b"l")
def limit(self):
if self.has_limit():
@@ -434,10 +431,10 @@ def limit(self):
return None
def has_key(self):
- return self.has_mode("k")
+ return self.has_mode(b"k")
def key(self):
if self.has_key():
- return self.modes["k"]
+ return self.modes[b"k"]
else:
return None
Oops, something went wrong.

0 comments on commit b59be37

Please sign in to comment.