Upgrade matrix-client to 0.3.2 (#30027)

This commit is contained in:
Fabian Affolter 2019-12-17 16:26:36 +01:00 committed by Pascal Vizeli
parent 115aa2e49c
commit 31cd0af47a
6 changed files with 30 additions and 36 deletions

View File

@ -1,4 +1,4 @@
"""The matrix bot component.""" """The Matrix bot component."""
from functools import partial from functools import partial
import logging import logging
import os import os
@ -19,6 +19,8 @@ from homeassistant.exceptions import HomeAssistantError
import homeassistant.helpers.config_validation as cv import homeassistant.helpers.config_validation as cv
from homeassistant.util.json import load_json, save_json from homeassistant.util.json import load_json, save_json
from .const import DOMAIN, SERVICE_SEND_MESSAGE
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
SESSION_FILE = ".matrix.conf" SESSION_FILE = ".matrix.conf"
@ -31,10 +33,7 @@ CONF_EXPRESSION = "expression"
EVENT_MATRIX_COMMAND = "matrix_command" EVENT_MATRIX_COMMAND = "matrix_command"
DOMAIN = "matrix"
COMMAND_SCHEMA = vol.All( COMMAND_SCHEMA = vol.All(
# Basic Schema
vol.Schema( vol.Schema(
{ {
vol.Exclusive(CONF_WORD, "trigger"): cv.string, vol.Exclusive(CONF_WORD, "trigger"): cv.string,
@ -43,7 +42,6 @@ COMMAND_SCHEMA = vol.All(
vol.Optional(CONF_ROOMS, default=[]): vol.All(cv.ensure_list, [cv.string]), vol.Optional(CONF_ROOMS, default=[]): vol.All(cv.ensure_list, [cv.string]),
} }
), ),
# Make sure it's either a word or an expression command
cv.has_at_least_one_key(CONF_WORD, CONF_EXPRESSION), cv.has_at_least_one_key(CONF_WORD, CONF_EXPRESSION),
) )
@ -65,7 +63,6 @@ CONFIG_SCHEMA = vol.Schema(
extra=vol.ALLOW_EXTRA, extra=vol.ALLOW_EXTRA,
) )
SERVICE_SEND_MESSAGE = "send_message"
SERVICE_SCHEMA_SEND_MESSAGE = vol.Schema( SERVICE_SCHEMA_SEND_MESSAGE = vol.Schema(
{ {
@ -77,7 +74,6 @@ SERVICE_SCHEMA_SEND_MESSAGE = vol.Schema(
def setup(hass, config): def setup(hass, config):
"""Set up the Matrix bot component.""" """Set up the Matrix bot component."""
config = config[DOMAIN] config = config[DOMAIN]
try: try:
@ -138,11 +134,11 @@ class MatrixBot:
# so we only do it once per room. # so we only do it once per room.
self._aliases_fetched_for = set() self._aliases_fetched_for = set()
# word commands are stored dict-of-dict: First dict indexes by room ID # Word commands are stored dict-of-dict: First dict indexes by room ID
# / alias, second dict indexes by the word # / alias, second dict indexes by the word
self._word_commands = {} self._word_commands = {}
# regular expression commands are stored as a list of commands per # Regular expression commands are stored as a list of commands per
# room, i.e., a dict-of-list # room, i.e., a dict-of-list
self._expression_commands = {} self._expression_commands = {}
@ -184,7 +180,7 @@ class MatrixBot:
self.hass.bus.listen_once(EVENT_HOMEASSISTANT_START, handle_startup) self.hass.bus.listen_once(EVENT_HOMEASSISTANT_START, handle_startup)
def _handle_room_message(self, room_id, room, event): def _handle_room_message(self, room_id, room, event):
"""Handle a message sent to a room.""" """Handle a message sent to a Matrix room."""
if event["content"]["msgtype"] != "m.text": if event["content"]["msgtype"] != "m.text":
return return
@ -194,7 +190,7 @@ class MatrixBot:
_LOGGER.debug("Handling message: %s", event["content"]["body"]) _LOGGER.debug("Handling message: %s", event["content"]["body"])
if event["content"]["body"][0] == "!": if event["content"]["body"][0] == "!":
# Could trigger a single-word command. # Could trigger a single-word command
pieces = event["content"]["body"].split(" ") pieces = event["content"]["body"].split(" ")
cmd = pieces[0][1:] cmd = pieces[0][1:]
@ -248,8 +244,7 @@ class MatrixBot:
return room return room
def _join_rooms(self): def _join_rooms(self):
"""Join the rooms that we listen for commands in.""" """Join the Matrix rooms that we listen for commands in."""
for room_id in self._listening_rooms: for room_id in self._listening_rooms:
try: try:
room = self._join_or_get_room(room_id) room = self._join_or_get_room(room_id)
@ -285,8 +280,7 @@ class MatrixBot:
save_json(self._session_filepath, self._auth_tokens) save_json(self._session_filepath, self._auth_tokens)
def _login(self): def _login(self):
"""Login to the matrix homeserver and return the client instance.""" """Login to the Matrix homeserver and return the client instance."""
# Attempt to generate a valid client using either of the two possible # Attempt to generate a valid client using either of the two possible
# login methods: # login methods:
client = None client = None
@ -299,13 +293,12 @@ class MatrixBot:
except MatrixRequestError as ex: except MatrixRequestError as ex:
_LOGGER.warning( _LOGGER.warning(
"Login by token failed, falling back to password. " "Login by token failed, falling back to password: %d, %s",
"login_by_token raised: (%d) %s",
ex.code, ex.code,
ex.content, ex.content,
) )
# If we still don't have a client try password. # If we still don't have a client try password
if not client: if not client:
try: try:
client = self._login_by_password() client = self._login_by_password()
@ -313,20 +306,17 @@ class MatrixBot:
except MatrixRequestError as ex: except MatrixRequestError as ex:
_LOGGER.error( _LOGGER.error(
"Login failed, both token and username/password invalid " "Login failed, both token and username/password invalid: %d, %s",
"login_by_password raised: (%d) %s",
ex.code, ex.code,
ex.content, ex.content,
) )
# Re-raise the error so _setup can catch it
# re-raise the error so _setup can catch it.
raise raise
return client return client
def _login_by_token(self): def _login_by_token(self):
"""Login using authentication token and return the client.""" """Login using authentication token and return the client."""
return MatrixClient( return MatrixClient(
base_url=self._homeserver, base_url=self._homeserver,
token=self._auth_tokens[self._mx_id], token=self._auth_tokens[self._mx_id],
@ -336,7 +326,6 @@ class MatrixBot:
def _login_by_password(self): def _login_by_password(self):
"""Login using password authentication and return the client.""" """Login using password authentication and return the client."""
_client = MatrixClient( _client = MatrixClient(
base_url=self._homeserver, valid_cert_check=self._verify_tls base_url=self._homeserver, valid_cert_check=self._verify_tls
) )
@ -348,7 +337,7 @@ class MatrixBot:
return _client return _client
def _send_message(self, message, target_rooms): def _send_message(self, message, target_rooms):
"""Send the message to the matrix server.""" """Send the message to the Matrix server."""
for target_room in target_rooms: for target_room in target_rooms:
try: try:
@ -356,7 +345,7 @@ class MatrixBot:
_LOGGER.debug(room.send_text(message)) _LOGGER.debug(room.send_text(message))
except MatrixRequestError as ex: except MatrixRequestError as ex:
_LOGGER.error( _LOGGER.error(
"Unable to deliver message to room '%s': (%d): %s", "Unable to deliver message to room '%s': %d, %s",
target_room, target_room,
ex.code, ex.code,
ex.content, ex.content,

View File

@ -0,0 +1,4 @@
"""Constants for the Matrix integration."""
DOMAIN = "matrix"
SERVICE_SEND_MESSAGE = "send_message"

View File

@ -3,7 +3,7 @@
"name": "Matrix", "name": "Matrix",
"documentation": "https://www.home-assistant.io/integrations/matrix", "documentation": "https://www.home-assistant.io/integrations/matrix",
"requirements": [ "requirements": [
"matrix-client==0.2.0" "matrix-client==0.3.2"
], ],
"dependencies": [], "dependencies": [],
"codeowners": [ "codeowners": [

View File

@ -11,32 +11,33 @@ from homeassistant.components.notify import (
) )
import homeassistant.helpers.config_validation as cv import homeassistant.helpers.config_validation as cv
from .const import DOMAIN, SERVICE_SEND_MESSAGE
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
CONF_DEFAULT_ROOM = "default_room" CONF_DEFAULT_ROOM = "default_room"
DOMAIN = "matrix"
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({vol.Required(CONF_DEFAULT_ROOM): cv.string}) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({vol.Required(CONF_DEFAULT_ROOM): cv.string})
def get_service(hass, config, discovery_info=None): def get_service(hass, config, discovery_info=None):
"""Get the Matrix notification service.""" """Get the Matrix notification service."""
return MatrixNotificationService(config.get(CONF_DEFAULT_ROOM)) return MatrixNotificationService(config[CONF_DEFAULT_ROOM])
class MatrixNotificationService(BaseNotificationService): class MatrixNotificationService(BaseNotificationService):
"""Send Notifications to a Matrix Room.""" """Send notifications to a Matrix room."""
def __init__(self, default_room): def __init__(self, default_room):
"""Set up the notification service.""" """Set up the Matrix notification service."""
self._default_room = default_room self._default_room = default_room
def send_message(self, message="", **kwargs): def send_message(self, message="", **kwargs):
"""Send the message to the matrix server.""" """Send the message to the Matrix server."""
target_rooms = kwargs.get(ATTR_TARGET) or [self._default_room] target_rooms = kwargs.get(ATTR_TARGET) or [self._default_room]
service_data = {ATTR_TARGET: target_rooms, ATTR_MESSAGE: message} service_data = {ATTR_TARGET: target_rooms, ATTR_MESSAGE: message}
return self.hass.services.call( return self.hass.services.call(
DOMAIN, "send_message", service_data=service_data DOMAIN, SERVICE_SEND_MESSAGE, service_data=service_data
) )

View File

@ -2,8 +2,8 @@ send_message:
description: Send message to target room(s) description: Send message to target room(s)
fields: fields:
message: message:
description: The message to be sent description: The message to be sent.
example: 'This is a message I am sending to matrix' example: 'This is a message I am sending to matrix'
target: target:
description: A list of room(s) to send the message to description: A list of room(s) to send the message to.
example: '#hasstest:matrix.org' example: '#hasstest:matrix.org'

View File

@ -819,7 +819,7 @@ lyft_rides==0.2
magicseaweed==1.0.3 magicseaweed==1.0.3
# homeassistant.components.matrix # homeassistant.components.matrix
matrix-client==0.2.0 matrix-client==0.3.2
# homeassistant.components.maxcube # homeassistant.components.maxcube
maxcube-api==0.1.0 maxcube-api==0.1.0