Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for multiple match regexs #2009

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 20 additions & 2 deletions opsdroid/events.py
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@

return result

def update_entity(self, name, value, confidence=None):
def update_entity(self, name, value, confidence=None, append=False):
"""Add or update an entitiy.

Adds or updates an entitiy entry for an event.
Expand All @@ -166,9 +166,27 @@
name (string): Name of entity
value (string): Value of entity
confidence (float, optional): Confidence that entity is correct
append (bool, optional): Append the entity to a list with exisitng
entities of the same name. If False will replace the previous
entity.

"""
self.entities[name] = {"value": value, "confidence": confidence}
entity_dict = {"value": value, "confidence": confidence}
# Handle multiple matches:
if name in self.entities and append:
if isinstance(self.entities[name], dict):
new_entity = [self.entities[name], entity_dict]
elif isinstance(self.entities[name], list):
new_entity = self.entities[name] + [entity_dict]

Check warning on line 180 in opsdroid/events.py

View check run for this annotation

Codecov / codecov/patch

opsdroid/events.py#L179-L180

Added lines #L179 - L180 were not covered by tests
else:
# We would only end up here if someone else has modified entities
raise ValueError(
"Can't append a second entity to an existing entity"
f" of type {type(self.entities[name])} with the same name."
) # pragma: no cover
else:
new_entity = entity_dict
self.entities[name] = new_entity

def get_entity(self, name):
"""Get the value of an entity by name.
Expand Down
13 changes: 11 additions & 2 deletions opsdroid/parsers/regex.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,10 @@ def is_case_sensitive():
matched_regex = regex.search(opts["expression"], text, is_case_sensitive())
elif opts["matching_condition"].lower() == "fullmatch":
matched_regex = regex.fullmatch(opts["expression"], text, is_case_sensitive())
elif opts["matching_condition"].lower() == "findall":
matched_regex = list(
regex.finditer(opts["expression"], text, is_case_sensitive())
)
else:
matched_regex = regex.match(opts["expression"], text, is_case_sensitive())
return matched_regex
Expand All @@ -40,8 +44,13 @@ async def parse_regex(opsdroid, skills, message):
matched_regex = await match_regex(message.text, opts)
if matched_regex:
message.regex = matched_regex
for regroup, value in matched_regex.groupdict().items():
message.update_entity(regroup, value, None)
# If we have used findall then we have an iterable
# if we haven't make it one so we can use the same codepath
if opts["matching_condition"] != "findall":
matched_regex = [matched_regex]
for match in matched_regex:
for regroup, value in match.groupdict().items():
message.update_entity(regroup, value, None, append=True)
matched_skills.append(
{
"score": await calculate_score(
Expand Down
24 changes: 24 additions & 0 deletions tests/test_parser_regex.py
Original file line number Diff line number Diff line change
Expand Up @@ -164,3 +164,27 @@ async def test_parse_regex_identically_named_groups_entities(self):
self.assertEqual(len(parsed_message.entities.keys()), 1)
self.assertTrue("name" in parsed_message.entities.keys())
self.assertEqual(parsed_message.entities["name"]["value"], "opsdroid")

async def test_parse_regex_findall(self):
with OpsDroid() as opsdroid:
regex = r"Hello (?P<name>\w+)|Hi (?P<name>\w+)"

mock_skill_named_groups = await self.getMockSkill()
opsdroid.skills.append(
match_regex(regex, matching_condition="findall")(
mock_skill_named_groups
)
)

mock_connector = amock.CoroutineMock()
message = Message(
"Hi opsdroid, Hello world", "user", "default", mock_connector
)

[skill] = await opsdroid.get_ranked_skills(opsdroid.skills, message)
parsed_message = skill["message"]
self.assertEqual(len(parsed_message.entities.keys()), 1)
self.assertEqual(len(parsed_message.entities["name"]), 2)
self.assertTrue("name" in parsed_message.entities.keys())
self.assertEqual(parsed_message.entities["name"][0]["value"], "opsdroid")
self.assertEqual(parsed_message.entities["name"][1]["value"], "world")
Loading