plugable-matrix-bot/matrix_bot_api/mregex_handler.py

35 lines
1.1 KiB
Python

"""
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
def __init__(self, regex_str, handle_callback, bot):
MHandler.__init__(self, self.test_regex, handle_callback)
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)
def test_regex(self, room, event):
r = r'^{}'.format(self.regex_str)
# Test the message and see if it matches the regex
if event['type'] == "m.room.message":
if re.search(r, event['content']['body'], re.I):
# The message matches the regex, return true
return True
return False