Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
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...
commit b59be374968d2d7f574f943819a33897a0986f40 1 parent a0d4377
Kyung-hown Chung authored
18 BufferingBot.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
4 config.py.sample
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',
}
18 inkblot.py
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__':
69 ircbot.py
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
329 irclib.py
View
@@ -207,8 +207,8 @@ def process_once(self, timeout=0):
incoming data, if there are any. If that seems boring, look
at the process_forever method.
"""
- sockets = map(lambda x: x._get_socket(), self.connections)
- sockets = filter(lambda x: x != None, sockets)
+ sockets = [x._get_socket() for x in self.connections]
+ sockets = [x for x in sockets if x != None]
if sockets:
(i, o, e) = select.select(sockets, [], [], timeout)
self.process_data(i)
@@ -228,7 +228,7 @@ def process_forever(self, timeout=0.2):
while 1:
self.process_once(timeout)
- def disconnect_all(self, message=""):
+ def disconnect_all(self, message=b""):
"""Disconnects all connections."""
for c in self.connections:
c.disconnect(message)
@@ -256,7 +256,7 @@ def add_global_handler(self, event, handler, priority=0):
"""
if not event in self.handlers:
self.handlers[event] = []
- bisect.insort(self.handlers[event], ((priority, handler)))
+ bisect.insort(self.handlers[event], (priority, hash(handler), handler))
def remove_global_handler(self, event, handler):
"""Removes a global handler function.
@@ -322,7 +322,7 @@ def _handle_event(self, connection, event):
"""[Internal]"""
h = self.handlers
for handler in h.get("all_events", []) + h.get(event.eventtype(), []):
- if handler[1](connection, event) == "NO MORE":
+ if handler[2](connection, event) == "NO MORE":
return
def _remove_connection(self, connection):
@@ -331,7 +331,7 @@ def _remove_connection(self, connection):
if self.fn_to_remove_socket:
self.fn_to_remove_socket(connection._get_socket())
-_rfc_1459_command_regexp = re.compile("^(:(?P<prefix>[^ ]+) +)?(?P<command>[^ ]+)( *(?P<argument> .+))?")
+_rfc_1459_command_regexp = re.compile(b"^(:(?P<prefix>[^ ]+) +)?(?P<command>[^ ]+)( *(?P<argument> .+))?")
class Connection:
"""Base class for IRC connections.
@@ -342,7 +342,7 @@ def __init__(self, irclibobj):
self.irclibobj = irclibobj
def _get_socket():
- raise IRCError, "Not overridden"
+ raise IRCError("Not overridden")
##############################
### Convenience wrappers.
@@ -363,7 +363,7 @@ class ServerNotConnectedError(ServerConnectionError):
# Huh!? Crrrrazy EFNet doesn't follow the RFC: their ircd seems to
# use \n as message separator! :P
-_linesep_regexp = re.compile("\r?\n")
+_linesep_regexp = re.compile(b"\r?\n")
class ServerConnection(Connection):
"""This class represents an IRC server connection.
@@ -411,9 +411,9 @@ def connect(self, server, port, nickname, password=None, username=None,
if self.connected:
self.disconnect("Changing servers")
- self.previous_buffer = ""
+ self.previous_buffer = b""
self.handlers = {}
- self.real_server_name = ""
+ self.real_server_name = b""
self.real_nickname = nickname
self.server = server
self.port = port
@@ -433,10 +433,10 @@ def connect(self, server, port, nickname, password=None, username=None,
self.socket.connect((self.server, self.port))
if ssl:
self.ssl = socket.ssl(self.socket)
- except socket.error, x:
+ except socket.error as x:
self.socket.close()
self.socket = None
- raise ServerConnectionError, "Couldn't connect to socket: %s" % x
+ raise ServerConnectionError("Couldn't connect to socket: %s" % x)
self.connected = 1
if self.irclibobj.fn_to_add_socket:
self.irclibobj.fn_to_add_socket(self.socket)
@@ -491,7 +491,7 @@ def process_data(self):
new_data = self.ssl.read(2**14)
else:
new_data = self.socket.recv(2**14)
- except socket.error, x:
+ except socket.error as x:
# The server hung up.
self.disconnect("Connection reset by peer")
return
@@ -507,7 +507,7 @@ def process_data(self):
for line in lines:
if DEBUG:
- print "FROM SERVER:", line
+ print("FROM SERVER:", line)
if not line:
continue
@@ -527,10 +527,10 @@ def process_data(self):
self.real_server_name = prefix
if m.group("command"):
- command = m.group("command").lower()
+ command = m.group("command").decode('latin-1').lower()
if m.group("argument"):
- a = m.group("argument").split(" :", 1)
+ a = m.group("argument").split(b" :", 1)
arguments = a[0].split()
if len(a) == 2:
arguments.append(a[1])
@@ -561,7 +561,7 @@ def process_data(self):
command = "privnotice"
for m in messages:
- if type(m) is types.TupleType:
+ if type(m) is tuple:
if command in ["privmsg", "pubmsg"]:
command = "ctcp"
else:
@@ -569,15 +569,15 @@ def process_data(self):
m = list(m)
if DEBUG:
- print "command: %s, source: %s, target: %s, arguments: %s" % (
- command, prefix, target, m)
+ print("command: %s, source: %s, target: %s, arguments: %s" % (
+ command, prefix, target, m))
self._handle_event(Event(command, prefix, target, m))
if command == "ctcp" and m[0] == "ACTION":
self._handle_event(Event("action", prefix, target, m[1:]))
else:
if DEBUG:
- print "command: %s, source: %s, target: %s, arguments: %s" % (
- command, prefix, target, [m])
+ print("command: %s, source: %s, target: %s, arguments: %s" % (
+ command, prefix, target, [m]))
self._handle_event(Event(command, prefix, target, [m]))
else:
target = None
@@ -595,8 +595,8 @@ def process_data(self):
command = "umode"
if DEBUG:
- print "command: %s, source: %s, target: %s, arguments: %s" % (
- command, prefix, target, arguments)
+ print("command: %s, source: %s, target: %s, arguments: %s" % (
+ command, prefix, target, arguments))
self._handle_event(Event(command, prefix, target, arguments))
def _handle_event(self, event):
@@ -629,22 +629,24 @@ def remove_global_handler(self, *args):
def action(self, target, action):
"""Send a CTCP ACTION command."""
- self.ctcp("ACTION", target, action)
+ self.ctcp(b"ACTION", target, action)
- def admin(self, server=""):
+ def admin(self, server=b""):
"""Send an ADMIN command."""
- self.send_raw(" ".join(["ADMIN", server]).strip())
+ self.send_raw(b" ".join([b"ADMIN", server]).strip())
- def ctcp(self, ctcptype, target, parameter=""):
+ def ctcp(self, ctcptype, target, parameter=b""):
"""Send a CTCP command."""
- ctcptype = ctcptype.upper()
- self.privmsg(target, "\001%s%s\001" % (ctcptype, parameter and (" " + parameter) or ""))
+ command = ctcptype.upper()
+ if paramter:
+ command += b" " + parameter
+ self.privmsg(target, b"\001" + command + b"\001")
def ctcp_reply(self, target, parameter):
"""Send a CTCP REPLY command."""
- self.notice(target, "\001%s\001" % parameter)
+ self.notice(target, b"\001" + parameter + b"\001")
- def disconnect(self, message=""):
+ def disconnect(self, message=b""):
"""Hang up the connection.
Arguments:
@@ -660,22 +662,22 @@ def disconnect(self, message=""):
try:
self.socket.close()
- except socket.error, x:
+ except socket.error as x:
pass
self.socket = None
self._handle_event(Event("disconnect", self.server, "", [message]))
def globops(self, text):
"""Send a GLOBOPS command."""
- self.send_raw("GLOBOPS :" + text)
+ self.send_raw(b"GLOBOPS :" + text)
- def info(self, server=""):
+ def info(self, server=b""):
"""Send an INFO command."""
- self.send_raw(" ".join(["INFO", server]).strip())
+ self.send_raw(b" ".join([b"INFO", server]).strip())
def invite(self, nick, channel):
"""Send an INVITE command."""
- self.send_raw(" ".join(["INVITE", nick, channel]).strip())
+ self.send_raw(b" ".join([b"INVITE", nick, channel]).strip())
def ison(self, nicks):
"""Send an ISON command.
@@ -684,97 +686,124 @@ def ison(self, nicks):
nicks -- List of nicks.
"""
- self.send_raw("ISON " + " ".join(nicks))
+ self.send_raw(b"ISON " + " ".join(nicks))
- def join(self, channel, key=""):
+ def join(self, channel, key=b""):
"""Send a JOIN command."""
- self.send_raw("JOIN %s%s" % (channel, (key and (" " + key))))
+ command = b"JOIN " + channel
+ if key:
+ command += b" " + key
+ self.send_raw(command)
- def kick(self, channel, nick, comment=""):
+ def kick(self, channel, nick, comment=b""):
"""Send a KICK command."""
- self.send_raw("KICK %s %s%s" % (channel, nick, (comment and (" :" + comment))))
+ command = b"KICK " + channel + b" " + nick
+ if comment:
+ command += b" :" + comment
+ self.send_raw(command)
- def links(self, remote_server="", server_mask=""):
+ def links(self, remote_server=b"", server_mask=b""):
"""Send a LINKS command."""
- command = "LINKS"
+ command = b"LINKS"
if remote_server:
- command = command + " " + remote_server
+ command += b" " + remote_server
if server_mask:
- command = command + " " + server_mask
+ command += b" " + server_mask
self.send_raw(command)
- def list(self, channels=None, server=""):
+ def list(self, channels=None, server=b""):
"""Send a LIST command."""
- command = "LIST"
+ command = b"LIST"
if channels:
- command = command + " " + ",".join(channels)
+ command = command + b" " + b",".join(channels)
if server:
- command = command + " " + server
+ command = command + b" " + server
self.send_raw(command)
- def lusers(self, server=""):
+ def lusers(self, server=b""):
"""Send a LUSERS command."""
- self.send_raw("LUSERS" + (server and (" " + server)))
+ command = b"LUSERS"
+ if server:
+ command += b" " + server
+ self.send_raw(command)
def mode(self, target, command):
"""Send a MODE command."""
- self.send_raw("MODE %s %s" % (target, command))
+ self.send_raw(b"MODE " + target + b" " + command)
- def motd(self, server=""):
+ def motd(self, server=b""):
"""Send an MOTD command."""
- self.send_raw("MOTD" + (server and (" " + server)))
+ command = b"MOTD"
+ if server:
+ command += b" " + server
+ self.send_raw(command)
def names(self, channels=None):
"""Send a NAMES command."""
- self.send_raw("NAMES" + (channels and (" " + ",".join(channels)) or ""))
+ command = b"NAMES"
+ if channels:
+ command += b" " + b",".join(channels)
+ self.send_raw(command)
def nick(self, newnick):
"""Send a NICK command."""
- self.send_raw("NICK " + newnick)
+ self.send_raw(b"NICK " + newnick)
def notice(self, target, text):
"""Send a NOTICE command."""
# Should limit len(text) here!
- self.send_raw("NOTICE %s :%s" % (target, text))
+ self.send_raw(b"NOTICE " + target + b" :" + text)
def oper(self, nick, password):
"""Send an OPER command."""
- self.send_raw("OPER %s %s" % (nick, password))
+ self.send_raw(b"OPER " + nick + b" " + password)
- def part(self, channels, message=""):
+ def part(self, channels, message=b""):
"""Send a PART command."""
- if type(channels) == types.StringType:
- self.send_raw("PART " + channels + (message and (" " + message)))
+ if isinstance(channels, (bytes, str)):
+ command = b"PART " + channels
else:
- self.send_raw("PART " + ",".join(channels) + (message and (" " + message)))
+ command = b"PART " + b",".join(channels)
+ if message:
+ command += b" " + message
+ self.send_raw(command)
def pass_(self, password):
"""Send a PASS command."""
- self.send_raw("PASS " + password)
+ self.send_raw(b"PASS " + password)
- def ping(self, target, target2=""):
+ def ping(self, target, target2=b""):
"""Send a PING command."""
- self.send_raw("PING %s%s" % (target, target2 and (" " + target2)))
+ command = b"PING " + target
+ if target2:
+ command += b" " + target2
+ self.send_raw(command)
- def pong(self, target, target2=""):
+ def pong(self, target, target2=b""):
"""Send a PONG command."""
- self.send_raw("PONG %s%s" % (target, target2 and (" " + target2)))
+ command = b"PONG " + target
+ if target2:
+ command += b" " + target2
+ self.send_raw(command)
def privmsg(self, target, text):
"""Send a PRIVMSG command."""
# Should limit len(text) here!
- self.send_raw("PRIVMSG %s :%s" % (target, text))
+ self.send_raw(b"PRIVMSG " + target + b" :" + text)
def privmsg_many(self, targets, text):
"""Send a PRIVMSG command to multiple targets."""
# Should limit len(text) here!
- self.send_raw("PRIVMSG %s :%s" % (",".join(targets), text))
+ self.send_raw(b"PRIVMSG " + b",".join(targets) + b" :" + text)
- def quit(self, message=""):
+ def quit(self, message=b""):
"""Send a QUIT command."""
# Note that many IRC servers don't use your QUIT message
# unless you've been connected for at least 5 minutes!
- self.send_raw("QUIT" + (message and (" :" + message)))
+ command = b"QUIT "
+ if target2:
+ command += b" :" + message
+ self.send_raw(command)
def send_raw(self, string):
"""Send raw string to the server.
@@ -782,74 +811,91 @@ def send_raw(self, string):
The string will be padded with appropriate CR LF.
"""
if self.socket is None:
- raise ServerNotConnectedError, "Not connected."
+ raise ServerNotConnectedError("Not connected.")
try:
if self.ssl:
- self.ssl.write(string + "\r\n")
+ self.ssl.write(string + b"\r\n")
else:
- self.socket.send(string + "\r\n")
+ self.socket.send(string + b"\r\n")
if DEBUG:
- print "TO SERVER:", string
- except socket.error, x:
+ print("TO SERVER:", string)
+ except socket.error as x:
# Ouch!
self.disconnect("Connection reset by peer.")
- def squit(self, server, comment=""):
+ def squit(self, server, comment=b""):
"""Send an SQUIT command."""
- self.send_raw("SQUIT %s%s" % (server, comment and (" :" + comment)))
+ self.send_raw(b"SQUIT " + server + (comment and (" :" + comment)))
- def stats(self, statstype, server=""):
+ def stats(self, statstype, server=b""):
"""Send a STATS command."""
- self.send_raw("STATS %s%s" % (statstype, server and (" " + server)))
+ self.send_raw(b"STATS " + statstype + (server and (" " + server)))
- def time(self, server=""):
+ def time(self, server=b""):
"""Send a TIME command."""
- self.send_raw("TIME" + (server and (" " + server)))
+ self.send_raw(b"TIME" + (server and (" " + server)))
def topic(self, channel, new_topic=None):
"""Send a TOPIC command."""
if new_topic is None:
- self.send_raw("TOPIC " + channel)
+ self.send_raw(b"TOPIC " + channel)
else:
- self.send_raw("TOPIC %s :%s" % (channel, new_topic))
+ self.send_raw(b"TOPIC " + channel + b" :" + new_topic)
- def trace(self, target=""):
+ def trace(self, target=b""):
"""Send a TRACE command."""
- self.send_raw("TRACE" + (target and (" " + target)))
+ command = b"TRACE"
+ if target:
+ command += b" " + target
+ self.send_raw(command)
def user(self, username, realname):
"""Send a USER command."""
- self.send_raw("USER %s 0 * :%s" % (username, realname))
+ self.send_raw(b"USER " + username + b" 0 * :" + realname)
def userhost(self, nicks):
"""Send a USERHOST command."""
- self.send_raw("USERHOST " + ",".join(nicks))
+ self.send_raw(b"USERHOST " + ",".join(nicks))
- def users(self, server=""):
+ def users(self, server=b""):
"""Send a USERS command."""
- self.send_raw("USERS" + (server and (" " + server)))
+ command = b"USERS"
+ if server:
+ command += b" " + server
+ self.send_raw(command)
- def version(self, server=""):
+ def version(self, server=b""):
"""Send a VERSION command."""
- self.send_raw("VERSION" + (server and (" " + server)))
+ command = b"VERSION"
+ if server:
+ command += b" " + server
+ self.send_raw(command)
def wallops(self, text):
"""Send a WALLOPS command."""
- self.send_raw("WALLOPS :" + text)
+ self.send_raw(b"WALLOPS :" + text)
- def who(self, target="", op=""):
+ def who(self, target=b"", op=b""):
"""Send a WHO command."""
- self.send_raw("WHO%s%s" % (target and (" " + target), op and (" o")))
+ command = b"WHO"
+ if target:
+ command += b" " + target
+ if op:
+ command += b" o"
+ self.send_raw(command)
def whois(self, targets):
"""Send a WHOIS command."""
- self.send_raw("WHOIS " + ",".join(targets))
+ self.send_raw(b"WHOIS " + b",".join(targets))
- def whowas(self, nick, max="", server=""):
+ def whowas(self, nick, max=b"", server=b""):
"""Send a WHOWAS command."""
- self.send_raw("WHOWAS %s%s%s" % (nick,
- max and (" " + max),
- server and (" " + server)))
+ command = b"WHOWAS" + nick
+ if max:
+ command += b" " + max
+ if server:
+ command += b" " + server
+ self.send_raw(command)
class DCCConnectionError(IRCError):
pass
@@ -888,8 +934,8 @@ def connect(self, address, port):
self.passive = 0
try:
self.socket.connect((self.peeraddress, self.peerport))
- except socket.error, x:
- raise DCCConnectionError, "Couldn't connect to socket: %s" % x
+ except socket.error as x:
+ raise DCCConnectionError("Couldn't connect to socket: %s" % x)
self.connected = 1
if self.irclibobj.fn_to_add_socket:
self.irclibobj.fn_to_add_socket(self.socket)
@@ -913,11 +959,11 @@ def listen(self):
self.socket.bind((socket.gethostbyname(socket.gethostname()), 0))
self.localaddress, self.localport = self.socket.getsockname()
self.socket.listen(10)
- except socket.error, x:
- raise DCCConnectionError, "Couldn't bind socket: %s" % x
+ except socket.error as x:
+ raise DCCConnectionError("Couldn't bind socket: %s" % x)
return self
- def disconnect(self, message=""):
+ def disconnect(self, message=b""):
"""Hang up the connection and close the object.
Arguments:
@@ -930,7 +976,7 @@ def disconnect(self, message=""):
self.connected = 0
try:
self.socket.close()
- except socket.error, x:
+ except socket.error as x:
pass
self.socket = None
self.irclibobj._handle_event(
@@ -947,8 +993,8 @@ def process_data(self):
self.socket = conn
self.connected = 1
if DEBUG:
- print "DCC connection from %s:%d" % (
- self.peeraddress, self.peerport)
+ print("DCC connection from %s:%d" % (
+ self.peeraddress, self.peerport))
self.irclibobj._handle_event(
self,
Event("dcc_connect", self.peeraddress, None, None))
@@ -956,7 +1002,7 @@ def process_data(self):
try:
new_data = self.socket.recv(2**14)
- except socket.error, x:
+ except socket.error as x:
# The server hung up.
self.disconnect("Connection reset by peer")
return
@@ -985,11 +1031,11 @@ def process_data(self):
target = None
for chunk in chunks:
if DEBUG:
- print "FROM PEER:", chunk
+ print("FROM PEER:", chunk)
arguments = [chunk]
if DEBUG:
- print "command: %s, source: %s, target: %s, arguments: %s" % (
- command, prefix, target, arguments)
+ print("command: %s, source: %s, target: %s, arguments: %s" % (
+ command, prefix, target, arguments))
self.irclibobj._handle_event(
self,
Event(command, prefix, target, arguments))
@@ -1009,8 +1055,8 @@ def privmsg(self, string):
if self.dcctype == "chat":
self.socket.send("\n")
if DEBUG:
- print "TO PEER: %s\n" % string
- except socket.error, x:
+ print("TO PEER: %s\n" % string)
+ except socket.error as x:
# Ouch!
self.disconnect("Connection reset by peer.")
@@ -1153,18 +1199,18 @@ def arguments(self):
"""Get the event arguments."""
return self._arguments
-_LOW_LEVEL_QUOTE = "\020"
-_CTCP_LEVEL_QUOTE = "\134"
-_CTCP_DELIMITER = "\001"
+_LOW_LEVEL_QUOTE = b"\020"
+_CTCP_LEVEL_QUOTE = b"\134"
+_CTCP_DELIMITER = b"\001"
_low_level_mapping = {
- "0": "\000",
- "n": "\n",
- "r": "\r",
+ b"0": b"\000",
+ b"n": b"\n",
+ b"r": b"\r",
_LOW_LEVEL_QUOTE: _LOW_LEVEL_QUOTE
}
-_low_level_regexp = re.compile(_LOW_LEVEL_QUOTE + "(.)")
+_low_level_regexp = re.compile(_LOW_LEVEL_QUOTE + b"(.)")
def mask_matches(nick, mask):
"""Check if a nick matches a mask.
@@ -1181,10 +1227,10 @@ def mask_matches(nick, mask):
r = re.compile(mask, re.IGNORECASE)
return r.match(nick)
-_special = "-[]\\`^{}"
-nick_characters = string.ascii_letters + string.digits + _special
-_ircstring_translation = string.maketrans(string.ascii_uppercase + "[]\\^",
- string.ascii_lowercase + "{}|~")
+_special = r"-[]\`^{}"
+nick_characters = (string.ascii_letters + string.digits + _special).encode('ascii')
+_ircstring_translation = bytes.maketrans(string.ascii_uppercase.encode('ascii') + b"[]\\^",
+ string.ascii_lowercase.encode('ascii') + b"{}|~")
def irc_lower(s):
"""Returns a lowercased string.
@@ -1235,7 +1281,7 @@ def _low_level_replace(match_obj):
if i < len(chunks)-2:
# Aye! CTCP tagged data ahead!
- messages.append(tuple(chunks[i+1].split(" ", 1)))
+ messages.append(tuple(chunks[i+1].split(b" ", 1)))
i = i + 2
@@ -1253,22 +1299,21 @@ def is_channel(string):
Returns true if the argument is a channel name, otherwise false.
"""
- return string and string[0] in "#&+!"
+ return string and string[0] in b"#&+!"
def ip_numstr_to_quad(num):
"""Convert an IP number as an integer given in ASCII
representation (e.g. '3232235521') to an IP address string
(e.g. '192.168.0.1')."""
- n = long(num)
- p = map(str, map(int, [n >> 24 & 0xFF, n >> 16 & 0xFF,
- n >> 8 & 0xFF, n & 0xFF]))
- return ".".join(p)
+ n = int(num)
+ p = [n >> 24 & 0xFF, n >> 16 & 0xFF, n >> 8 & 0xFF, n & 0xFF]
+ return ".".join(str(int(_)) for _ in p)
def ip_quad_to_numstr(quad):
"""Convert an IP address string (e.g. '192.168.0.1') to an IP
number as an integer given in ASCII representation
(e.g. '3232235521')."""
- p = map(long, quad.split("."))
+ p = [int(_) for _ in quad.split(".")]
s = str((p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3])
if s[-1] == "L":
s = s[:-1]
@@ -1279,29 +1324,29 @@ def nm_to_n(s):
(The source of an Event is a nickmask.)
"""
- return s.split("!")[0]
+ return s.split(b"!")[0]
def nm_to_uh(s):
"""Get the userhost part of a nickmask.
(The source of an Event is a nickmask.)
"""
- return s.split("!")[1]
+ return s.split(b"!")[1]
def nm_to_h(s):
"""Get the host part of a nickmask.
(The source of an Event is a nickmask.)
"""
- return s.split("@")[1]
+ return s.split(b"@")[1]
def nm_to_u(s):
"""Get the user part of a nickmask.
(The source of an Event is a nickmask.)
"""
- s = s.split("!")[1]
- return s.split("@")[0]
+ s = s.split(b"!")[1]
+ return s.split(b"@")[0]
def parse_nick_modes(mode_string):
"""Parse a nick mode string.
@@ -1331,7 +1376,7 @@ def parse_channel_modes(mode_string):
[['+', 'a', None], ['+', 'b', 'foo'], ['-', 'c', None]]
"""
- return _parse_modes(mode_string, "bklvo")
+ return _parse_modes(mode_string, b"bklvo")
def _parse_modes(mode_string, unary_modes=""):
"""[Internal]"""
@@ -1347,12 +1392,12 @@ def _parse_modes(mode_string, unary_modes=""):
else:
mode_part, args = a[0], a[1:]
- if mode_part[0] not in "+-":
+ if mode_part[0] not in b"+-":
return []
for ch in mode_part:
- if ch in "+-":
+ if ch in b"+-":
sign = ch
- elif ch == " ":
+ elif ch == b" ":
collecting_arguments = 1
elif ch in unary_modes:
if len(args) >= arg_count + 1:
@@ -1557,4 +1602,4 @@ def _ping_ponger(connection, event):
"pong",
]
-all_events = generated_events + protocol_events + numeric_events.values()
+all_events = generated_events + protocol_events + list(numeric_events.values())
85 lib/whois.py
View
@@ -1,5 +1,5 @@
#!/usr/bin/env python
-# -*- coding: cp949 -*-
+# -*- coding: utf8 -*-
# vim: ts=8 sts=4 et
#
# Copyright 2000 Dominic Mitchell <dom@happygiraffe.net>
@@ -63,7 +63,7 @@ def Server(domain):
"""Return the whois server for domain."""
server = INTERNIC # Default.
- for tld in servers.keys():
+ for tld in list(servers.keys()):
l = len(tld)
if domain[-l:] == tld:
server = servers[tld]
@@ -74,71 +74,75 @@ def Server(domain):
def digest_ARIN(winfo):
r = {}
try:
- r[u'owner'] = re.findall(r'OrgName:\s+(.+)', winfo)[0].decode('latin1')
- r[u'netname'] = re.findall(r'NetName:\s+(.*)', winfo)[0].decode('latin1')
- r[u'netblock'] = re.findall(r'NetRange:\s+([0-9\.]+) - ([0-9\.]+)', winfo)[0]
+ r['owner'] = re.findall(b'OrgName:\\s+(.+)', winfo)[0].decode('latin1')
+ r['netname'] = re.findall(b'NetName:\\s+(.*)', winfo)[0].decode('latin1')
+ r['netblock'] = re.findall(b'NetRange:\\s+([0-9\\.]+) - ([0-9\\.]+)', winfo)[0]
except IndexError:
- r[u'owner'], r[u'netname'] = re.findall(r'(.+) (.+) \(NET-', winfo)[0]
- r[u'netblock'] = re.findall(r'([0-9\.]+) - ([0-9\.]+)', winfo)[0]
- r[u'source'] = u'ARIN'
+ r['owner'], r['netname'] = re.findall(b'(.+) (.+) \\(NET-', winfo)[0]
+ r['netblock'] = re.findall(b'([0-9\\.]+) - ([0-9\\.]+)', winfo)[0]
+ r['source'] = 'ARIN'
return r
def digest_RIPE(winfo): # Used by RIPE, APNIC
r = {}
- r[u'netblock'] = re.findall(r'inetnum:\s+([0-9\.]+) {1,2}- {1,2}([0-9\.]+)', winfo)[0]
- r[u'netname'] = re.findall(r'netname:\s+(.+)', winfo)[0].decode('latin1')
- r[u'owner'] = re.findall(r'descr:\s+(.+)', winfo)[0].decode('latin1')
+ r['netblock'] = re.findall(b'inetnum:\\s+([0-9\\.]+) {1,2}- {1,2}([0-9\\.]+)', winfo)[0]
+ r['netname'] = re.findall(b'netname:\\s+(.+)', winfo)[0].decode('latin1')
+ r['owner'] = re.findall(b'descr:\\s+(.+)', winfo)[0].decode('latin1')
try:
- r[u'route'] = re.findall(r'route:[\s0-9\./]+\ndescr:\s+(.*)', winfo)[0].decode('latin1')
+ r['route'] = re.findall(b'route:[\\s0-9\\./]+\\ndescr:\\s+(.*)', winfo)[0].decode('latin1')
except IndexError:
pass
- r[u'source'] = re.findall(r'source:\s+(.+)', winfo)[0].decode('latin1')
+ r['source'] = re.findall(b'source:\\s+(.+)', winfo)[0].decode('latin1')
return r
def digest_KRNIC(winfo):
+ winfo = winfo.decode('cp949')
r = {}
try:
- r[u'netblock'] = re.findall(r'IPv4주소\s+: ([0-9\.]+)-([0-9\.]+)', winfo)[0]
+ r['netblock'] = re.findall(r'IPv4주소\s+: ([0-9\.]+)-([0-9\.]+)', winfo)[0]
except IndexError:
- r[u'netblock'] = u'no block' # ISP Only Format
- r[u'netname'] = re.findall(r'서비스명\s+: (.+)', winfo)[0].decode('cp949')
- r[u'owner'] = re.findall(r'기 관 명\s+: (.+)', winfo)[0].decode('cp949')
+ r['netblock'] = 'no block' # ISP Only Format
+ r['netname'] = re.findall(r'서비스명\s+: (.+)', winfo)[0]
+ r['owner'] = re.findall(r'기 관 명\s+: (.+)', winfo)[0]
else:
- r[u'netname'] = re.findall(r'네트워크 이름\s+: (.+)', winfo)[0].decode('cp949')
- r[u'owner'] = re.findall(r'기관명\s+: (.+)', winfo)[0].decode('cp949')
- try: r[u'route'] = re.findall(r'연결 ISP명\s+: (.+)', winfo)[0].decode('cp949')
- except IndexError: r[u'route'] = u'unknown'
- r[u'source'] = u'KRNIC'
+ r['netname'] = re.findall(r'네트워크 이름\s+: (.+)', winfo)[0]
+ r['owner'] = re.findall(r'기관명\s+: (.+)', winfo)[0]
+ try: r['route'] = re.findall(r'연결 ISP명\s+: (.+)', winfo)[0]
+ except IndexError: r['route'] = 'unknown'
+ r['source'] = 'KRNIC'
return r
def digest_JPNIC(winfo):
r = {}
try:
- r[u'netblock'] = re.findall(r'a\. \[Network Number\]\s+([0-9\.]+)-([0-9\.]+)', winfo)[0]
+ r['netblock'] = re.findall(b'a\\. \\[Network Number\\]\\s+([0-9\\.]+)-([0-9\\.]+)', winfo)[0]
except:
- r[u'netblock'] = re.findall(r'a\. \[Network Number\]\s+([0-9\.]+)', winfo)[0].decode('ascii')
- r[u'netname'] = re.findall(r'b\. \[Network Name\]\s+(.+)', winfo)[0].decode('shift-jis')
- r[u'owner'] = re.findall(r'g\. \[Organization\]\s+(.+)', winfo)[0].decode('shift-jis')
- r[u'source'] = u'JPNIC'
+ r['netblock'] = re.findall(b'a\\. \\[Network Number\\]\\s+([0-9\\.]+)', winfo)[0].decode('ascii')
+ r['netname'] = re.findall(b'b\\. \\[Network Name\\]\\s+(.+)', winfo)[0].decode('shift-jis')
+ r['owner'] = re.findall(b'g\\. \\[Organization\\]\\s+(.+)', winfo)[0].decode('shift-jis')
+ r['source'] = 'JPNIC'
return r
_=re.compile
ipwregion = { # whois server search suffix, redirect match, digest
'ARIN': ('whois.arin.net', '', None, digest_ARIN),
- 'RIPE': ('whois.ripe.net', '', _('(be found in the RIPE database at whois.ripe.net)|(European Regional Internet Registry/RIPE NCC|RIPE Network Coordination Centre)'), digest_RIPE),
- 'APNIC': ('whois.apnic.net', '', _('refer to the APNIC Whois Database'), digest_RIPE),
+ 'RIPE': ('whois.ripe.net', '', _(b'(be found in the RIPE database at whois.ripe.net)|(European Regional Internet Registry/RIPE NCC|RIPE Network Coordination Centre)'), digest_RIPE),
+ 'APNIC': ('whois.apnic.net', '', _(b'refer to the APNIC Whois Database'), digest_RIPE),
- 'KRNIC': ('whois.nic.or.kr', '', _('(For more information, using KRNIC Whois Database)|(please refer to the KRNIC Whois DB)'), digest_KRNIC),
- 'JPNIC': ('whois.nic.ad.jp', '/e', _('(JPNIC whois server at whois.nic.ad.jp)|(Japan Network Information Center \(NETBLK-JAPAN-NET\))'), digest_JPNIC),
+ 'KRNIC': ('whois.nic.or.kr', '', _(b'(For more information, using KRNIC Whois Database)|(please refer to the KRNIC Whois DB)'), digest_KRNIC),
+ 'JPNIC': ('whois.nic.ad.jp', '/e', _(b'(JPNIC whois server at whois.nic.ad.jp)|(Japan Network Information Center \(NETBLK-JAPAN-NET\))'), digest_JPNIC),
}
def IPWhois(addr):
ip = socket.gethostbyname(addr) # this may cause socket.gaierror exception
+ ip = ip.encode('utf8')
winfo = Whois(ip, ipwregion['ARIN'][0])
wdigest = ipwregion['ARIN'][3]
while 1:
- for server, suffix, redir, digest in ipwregion.values():
+ for server, suffix, redir, digest in list(ipwregion.values()):
+ print(repr(redir))
+ print(repr(winfo))
if redir and redir.search(winfo):
winfo = Whois(ip+suffix, server)
wdigest = digest
@@ -147,9 +151,9 @@ def IPWhois(addr):
break
r = wdigest(winfo)
- r[u'ipv4addr'] = ip.decode('ascii')
- if isinstance(r[u'netblock'], tuple):
- r[u'netblock'] = u'-'.join(r[u'netblock'])
+ r['ipv4addr'] = ip.decode('ascii')
+ if isinstance(r['netblock'], tuple):
+ r['netblock'] = b'-'.join(r['netblock'])
return r
@@ -165,17 +169,16 @@ def Whois(domain, server=None):
sock.connect((server, port))
# The protocol itself.
- sock.send(domain + '\r\n')
+ sock.send(domain + b'\r\n')
#sock.shutdown(1) # No more sends. XXX: this doesn't work on RIPE
- data = ''
+ data = b''
while 1:
newdata = sock.recv(16384)
if not newdata: break
data = data + newdata
sock.close()
# Zap any CR's we see.
- if string.find(data, '\r') >= 0:
- data = string.join(string.split(data, '\r'), '')
+ data = b''.join(data.split(b'\r'))
return data
def WhoisList(domain, server=None):
@@ -207,9 +210,9 @@ def _init():
from pprint import pprint
name = sys.argv[1]
dom = sys.argv[2]
- print "%% whois -h %s '%s'" % (dom, name)
+ print("%% whois -h %s '%s'" % (dom, name))
pprint(WhoisList(name, dom))
except IndexError:
- print "usage: whoisserver.py name domain"
+ print("usage: whoisserver.py name domain")
# vim: ai et sw=4 ts=4
46 plugins/interwiki.py
View
@@ -1,63 +1,61 @@
# encoding: utf-8
import re
-import urllib
+import urllib.request, urllib.parse, urllib.error
def get_mediawiki_page(page, enc):
- page = page.replace(u' ', u'_')
- page = urllib.quote(page.encode(enc))
+ page = page.replace(' ', '_')
+ page = urllib.parse.quote(page.encode(enc))
page = re.sub('%23(.*)', lambda x: '#'+x.group(1).replace('%', '.'), page)
page = re.sub('%3A(.*)', r':\1', page)
- return page.decode('ascii')
+ return page
LOCATION = {
- u'b': u'wikibooks',
- u'm': u'meta',
- u'mw': u'mediawiki',
- u's': u'wikisource',
- u'wikt': u'wiktionary',
+ 'b': 'wikibooks',
+ 'm': 'meta',
+ 'mw': 'mediawiki',
+ 's': 'wikisource',
+ 'wikt': 'wiktionary',
}
-def get_wikipedia_url(page, lang=u'ko', location=u'wikipedia'):
- left, partitioned, right = page.partition(u':')
+def get_wikipedia_url(page, lang='ko', location='wikipedia'):
+ left, partitioned, right = page.partition(':')
while partitioned:
if left in LOCATION:
location = LOCATION[left]
- elif re.match(ur'^[a-z][a-z]$', left) is not None:
+ elif re.match(r'^[a-z][a-z]$', left) is not None:
lang = left
else:
break
page = right
return get_wikipedia_url(page, lang, location)
page = get_mediawiki_page(page, 'utf-8')
- if location in (u'meta', u'commons'):
- return u'http://%s.wikimedia.org/wiki/%s' % (location, page)
- elif location in (u'mediawiki'):
- return u'http://www.%s.org/wiki/%s' % (location, page)
- return u'http://%s.%s.org/wiki/%s' % (lang, location, page)
+ if location in ('meta', 'commons'):
+ return 'http://%s.wikimedia.org/wiki/%s' % (location, page)
+ elif location in ('mediawiki'):
+ return 'http://www.%s.org/wiki/%s' % (location, page)
+ return 'http://%s.%s.org/wiki/%s' % (lang, location, page)
def on_msg(bot, connection, event):
msg = event.arguments()[0]
- if event.source() in ['uniko', 'kouni']:
- msg = re.sub(r'^<.*?> ', '', msg, 1)
try: # XXX
msg = msg.decode('utf-8')
except UnicodeDecodeError:
return
- if u'[[' not in msg:
+ if '[[' not in msg:
return
MAX_CNT = 5
cnt = 0
visit = {}
- for page in re.findall(ur'\[\[(.+?)\]\]', msg):
+ for page in re.findall(r'\[\[(.+?)\]\]', msg):
if page != page.strip(): continue
if page in visit: continue
visit[page] = True
if cnt >= MAX_CNT:
- bot.reply(event, u'최대 %d개까지만 출력합니다.' % MAX_CNT)
+ bot.reply(event, '최대 %d개까지만 출력합니다.' % MAX_CNT)
return
- label = u''
+ label = ''
url = get_wikipedia_url(page)
- bot.reply(event, u'\x02[%s]\x02 %s' % (page, url))
+ bot.reply(event, '\x02[%s]\x02 %s' % (page, url))
cnt += 1
def on_privmsg(bot, connection, event):
35 plugins/ipw.py
View
@@ -1,33 +1,34 @@
import re
+import imp
-from lib import whois; reload(whois)
+from lib import whois; imp.reload(whois)
def on_msg(bot, connection, event):
msg = event.arguments()[0]
# XXX
- source = str(event.source())
- source = source.split('!', 1)[1]
- source = source.split('@')[0]
- if '=' in source: source = source.split('=',1)[1]
- if '~' in source: source = source.split('~',1)[1]
- if source in ['I|', '|I', '|']:
- msg = re.sub(r'^<.*?> ', '', msg, 1)
- if not msg.startswith('!ipw'):
+ source = event.source()
+ source = source.split(b'!', 1)[1]
+ source = source.split(b'@')[0]
+ if b'=' in source: source = source.split(b'=',1)[1]
+ if b'~' in source: source = source.split(b'~',1)[1]
+ if source in [b'I|', b'|I', b'|']:
+ msg = re.sub(b'^<.*?> ', b'', msg, 1)
+ if not msg.startswith(b'!ipw'):
return
ip = msg.strip()
- ip = ip.split(' ',1)[1]
- res = whois.IPWhois(ip.encode('utf-8'))
- output = u''
- output += u'[\x1f%s\x1f] ' % res['source']
+ ip = ip.split(b' ',1)[1]
+ res = whois.IPWhois(ip.decode('utf8'))
+ output = ''
+ output += '[\x1f%s\x1f] ' % res['source']
if ip != res['ipv4addr']:
- output += u'%s (%s)' % (ip, res['ipv4addr'])
+ output += '%s (%s)' % (ip, res['ipv4addr'])
else:
output += ip
- if res.has_key('route'):
- output += u' \x02%(owner)s\x02 (%(route)s/%(netname)s, %(netblock)s)' % res
+ if 'route' in res:
+ output += ' \x02%(owner)s\x02 (%(route)s/%(netname)s, %(netblock)s)' % res
else:
- output += u' : \x02%(owner)s\x02 (%(netname)s, %(netblock)s)' % res
+ output += ' : \x02%(owner)s\x02 (%(netname)s, %(netblock)s)' % res
bot.reply(event, output)
def on_privmsg(bot, connection, event):
24 plugins/mathnet.py
View
@@ -14,30 +14,30 @@ def search(eng):
f = con.execute(q).fetchall()
return f
-
def on_pubmsg(bot, connection, event):
msg = event.arguments()[0]
- source = str(event.source())
- source = source.split('!', 1)[1]
- source = source.split('@')[0]
- if '=' in source: source = source.split('=',1)[1]
- if '~' in source: source = source.split('~',1)[1]
- if source in ['I|', '|I', '|']:
- msg = re.sub(r'^<.*?> ', '', msg, 1)
+ source = event.source()
+ source = source.split(b'!', 1)[1]
+ source = source.split(b'@')[0]
+ if b'=' in source: source = source.split(b'=',1)[1]
+ if b'~' in source: source = source.split(b'~',1)[1]
+ if source in [b'I|', b'|I', b'|']:
+ msg = re.sub(b'^<.*?> ', b'', msg, 1)
- commands = ['mathnet', 'mn']
+ commands = [b'mathnet', b'mn']
for command in commands:
- if msg.startswith('!'+command+" "): break
+ if msg.startswith(b'!'+command+b" "): break
else: return
- output = u''
+ output = ''
try:
+ msg = msg.decode('utf8') # XXX
s = msg.split(' ', 1)[1].strip()
f = search(s)
if f:
output += " / ".join(" = ".join(i) for i in f)
else:
- output += u"'%s': 검색 결과가 없습니다."%s
+ output += "'%s': 검색 결과가 없습니다."%s
except IndexError:
return
Please sign in to comment.
Something went wrong with that request. Please try again.