Created
January 6, 2012 17:08
-
-
Save borntyping/1571471 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import re | |
regex = { | |
'prefix' : re.compile("^:(?P<nick>.+)(?:!(?P<user>.+))(?:@(?P<host>.+))") | |
} | |
def read_message (message): | |
""" | |
Turn an IRC message into an object | |
http://www.irchelp.org/irchelp/rfc/chapter2.html#c2_3 | |
2.3.1 Message format | |
The extracted message is parsed into the components <prefix>, <command> and list of parameters matched either by <middle> or <trailing> components. | |
The BNF representation for this is: | |
<message> ::= | |
[':' <prefix> <space> ] <command> <params> | |
<prefix> ::= | |
<servername> | <nick> [ '!' <user> ] [ '@' <host> ] | |
<command> ::= | |
<letter> { <letter> } | <number> <number> <number> | |
<space> ::= | |
' ' { ' ' } | |
<params> ::= | |
<space> [ ':' <trailing> | <middle> <params> ] | |
<middle> ::= | |
<Any *non-empty* sequence of characters not including SPACE or NUL or CR or LF, the first of which may not be ':'> | |
<trailing> ::= | |
<Any, possibly *empty*, sequence of characters not including NUL or CR or LF> | |
""" | |
message = re.search("^(?::(?P<prefix>\S+) )?(?P<command>\w+|\d\d\d) (?P<params>.+)$", message) | |
if message: | |
put = lambda x: "<%s> %s" % (x, message.group(x)) | |
print (put('prefix'), put('command'), put('params')), "\t", | |
### THIS: | |
params, trailing = message.group('params').split(), None | |
if params[-1][0] == ':': | |
params, trailing = params[:-1], params[-1] | |
print params, trailing | |
### OR THIS: | |
if ' :' in params: | |
params, trailing = line.split(' :', 1) | |
else: | |
params, trailing = params, None | |
params.split() | |
### | |
else: | |
print message | |
return |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment