2018-12-16 15:38:47 +00:00
|
|
|
"""
|
|
|
|
Defines a matrix bot handler that uses regex to determine if message should be handled
|
|
|
|
"""
|
|
|
|
import re
|
|
|
|
|
|
|
|
from matrix_bot_api.mhandler import MHandler
|
|
|
|
|
|
|
|
|
|
|
|
class MRegexHandler(MHandler):
|
|
|
|
|
|
|
|
# regex_str - Regular expression to test message against
|
|
|
|
#
|
|
|
|
# handle_callback - Function to call if messages matches regex
|
2019-02-27 18:08:09 +00:00
|
|
|
def __init__(self, regex_str, handle_callback, bot):
|
2018-12-16 15:38:47 +00:00
|
|
|
MHandler.__init__(self, self.test_regex, handle_callback)
|
2019-02-27 18:08:09 +00:00
|
|
|
self.name = bot.config['character']['sensitivity_name']
|
|
|
|
|
|
|
|
regex_str_temp = "{} {}".format(self.name, regex_str)
|
|
|
|
self.regex_str = regex_str_temp
|
|
|
|
|
|
|
|
for key,value in bot.aliases.items():
|
|
|
|
if (value == regex_str_temp):
|
|
|
|
self.regex_str += "|{}".format(key)
|
2018-12-16 15:38:47 +00:00
|
|
|
|
|
|
|
def test_regex(self, room, event):
|
2019-02-27 18:08:09 +00:00
|
|
|
r = r'^{}'.format(self.regex_str)
|
|
|
|
|
2018-12-16 15:38:47 +00:00
|
|
|
# Test the message and see if it matches the regex
|
|
|
|
if event['type'] == "m.room.message":
|
2019-02-27 18:08:09 +00:00
|
|
|
if re.search(r, event['content']['body'], re.I):
|
2018-12-16 15:38:47 +00:00
|
|
|
# The message matches the regex, return true
|
|
|
|
return True
|
|
|
|
|
|
|
|
return False
|