Skip to content

Commit

Permalink
Compile regular expressions on init.
Browse files Browse the repository at this point in the history
  • Loading branch information
Wei En committed Nov 20, 2013
1 parent b75b9dd commit 1ceb515
Showing 1 changed file with 25 additions and 16 deletions.
41 changes: 25 additions & 16 deletions pyrc/bots.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,10 @@ def __init__(self, host, **kwargs):
self.initialized = False
self.listeners = {}

# init funcs
self.add_listeners()
self.addhooks()
self.compile_regex()

def message(self, recipient, s):
"High level interface to sending an IRC message."
Expand Down Expand Up @@ -84,7 +86,7 @@ def run_listeners(self, line):
with all the regular expression's matched subgroups.
"""
for regex, callbacks in self.listeners.iteritems():
match = re.match(regex, line)
match = regex.match(line)

if not match:
continue
Expand Down Expand Up @@ -135,28 +137,35 @@ def parsefuncs(self, channel, sender, message, funcs):
if self.config['break_on_match']: return False
return True

def strip_prefix(self, message):
"""
Checks if the bot was called by a user.
Returns the suffix if so.
Prefixes include the bot's nick as well as a set symbol.
"""
# sort names so names that are substrings work
names = sorted(self.config['names'], key=len, reverse=True)
prefix = self.config['prefix']
def compile_regex(self):
self.compile_strip_prefix()

def compile_strip_prefix(self):
"""
regex example:
^(((BotA|BotB)[,:]?\s+)|%)(.+)$
names = [BotA, BotB]
prefix = %
"""
name_regex_str = r'^(((%s)[,:]?\s+)|%s)(.+)$' % (re.escape("|".join(names)), prefix)
name_regex = re.compile(name_regex_str, re.IGNORECASE)
if name_regex.match(message):
return name_regex.match(message).group(4)

names = self.config['names']
prefix = self.config['prefix']

name_regex_str = r'^(?:(?:(%s)[,:]?\s+)|%s)(.+)$' % (re.escape("|".join(names)), prefix)
self.name_regex = re.compile(name_regex_str, re.IGNORECASE)

def strip_prefix(self, message):
"""
Checks if the bot was called by a user.
Returns the suffix if so.
Prefixes include the bot's nick as well as a set symbol.
"""

match = self.name_regex.match(message)
if match:
return match.group(1)

return None

Expand Down Expand Up @@ -190,7 +199,7 @@ def add_listeners(self):
self._mode)

def add_listener(self, regex, func):
array = self.listeners.setdefault(regex, [])
array = self.listeners.setdefault(re.compile(regex), [])
array.append(func)

# Default listeners
Expand Down

0 comments on commit 1ceb515

Please sign in to comment.