Black
This commit is contained in:
1 parent
da05dfe708
commit
4de97abc3a
2676 files changed
+163166
-140084
No files matched your search
@@ -6,59 +6,72 @@ from functools import partial
|
||||
import voluptuous as vol
|
||||
|
||||
import homeassistant.helpers.config_validation as cv
|
||||
from homeassistant.components.notify import (ATTR_TARGET, ATTR_MESSAGE)
|
||||
from homeassistant.const import (CONF_USERNAME, CONF_PASSWORD,
|
||||
CONF_VERIFY_SSL, CONF_NAME,
|
||||
EVENT_HOMEASSISTANT_STOP,
|
||||
EVENT_HOMEASSISTANT_START)
|
||||
from homeassistant.components.notify import ATTR_TARGET, ATTR_MESSAGE
|
||||
from homeassistant.const import (
|
||||
CONF_USERNAME,
|
||||
CONF_PASSWORD,
|
||||
CONF_VERIFY_SSL,
|
||||
CONF_NAME,
|
||||
EVENT_HOMEASSISTANT_STOP,
|
||||
EVENT_HOMEASSISTANT_START,
|
||||
)
|
||||
from homeassistant.util.json import load_json, save_json
|
||||
from homeassistant.exceptions import HomeAssistantError
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
SESSION_FILE = '.matrix.conf'
|
||||
SESSION_FILE = ".matrix.conf"
|
||||
|
||||
CONF_HOMESERVER = 'homeserver'
|
||||
CONF_ROOMS = 'rooms'
|
||||
CONF_COMMANDS = 'commands'
|
||||
CONF_WORD = 'word'
|
||||
CONF_EXPRESSION = 'expression'
|
||||
CONF_HOMESERVER = "homeserver"
|
||||
CONF_ROOMS = "rooms"
|
||||
CONF_COMMANDS = "commands"
|
||||
CONF_WORD = "word"
|
||||
CONF_EXPRESSION = "expression"
|
||||
|
||||
EVENT_MATRIX_COMMAND = 'matrix_command'
|
||||
EVENT_MATRIX_COMMAND = "matrix_command"
|
||||
|
||||
DOMAIN = 'matrix'
|
||||
DOMAIN = "matrix"
|
||||
|
||||
COMMAND_SCHEMA = vol.All(
|
||||
# Basic Schema
|
||||
vol.Schema({
|
||||
vol.Exclusive(CONF_WORD, 'trigger'): cv.string,
|
||||
vol.Exclusive(CONF_EXPRESSION, 'trigger'): cv.is_regex,
|
||||
vol.Required(CONF_NAME): cv.string,
|
||||
vol.Optional(CONF_ROOMS, default=[]):
|
||||
vol.All(cv.ensure_list, [cv.string]),
|
||||
}),
|
||||
vol.Schema(
|
||||
{
|
||||
vol.Exclusive(CONF_WORD, "trigger"): cv.string,
|
||||
vol.Exclusive(CONF_EXPRESSION, "trigger"): cv.is_regex,
|
||||
vol.Required(CONF_NAME): 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),
|
||||
)
|
||||
|
||||
CONFIG_SCHEMA = vol.Schema({
|
||||
DOMAIN: vol.Schema({
|
||||
vol.Required(CONF_HOMESERVER): cv.url,
|
||||
vol.Optional(CONF_VERIFY_SSL, default=True): cv.boolean,
|
||||
vol.Required(CONF_USERNAME): cv.matches_regex("@[^:]*:.*"),
|
||||
vol.Required(CONF_PASSWORD): cv.string,
|
||||
vol.Optional(CONF_ROOMS, default=[]):
|
||||
vol.All(cv.ensure_list, [cv.string]),
|
||||
vol.Optional(CONF_COMMANDS, default=[]): [COMMAND_SCHEMA]
|
||||
})
|
||||
}, extra=vol.ALLOW_EXTRA)
|
||||
CONFIG_SCHEMA = vol.Schema(
|
||||
{
|
||||
DOMAIN: vol.Schema(
|
||||
{
|
||||
vol.Required(CONF_HOMESERVER): cv.url,
|
||||
vol.Optional(CONF_VERIFY_SSL, default=True): cv.boolean,
|
||||
vol.Required(CONF_USERNAME): cv.matches_regex("@[^:]*:.*"),
|
||||
vol.Required(CONF_PASSWORD): cv.string,
|
||||
vol.Optional(CONF_ROOMS, default=[]): vol.All(
|
||||
cv.ensure_list, [cv.string]
|
||||
),
|
||||
vol.Optional(CONF_COMMANDS, default=[]): [COMMAND_SCHEMA],
|
||||
}
|
||||
)
|
||||
},
|
||||
extra=vol.ALLOW_EXTRA,
|
||||
)
|
||||
|
||||
SERVICE_SEND_MESSAGE = 'send_message'
|
||||
SERVICE_SEND_MESSAGE = "send_message"
|
||||
|
||||
SERVICE_SCHEMA_SEND_MESSAGE = vol.Schema({
|
||||
vol.Required(ATTR_MESSAGE): cv.string,
|
||||
vol.Required(ATTR_TARGET): vol.All(cv.ensure_list, [cv.string]),
|
||||
})
|
||||
SERVICE_SCHEMA_SEND_MESSAGE = vol.Schema(
|
||||
{
|
||||
vol.Required(ATTR_MESSAGE): cv.string,
|
||||
vol.Required(ATTR_TARGET): vol.All(cv.ensure_list, [cv.string]),
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def setup(hass, config):
|
||||
@@ -69,18 +82,26 @@ def setup(hass, config):
|
||||
|
||||
try:
|
||||
bot = MatrixBot(
|
||||
hass, os.path.join(hass.config.path(), SESSION_FILE),
|
||||
config[CONF_HOMESERVER], config[CONF_VERIFY_SSL],
|
||||
config[CONF_USERNAME], config[CONF_PASSWORD], config[CONF_ROOMS],
|
||||
config[CONF_COMMANDS])
|
||||
hass,
|
||||
os.path.join(hass.config.path(), SESSION_FILE),
|
||||
config[CONF_HOMESERVER],
|
||||
config[CONF_VERIFY_SSL],
|
||||
config[CONF_USERNAME],
|
||||
config[CONF_PASSWORD],
|
||||
config[CONF_ROOMS],
|
||||
config[CONF_COMMANDS],
|
||||
)
|
||||
hass.data[DOMAIN] = bot
|
||||
except MatrixRequestError as exception:
|
||||
_LOGGER.error("Matrix failed to log in: %s", str(exception))
|
||||
return False
|
||||
|
||||
hass.services.register(
|
||||
DOMAIN, SERVICE_SEND_MESSAGE, bot.handle_send_message,
|
||||
schema=SERVICE_SCHEMA_SEND_MESSAGE)
|
||||
DOMAIN,
|
||||
SERVICE_SEND_MESSAGE,
|
||||
bot.handle_send_message,
|
||||
schema=SERVICE_SCHEMA_SEND_MESSAGE,
|
||||
)
|
||||
|
||||
return True
|
||||
|
||||
@@ -88,8 +109,17 @@ def setup(hass, config):
|
||||
class MatrixBot:
|
||||
"""The Matrix Bot."""
|
||||
|
||||
def __init__(self, hass, config_file, homeserver, verify_ssl,
|
||||
username, password, listening_rooms, commands):
|
||||
def __init__(
|
||||
self,
|
||||
hass,
|
||||
config_file,
|
||||
homeserver,
|
||||
verify_ssl,
|
||||
username,
|
||||
password,
|
||||
listening_rooms,
|
||||
commands,
|
||||
):
|
||||
"""Set up the client."""
|
||||
self.hass = hass
|
||||
|
||||
@@ -138,8 +168,7 @@ class MatrixBot:
|
||||
"""Handle exceptions raised inside the Matrix SDK."""
|
||||
_LOGGER.error("Matrix exception:\n %s", str(exception))
|
||||
|
||||
self._client.start_listener_thread(
|
||||
exception_handler=handle_matrix_exception)
|
||||
self._client.start_listener_thread(exception_handler=handle_matrix_exception)
|
||||
|
||||
def stop_client(_):
|
||||
"""Run once when Home Assistant stops."""
|
||||
@@ -156,39 +185,39 @@ class MatrixBot:
|
||||
|
||||
def _handle_room_message(self, room_id, room, event):
|
||||
"""Handle a message sent to a room."""
|
||||
if event['content']['msgtype'] != 'm.text':
|
||||
if event["content"]["msgtype"] != "m.text":
|
||||
return
|
||||
|
||||
if event['sender'] == self._mx_id:
|
||||
if event["sender"] == self._mx_id:
|
||||
return
|
||||
|
||||
_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.
|
||||
pieces = event['content']['body'].split(' ')
|
||||
pieces = event["content"]["body"].split(" ")
|
||||
cmd = pieces[0][1:]
|
||||
|
||||
command = self._word_commands.get(room_id, {}).get(cmd)
|
||||
if command:
|
||||
event_data = {
|
||||
'command': command[CONF_NAME],
|
||||
'sender': event['sender'],
|
||||
'room': room_id,
|
||||
'args': pieces[1:]
|
||||
"command": command[CONF_NAME],
|
||||
"sender": event["sender"],
|
||||
"room": room_id,
|
||||
"args": pieces[1:],
|
||||
}
|
||||
self.hass.bus.fire(EVENT_MATRIX_COMMAND, event_data)
|
||||
|
||||
# After single-word commands, check all regex commands in the room
|
||||
for command in self._expression_commands.get(room_id, []):
|
||||
match = command[CONF_EXPRESSION].match(event['content']['body'])
|
||||
match = command[CONF_EXPRESSION].match(event["content"]["body"])
|
||||
if not match:
|
||||
continue
|
||||
event_data = {
|
||||
'command': command[CONF_NAME],
|
||||
'sender': event['sender'],
|
||||
'room': room_id,
|
||||
'args': match.groupdict()
|
||||
"command": command[CONF_NAME],
|
||||
"sender": event["sender"],
|
||||
"room": room_id,
|
||||
"args": match.groupdict(),
|
||||
}
|
||||
self.hass.bus.fire(EVENT_MATRIX_COMMAND, event_data)
|
||||
|
||||
@@ -209,13 +238,13 @@ class MatrixBot:
|
||||
self._aliases_fetched_for.add(room.room_id)
|
||||
|
||||
if room_id_or_alias in room.aliases:
|
||||
_LOGGER.debug("Already in room %s (known as %s)",
|
||||
room.room_id, room_id_or_alias)
|
||||
_LOGGER.debug(
|
||||
"Already in room %s (known as %s)", room.room_id, room_id_or_alias
|
||||
)
|
||||
return room
|
||||
|
||||
room = self._client.join_room(room_id_or_alias)
|
||||
_LOGGER.info("Joined room %s (known as %s)", room.room_id,
|
||||
room_id_or_alias)
|
||||
_LOGGER.info("Joined room %s (known as %s)", room.room_id, room_id_or_alias)
|
||||
return room
|
||||
|
||||
def _join_rooms(self):
|
||||
@@ -225,8 +254,9 @@ class MatrixBot:
|
||||
for room_id in self._listening_rooms:
|
||||
try:
|
||||
room = self._join_or_get_room(room_id)
|
||||
room.add_listener(partial(self._handle_room_message, room_id),
|
||||
"m.room.message")
|
||||
room.add_listener(
|
||||
partial(self._handle_room_message, room_id), "m.room.message"
|
||||
)
|
||||
|
||||
except MatrixRequestError as ex:
|
||||
_LOGGER.error("Could not join room %s: %s", room_id, ex)
|
||||
@@ -244,7 +274,9 @@ class MatrixBot:
|
||||
except HomeAssistantError as ex:
|
||||
_LOGGER.warning(
|
||||
"Loading authentication tokens from file '%s' failed: %s",
|
||||
self._session_filepath, str(ex))
|
||||
self._session_filepath,
|
||||
str(ex),
|
||||
)
|
||||
return {}
|
||||
|
||||
def _store_auth_token(self, token):
|
||||
@@ -271,7 +303,9 @@ class MatrixBot:
|
||||
_LOGGER.warning(
|
||||
"Login by token failed, falling back to password. "
|
||||
"login_by_token raised: (%d) %s",
|
||||
ex.code, ex.content)
|
||||
ex.code,
|
||||
ex.content,
|
||||
)
|
||||
|
||||
# If we still don't have a client try password.
|
||||
if not client:
|
||||
@@ -283,7 +317,9 @@ class MatrixBot:
|
||||
_LOGGER.error(
|
||||
"Login failed, both token and username/password invalid "
|
||||
"login_by_password raised: (%d) %s",
|
||||
ex.code, ex.content)
|
||||
ex.code,
|
||||
ex.content,
|
||||
)
|
||||
|
||||
# re-raise the error so _setup can catch it.
|
||||
raise
|
||||
@@ -298,15 +334,16 @@ class MatrixBot:
|
||||
base_url=self._homeserver,
|
||||
token=self._auth_tokens[self._mx_id],
|
||||
user_id=self._mx_id,
|
||||
valid_cert_check=self._verify_tls)
|
||||
valid_cert_check=self._verify_tls,
|
||||
)
|
||||
|
||||
def _login_by_password(self):
|
||||
"""Login using password authentication and return the client."""
|
||||
from matrix_client.client import MatrixClient
|
||||
|
||||
_client = MatrixClient(
|
||||
base_url=self._homeserver,
|
||||
valid_cert_check=self._verify_tls)
|
||||
base_url=self._homeserver, valid_cert_check=self._verify_tls
|
||||
)
|
||||
|
||||
_client.login_with_password(self._mx_id, self._password)
|
||||
|
||||
@@ -325,9 +362,11 @@ class MatrixBot:
|
||||
except MatrixRequestError as ex:
|
||||
_LOGGER.error(
|
||||
"Unable to deliver message to room '%s': (%d): %s",
|
||||
target_room, ex.code, ex.content)
|
||||
target_room,
|
||||
ex.code,
|
||||
ex.content,
|
||||
)
|
||||
|
||||
def handle_send_message(self, service):
|
||||
"""Handle the send_message service."""
|
||||
self._send_message(service.data[ATTR_MESSAGE],
|
||||
service.data[ATTR_TARGET])
|
||||
self._send_message(service.data[ATTR_MESSAGE], service.data[ATTR_TARGET])
|
||||
Reference in new issue
Block a user