Skip to content

Commit

Permalink
feat(robot): add match result to regex handler
Browse files Browse the repository at this point in the history
* 使正则匹配到的对象传入处理函数

* 修改以符合pep8

* 当检查结果为bool类型时传入函数None

* 添加相关测试

* 测试不同环境下到底存在什么问题

* 修复测试中Unicode的问题

* 加入文档
  • Loading branch information
cxgreat2014 authored and helloqiu committed Jun 16, 2018
1 parent 59696d5 commit 58ef855
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 7 deletions.
20 changes: 17 additions & 3 deletions docs/handlers.rst
Expand Up @@ -160,12 +160,18 @@ robot.filter —— 回应有指定文本的消息

@robot.filter(re.compile(".*?bb.*?"))
def b():
return "正文中含有 b "
return "正文中含有 bb "

@robot.filter(re.compile(".*?c.*?"), "d")
def c():
return "正文中含有 c 或正文为 d"

@robot.filter(re.compile("(.*)?e(.*)?"), "f")
def d(message, session, match):
if match:
return "正文为 " + match.group(1) + "e" + match.group(2)
return "正文为 f"

这段代码等价于 ::

@robot.text
Expand All @@ -176,15 +182,23 @@ robot.filter —— 回应有指定文本的消息


@robot.text
def b():
def b(message):
if re.compile(".*?bb.*?").match(message.content):
return "正文中含有 b "

@robot.text
def c():
def c(message):
if re.compile(".*?c.*?").match(message.content) or message.content == "d":
return "正文中含有 c 或正文为 d"

@robot.text
def d(message):
match = re.compile("(.*)?e(.*)?").match(message.content)
if match:
return "正文为 " + match.group(1) + "e" + match.group(2)
if message.content == "f":
return "正文为 f"

如果你想通过修饰符以外的方法添加 filter,可以使用 :func:`~werobot.robot.BaseRoBot.add_filter` 方法 ::

def say_hello():
Expand Down
7 changes: 5 additions & 2 deletions tests/test_robot.py
Expand Up @@ -177,8 +177,10 @@ def _3():
pass
robot = WeRoBot(enable_session=False)

@robot.filter("帮助", "跪求帮助", re.compile(".*?help.*?"))
def _():
@robot.filter("帮助", "跪求帮助", re.compile("(.*?)help.*?"))
def _(message, session, match):
if match and match.group(1) == u"小姐姐":
return "本小姐就帮你一下"
return "就不帮"

assert len(robot._handlers["text"]) == 3
Expand All @@ -195,6 +197,7 @@ def _4():
assert tester.send_xml(_make_xml("帮助"))._args['content'] == u"就不帮"
assert tester.send_xml(_make_xml("跪求帮助"))._args['content'] == u"就不帮"
assert tester.send_xml(_make_xml("ooohelp"))._args['content'] == u"就不帮"
assert tester.send_xml(_make_xml("小姐姐help"))._args['content'] == u"本小姐就帮你一下"


def test_register_not_callable_object():
Expand Down
7 changes: 5 additions & 2 deletions werobot/robot.py
Expand Up @@ -547,8 +547,11 @@ def _check_content(message):

@self.text
def _f(message, session=None):
if _check_content(message):
return func(*[message, session][:argc])
_check_result = _check_content(message)
if _check_result:
if isinstance(_check_result, bool):
_check_result = None
return func(*[message, session, _check_result][:argc])

def parse_message(
self, body, timestamp=None, nonce=None, msg_signature=None
Expand Down

0 comments on commit 58ef855

Please sign in to comment.