Skip to content

Commit

Permalink
Regex matching
Browse files Browse the repository at this point in the history
  • Loading branch information
thefinn93 committed Jun 26, 2017
1 parent 107e9d5 commit 9734b2c
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 25 deletions.
7 changes: 5 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,16 +15,19 @@ Might put it in pypi eventually

*See `examples/` folder for more complete examples, etc*


A simple example that responds to messages starting with "hi" with the text "Hello!"

```python
from jsbf import Bot
bot = Bot('bin/signal-cli', '+12024561414')

@bot.handle('message')
@bot.handle('^hi')
def message_responder(message):
return {
"type": "send",
"recipientNumber": message['envelope']['source'],
"messageBody": message['envelope']['dataMessage']['message'],
"messageBody": "Hello!",
"id": "1"
}

Expand Down
2 changes: 1 addition & 1 deletion examples/echo.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
bot = Bot(signal_cli_binary, signal_number, dsn)


@bot.handle('message')
@bot.handle()
def message_responder(message):
logging.info("%s: %s", message['envelope']['source'], message['envelope']['dataMessage']['message'])
return {
Expand Down
51 changes: 29 additions & 22 deletions jsbf/bot.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import subprocess
import json
import re
import logging

try:
import raven
except ImportError:
Expand All @@ -11,7 +13,7 @@

class Bot(object):

handlers = {}
handlers = []

def __init__(self, binary, number, dsn=None):
self.binary = binary
Expand All @@ -23,34 +25,39 @@ def __init__(self, binary, number, dsn=None):
else:
self.sentry = raven.Client(dsn)

def register_handler(self, msg_type, handler):
if msg_type not in self.handlers:
self.handlers[msg_type] = []
self.handlers[msg_type].append(handler)
def register_handler(self, handler, regex, group):
if not isinstance(regex, re._pattern_type):
regex = re.compile(regex)
self.handlers.append((handler, regex, group))

def handle(self, regex=None, group=None):
regex = '' if regex is None else regex

def handle(self, msg_type):
def decorator(f):
self.register_handler(msg_type, f)
self.register_handler(f, regex=regex, group=group)
return f
return decorator

def _handle_message(self, message):
msg_type = message.get('type')
logger.debug("Handling %s message", msg_type)
responses = []
if msg_type in self.handlers:
for handler in self.handlers[msg_type]:
logger.debug("Running %s handler %s", handler.__name__, msg_type)
try:
handler_response = handler(message)
if handler_response is not None:
responses.append(json.dumps(handler_response))
except:
logger.exception("An error occured while running %s handler %s", msg_type, handler.__name__)
if self.sentry is not None:
self.sentry.captureException()
else:
logger.debug("No handler for message type %s", msg_type)
if message.get('type') == "message" and not message.get('envelope', {}).get('isReceipt', True):
logger.debug("Handling message %s", json.dumps(message, indent=4))
datamessage = message.get('envelope', {}).get('dataMessage', {})
text = datamessage.get('message')
group = datamessage.get('groupInfo')
for handler in self.handlers:
if (handler[2] is None or handler[2] == group is None):
match = handler[1].match(text)
if match is not None:
logger.debug("Running handler %s", handler[0].__name__)
try:
handler_response = handler[0](message)
if handler_response is not None:
responses.append(json.dumps(handler_response))
except:
logger.exception("An error occured while running handler %s", handler[0].__name__)
if self.sentry is not None:
self.sentry.captureException()
return responses

def run(self):
Expand Down

0 comments on commit 9734b2c

Please sign in to comment.