core/homeassistant/components/discord/notify.py

97 lines
3.2 KiB
Python
Raw Normal View History

"""Discord platform for notify component."""
import logging
import os.path
2019-10-15 08:06:29 +00:00
import discord
import voluptuous as vol
2019-07-31 19:25:30 +00:00
from homeassistant.components.notify import (
ATTR_DATA,
ATTR_TARGET,
PLATFORM_SCHEMA,
BaseNotificationService,
)
from homeassistant.const import CONF_TOKEN
import homeassistant.helpers.config_validation as cv
_LOGGER = logging.getLogger(__name__)
2019-07-31 19:25:30 +00:00
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({vol.Required(CONF_TOKEN): cv.string})
2019-07-31 19:25:30 +00:00
ATTR_IMAGES = "images"
def get_service(hass, config, discovery_info=None):
"""Get the Discord notification service."""
token = config[CONF_TOKEN]
return DiscordNotificationService(hass, token)
class DiscordNotificationService(BaseNotificationService):
"""Implement the notification service for Discord."""
def __init__(self, hass, token):
"""Initialize the service."""
self.token = token
self.hass = hass
def file_exists(self, filename):
"""Check if a file exists on disk and is in authorized path."""
if not self.hass.config.is_allowed_path(filename):
return False
return os.path.isfile(filename)
async def async_send_message(self, message, **kwargs):
"""Login to Discord, send message to channel(s) and log out."""
discord.VoiceClient.warn_nacl = False
discord_bot = discord.Client()
2019-04-30 20:12:39 +00:00
images = None
2017-03-04 00:03:10 +00:00
if ATTR_TARGET not in kwargs:
_LOGGER.error("No target specified")
return None
data = kwargs.get(ATTR_DATA) or {}
2019-04-30 20:12:39 +00:00
if ATTR_IMAGES in data:
2020-04-04 21:14:47 +00:00
images = []
2019-04-30 20:12:39 +00:00
for image in data.get(ATTR_IMAGES):
image_exists = await self.hass.async_add_executor_job(
2019-07-31 19:25:30 +00:00
self.file_exists, image
)
if image_exists:
images.append(image)
else:
_LOGGER.warning("Image not found: %s", image)
# pylint: disable=unused-variable
2017-03-03 22:15:03 +00:00
@discord_bot.event
async def on_ready():
2017-03-04 00:43:59 +00:00
"""Send the messages when the bot is ready."""
try:
for channelid in kwargs[ATTR_TARGET]:
2019-04-30 20:12:39 +00:00
channelid = int(channelid)
channel = discord_bot.get_channel(
channelid
) or discord_bot.get_user(channelid)
2019-04-30 20:12:39 +00:00
if channel is None:
2019-07-31 19:25:30 +00:00
_LOGGER.warning("Channel not found for id: %s", channelid)
2019-04-30 20:12:39 +00:00
continue
# Must create new instances of File for each channel.
files = None
if images:
2020-04-04 21:14:47 +00:00
files = []
2019-04-30 20:12:39 +00:00
for image in images:
files.append(discord.File(image))
await channel.send(message, files=files)
2019-07-31 19:25:30 +00:00
except (discord.errors.HTTPException, discord.errors.NotFound) as error:
_LOGGER.warning("Communication error: %s", error)
await discord_bot.logout()
await discord_bot.close()
2019-04-30 20:12:39 +00:00
# Using reconnect=False prevents multiple ready events to be fired.
await discord_bot.start(self.token, reconnect=False)