[TASK] Implement weird Message-inheriting classes.

This commit is contained in:
Jan Philipp Timme 2015-10-24 23:05:55 +02:00
parent bd825fe160
commit d2db65266d
2 changed files with 50 additions and 39 deletions

4
bot.py
View File

@ -146,10 +146,10 @@ if __name__ == "__main__":
loop = asyncio.get_event_loop() loop = asyncio.get_event_loop()
connection_manager = ConnectionManager(loop) connection_manager = ConnectionManager(loop)
connection_manager.add_endpoint(("irc.freenode.net", 6667), { connection_manager.add_endpoint(("irc.euirc.net", 6667), {
"encoding": "utf-8", "encoding": "utf-8",
"nick": "Pb42", "nick": "Pb42",
"user": "foobar", "user": "foobar2000",
"realname": "Baz McBatzen", "realname": "Baz McBatzen",
"channels": ["#botted"] "channels": ["#botted"]
}) })

85
irc.py
View File

@ -16,66 +16,77 @@ def parse(line):
tmp_args = line.split() tmp_args = line.split()
command, *middle = tmp_args command, *middle = tmp_args
params = middle[:] params = middle[:]
return prefix, subject, command, params, trailing return {"prefix": prefix, "subject": subject, "command": command, "params": params, "trailing": trailing}
class Message(object):
class IrcLine(object):
"""Handles translation between strings and IrcLines """Handles translation between strings and IrcLines
""" """
def __init__(self): _command_map = {}
self.prefix = ""
self.subject = "" def __init__(self, data={"prefix": "", "subject": "", "command": "", "params": "", "trailing": ""}):
self.command = "" self.data = data
self.params = ""
self.trailing = ""
@classmethod @classmethod
def from_string(cls, string): def from_string(cls, string):
instance = cls()
data = parse(string) data = parse(string)
print(data) instance = cls._command_map.get(data["command"].upper(), cls)(data)
instance.prefix = data[0] instance.data = data
instance.subject = data[1]
instance.command = data[2]
instance.params = data[3]
instance.trailing = data[4]
return instance return instance
def __repr__(self): def __repr__(self):
data = self.data
print(data)
e = [] e = []
if self.subject: if data["subject"]:
e.append(self.subject) e.append(data["subject"])
if self.command: if data["command"]:
e.append(self.command) e.append(data["command"])
if self.params: if data["params"]:
e.append(" ".join(self.params)) e.append(" ".join(data["params"]))
if self.trailing: if data["trailing"]:
e.append(":{}".format(self.trailing)) e.append(":{}".format(data["trailing"]))
result = " ".join(e) result = " ".join(e)
if self.prefix: if data["prefix"]:
result = "".join([self.prefix, result]) result = "".join([data["prefix"], result])
return result return result
@classmethod def register_derivative(name, bases, attr):
def kick(cls, channel, user, msg="KICK"): new_cls = type(name, bases, attr)
instance = cls() for cls in bases:
instance.command = "KICK" cmd_map = getattr(cls, '_command_map', None)
instance.params = [channel, user] if cmd_map is not None:
instance.trailing = msg command = name.upper()
return instance if command in cmd_map:
raise KeyError('command {} is already registered to this class'.format(command))
cmd_map[command] = new_cls
return new_cls
class Privmsg(Message, metaclass=register_derivative):
pass
class Kick(Message, metaclass=register_derivative):
def __init__(self, channel=None, user=None, message="KICK", *args, **kwargs):
super(Kick, self).__init__(*args, **kwargs)
self.data.update({
"command": "KICK",
"params": [channel, user],
"trailing": message
})
if __name__ == "__main__": if __name__ == "__main__":
l = IrcLine.from_string(":JPT|NC!~AS@euirc-6f528752.pools.arcor-ip.net JOIN :#euirc") l = Message.from_string(":JPT|NC!~AS@euirc-6f528752.pools.arcor-ip.net JOIN :#euirc")
print(str(l)) print(str(l))
print() print()
l = IrcLine.from_string(":ChanServ!services@euirc.net MODE #Tonari. +ao JPT JPT") l = Message.from_string(":ChanServ!services@euirc.net MODE #Tonari. +ao JPT JPT")
print(str(l)) print(str(l))
print() print()
line = IrcLine.kick("#botted", "JPT", "Du Sack!") line = Kick("#botted", "JPT", "Du Sack!")
print(str(line)) print(str(line))
line2 = IrcLine.from_string(str(line))
line2 = Message.from_string(str(line))
print(str(line2)) print(str(line2))
exit() exit()