Skip to content

Improvements and fixes #18

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

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
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
60 changes: 37 additions & 23 deletions matrix_bot_api/matrix_bot_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,44 +6,44 @@

class MatrixBotAPI:

# username - Matrix username
# password - Matrix password
# server - Matrix server url : port
# rooms - List of rooms ids to operate in, or None to accept all rooms
def __init__(self, username, password, server, rooms=None):
# username - Matrix username
# password - Matrix password
# server - Matrix server url : port
# rooms - List of rooms ids to operate in, or None to accept all rooms
# accept_invites - If true, accept invites to rooms
def __init__(self, username, password, server, rooms=None, accept_invites=True):
self.username = username

# Authenticate with given credentials
self.client = MatrixClient(server)
try:
self.client.login_with_password(username, password)
self.client.login(username, password)
except MatrixRequestError as e:
print(e)
if e.code == 403:
print("Bad username/password")
except Exception as e:
print("Invalid server URL")
traceback.print_exc()

# Store allowed rooms
self.rooms = rooms
print(e)

# Store allowed rooms. If rooms is None, store empty list
# of rooms and add all rooms we're currently in
if rooms:
self.rooms = rooms
else:
self.rooms = []
for room in self.client.rooms.values():
self.rooms.append(room)
print('Total rooms: ', len(self.rooms))
# Store empty list of handlers
self.handlers = []

# If rooms is None, we should listen for invites and automatically accept them
if rooms is None:
# we should listen for invites and automatically accept them
if accept_invites:
self.client.add_invite_listener(self.handle_invite)
self.rooms = []

# Add all rooms we're currently in to self.rooms and add their callbacks
for room_id, room in self.client.get_rooms().items():
room.add_listener(self.handle_message)
self.rooms.append(room_id)
else:
# Add the message callback for all specified rooms
for room in self.rooms:
room.add_listener(self.handle_message)
# Add handlers for all rooms
for room in self.rooms:
room.add_listener(self.handle_message)

def add_handler(self, handler):
self.handlers.append(handler)
Expand All @@ -55,7 +55,7 @@ def handle_message(self, room, event):

# Loop through all installed handlers and see if they need to be called
for handler in self.handlers:
if handler.test_callback(room, event):
if handler.test_callback(event):
# This handler needs to be called
try:
handler.handle_callback(room, event)
Expand All @@ -73,6 +73,20 @@ def handle_invite(self, room_id, state):
# Add room to list
self.rooms.append(room)

def send_message(self, message, room_id=None, room_alias=None):
if not room_id:
if not room_alias: # send to all rooms if no room specified
for room in self.rooms:
room.send_text(message)
return True
else: # no ID but we have alias, so get room_id from it
room_id = self.client.api.get_room_id(room_alias)
room = self.client.rooms.get(room_id)
if room and room in self.rooms:
room.send_text(message)
return True
return False

def start_polling(self):
# Starts polling for messages
self.client.start_listener_thread()
Expand Down
5 changes: 2 additions & 3 deletions matrix_bot_api/mcommand_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@
Defines a matrix bot handler for commands
"""
import re

from matrix_bot_api.mhandler import MHandler
from .mhandler import MHandler


class MCommandHandler(MHandler):
Expand All @@ -17,7 +16,7 @@ def __init__(self, command, handle_callback, cmd_char='!'):
self.cmd_char = cmd_char

# Function called by Matrix bot api to determine whether or not to handle this message
def test_command(self, room, event):
def test_command(self, event):
# Test the message to see if it has our command
if event['type'] == "m.room.message":
if re.match(self.cmd_char + self.command, event['content']['body']):
Expand Down
2 changes: 1 addition & 1 deletion matrix_bot_api/mhandler.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"""


class MHandler(object):
class MHandler:
# test_callback - function that takes a room and event and returns a boolean
# indicating whether we should pass the message on to handle_callback
#
Expand Down
2 changes: 1 addition & 1 deletion matrix_bot_api/mregex_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ def __init__(self, regex_str, handle_callback):
MHandler.__init__(self, self.test_regex, handle_callback)
self.regex_str = regex_str

def test_regex(self, room, event):
def test_regex(self, event):
# Test the message and see if it matches the regex
if event['type'] == "m.room.message":
if re.search(self.regex_str, event['content']['body']):
Expand Down