Skip to content

Instantly share code, notes, and snippets.

@borntyping
Created January 31, 2012 02:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save borntyping/1708371 to your computer and use it in GitHub Desktop.
Save borntyping/1708371 to your computer and use it in GitHub Desktop.
Parser for irc messages
"""
Parses incoming IRC messages, and formats outgoing IRC messages.
"""
def parse_message (string):
""" Parse an IRC message in the form:
[:{source} ]{command}[ parameters][ :{trailing}]
"""
# Default variables for parameters and trailing,
# as it is possible neither will be assigned
parameters, trailing = [], None
# Remove the source from the string if it has one
source, string = string[1:].split(' ',1) if string[0] == ':' else None, string
# Get the command from the string
command, string = get_token(string)
# While there are still elements in the string to parse,
# get either the trailing element or another parameter
while string:
if string[0] == ':':
trailing = string[1:].strip()
break
else:
param, string = get_token(string)
parameters.append(param)
# Return the message as a tuple of 4 elements
return source, command, parameters, trailing
def get_token (string):
split = string.split(' ',1)
return (split[0], None) if len(split) == 1 else tuple(split)
def format_message (command, parameters = None, trailing = None):
# Is this actually needed?
if not parameters and not trailing:
raise Exception("Either parameters or trailing must be used!")
string = "{} ".format(command)
# Join the parameters into a space seperated string,
# then append them to the string
if parameters: string = "{} {}".format(string, ' '.join(parameters))
# Append the trailing parameter
if trailing: string = "{} :{}".format(string, trailing)
return string
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment