-
-
Notifications
You must be signed in to change notification settings - Fork 32.7k
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
Add config flow to discord #61069
Merged
Merged
Add config flow to discord #61069
Changes from 8 commits
Commits
Show all changes
17 commits
Select commit
Hold shift + click to select a range
927ba43
Add config flow to discord
tkdrob c63b546
fix requirements
tkdrob 77b63b0
Merge branch 'dev' of https://github.com/home-assistant/core into dis…
tkdrob b38e5ef
Merge branch 'dev' of https://github.com/home-assistant/core into dis…
tkdrob accca4e
Add config flow to discord
tkdrob 7cd146b
Merge branch 'dev' of https://github.com/home-assistant/core into dis…
tkdrob 0cd5403
uno mas
tkdrob 0292822
fix mypy
tkdrob 1aa98fa
Merge branch 'dev' of https://github.com/home-assistant/core into dis…
tkdrob e5023c7
Merge branch 'dev' of https://github.com/home-assistant/core into dis…
tkdrob 13f1d57
rework
tkdrob 0d574aa
uno mas
tkdrob 31528a0
Merge branch 'dev' of https://github.com/home-assistant/core into dis…
tkdrob 6ed2892
uno mas
tkdrob 4189c12
uno mas
tkdrob 36b129a
Merge branch 'dev' of https://github.com/home-assistant/core into dis…
tkdrob 459a8ac
Merge branch 'dev' of https://github.com/home-assistant/core into dis…
tkdrob File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1 +1,63 @@ | ||
"""The discord integration.""" | ||
from aiohttp.client_exceptions import ClientConnectorError | ||
import nextcord | ||
|
||
from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry | ||
from homeassistant.const import CONF_PLATFORM, CONF_TOKEN, Platform | ||
from homeassistant.core import HomeAssistant | ||
from homeassistant.exceptions import ConfigEntryAuthFailed, ConfigEntryNotReady | ||
from homeassistant.helpers import discovery | ||
from homeassistant.helpers.typing import ConfigType | ||
|
||
from .const import DOMAIN | ||
|
||
PLATFORMS = [Platform.NOTIFY] | ||
|
||
|
||
async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool: | ||
"""Set up the Discord component.""" | ||
# Iterate all entries for notify to only get Discord | ||
if Platform.NOTIFY in config: | ||
for entry in config[Platform.NOTIFY]: | ||
if entry[CONF_PLATFORM] == DOMAIN: | ||
hass.async_create_task( | ||
hass.config_entries.flow.async_init( | ||
DOMAIN, context={"source": SOURCE_IMPORT}, data=entry | ||
) | ||
) | ||
|
||
return True | ||
|
||
|
||
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: | ||
"""Set up Discord from a config entry.""" | ||
nextcord.VoiceClient.warn_nacl = False | ||
discord_bot = nextcord.Client() | ||
try: | ||
await discord_bot.login(entry.data[CONF_TOKEN]) | ||
except nextcord.LoginFailure as ex: | ||
raise ConfigEntryAuthFailed("Invalid token given") from ex | ||
except (ClientConnectorError, nextcord.HTTPException, nextcord.NotFound) as ex: | ||
raise ConfigEntryNotReady("Failed to connect") from ex | ||
await discord_bot.close() | ||
|
||
hass.data.setdefault(DOMAIN, {})[entry.entry_id] = entry.data | ||
|
||
hass.async_create_task( | ||
discovery.async_load_platform( | ||
hass, | ||
Platform.NOTIFY, | ||
DOMAIN, | ||
hass.data[DOMAIN][entry.entry_id], | ||
hass.data[DOMAIN], | ||
) | ||
) | ||
|
||
return True | ||
|
||
|
||
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: | ||
"""Unload a config entry.""" | ||
if unload_ok := await hass.config_entries.async_unload_platforms(entry, PLATFORMS): | ||
hass.data[DOMAIN].pop(entry.entry_id) | ||
return unload_ok | ||
tkdrob marked this conversation as resolved.
Show resolved
Hide resolved
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,104 @@ | ||
"""Config flow for Discord integration.""" | ||
from __future__ import annotations | ||
|
||
import logging | ||
|
||
from aiohttp.client_exceptions import ClientConnectorError | ||
import nextcord | ||
import voluptuous as vol | ||
|
||
from homeassistant import config_entries | ||
from homeassistant.const import CONF_NAME, CONF_TOKEN | ||
from homeassistant.data_entry_flow import FlowResult | ||
|
||
from .const import DEFAULT_NAME, DOMAIN | ||
|
||
_LOGGER = logging.getLogger(__name__) | ||
|
||
|
||
class DiscordFlowHandler(config_entries.ConfigFlow, domain=DOMAIN): | ||
"""Handle a config flow for Discord.""" | ||
|
||
async def async_step_reauth(self, config: dict[str, str]) -> FlowResult: | ||
"""Handle a reauthorization flow request.""" | ||
return await self.async_step_reauth_confirm() | ||
|
||
async def async_step_reauth_confirm( | ||
self, user_input: dict[str, str] | None = None | ||
) -> FlowResult: | ||
"""Confirm reauth dialog.""" | ||
if user_input is None: | ||
return self.async_show_form( | ||
step_id="reauth_confirm", | ||
data_schema=vol.Schema({vol.Required(CONF_TOKEN): str}), | ||
errors={}, | ||
) | ||
|
||
return await self.async_step_user(user_input) | ||
tkdrob marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
async def async_step_user( | ||
self, user_input: dict[str, str] | None = None | ||
) -> FlowResult: | ||
"""Handle a flow initiated by the user.""" | ||
errors = {} | ||
|
||
if user_input is not None: | ||
token = user_input[CONF_TOKEN] | ||
name = user_input.get(CONF_NAME, DEFAULT_NAME) | ||
|
||
error, unique_id = await _async_try_connect(token) | ||
entry = await self.async_set_unique_id(unique_id) | ||
if entry and self.source == config_entries.SOURCE_REAUTH: | ||
self.hass.config_entries.async_update_entry(entry, data=user_input) | ||
await self.hass.config_entries.async_reload(entry.entry_id) | ||
return self.async_abort(reason="reauth_successful") | ||
tkdrob marked this conversation as resolved.
Show resolved
Hide resolved
|
||
self._abort_if_unique_id_configured() | ||
if error is None: | ||
return self.async_create_entry( | ||
title=name, | ||
data={CONF_TOKEN: token, CONF_NAME: name}, | ||
) | ||
errors["base"] = error | ||
|
||
user_input = user_input or {} | ||
return self.async_show_form( | ||
step_id="user", | ||
data_schema=vol.Schema( | ||
{ | ||
vol.Required(CONF_TOKEN, default=user_input.get(CONF_TOKEN)): str, | ||
vol.Required( | ||
CONF_NAME, default=user_input.get(CONF_NAME, DEFAULT_NAME) | ||
): str, | ||
tkdrob marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} | ||
), | ||
errors=errors, | ||
) | ||
|
||
async def async_step_import(self, import_config: dict[str, str]) -> FlowResult: | ||
"""Import a config entry from configuration.yaml.""" | ||
_LOGGER.warning( | ||
"Discord yaml config with partial key %s has been imported. Please remove it", | ||
tkdrob marked this conversation as resolved.
Show resolved
Hide resolved
|
||
import_config[CONF_TOKEN][0:4], | ||
) | ||
for entry in self._async_current_entries(): | ||
if entry.data[CONF_TOKEN] == import_config[CONF_TOKEN]: | ||
return self.async_abort(reason="already_configured") | ||
import_config[CONF_TOKEN] = import_config.pop(CONF_TOKEN) | ||
return await self.async_step_user(import_config) | ||
|
||
|
||
async def _async_try_connect(token: str) -> tuple[str | None, str | None]: | ||
"""Try connecting to Discord.""" | ||
discord_bot = nextcord.Client() | ||
try: | ||
await discord_bot.login(token) | ||
info = await discord_bot.application_info() | ||
except nextcord.LoginFailure: | ||
return "invalid_auth", None | ||
except (ClientConnectorError, nextcord.HTTPException, nextcord.NotFound): | ||
return "cannot_connect", None | ||
except Exception: # pylint: disable=broad-except | ||
_LOGGER.exception("Unexpected exception") | ||
return "unknown", None | ||
await discord_bot.close() | ||
return None, str(info.id) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
"""Constants for the Discord integration.""" | ||
|
||
from typing import Final | ||
|
||
DEFAULT_NAME = "Discord" | ||
DOMAIN: Final = "discord" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,9 +1,10 @@ | ||
{ | ||
"domain": "discord", | ||
"name": "Discord", | ||
"config_flow": true, | ||
"documentation": "https://www.home-assistant.io/integrations/discord", | ||
"requirements": ["nextcord==2.0.0a8"], | ||
"codeowners": [], | ||
"codeowners": ["@tkdrob"], | ||
"iot_class": "cloud_push", | ||
"loggers": ["discord"] | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
{ | ||
"config": { | ||
"step": { | ||
"user": { | ||
"title": "Discord Notifications", | ||
tkdrob marked this conversation as resolved.
Show resolved
Hide resolved
|
||
"description": "Refer to the documentation on getting your Discord bot key.\n\nhttps://www.home-assistant.io/integrations/discord", | ||
tkdrob marked this conversation as resolved.
Show resolved
Hide resolved
|
||
"data": { | ||
"api_token": "[%key:common::config_flow::data::api_token%]", | ||
"name": "[%key:common::config_flow::data::name%]" | ||
} | ||
}, | ||
"reauth_confirm": { | ||
"title": "Discord Notifications", | ||
tkdrob marked this conversation as resolved.
Show resolved
Hide resolved
|
||
"description": "Refer to the documentation on getting your Discord bot key.\n\nhttps://www.home-assistant.io/integrations/discord", | ||
tkdrob marked this conversation as resolved.
Show resolved
Hide resolved
|
||
"data": { | ||
"api_token": "[%key:common::config_flow::data::api_token%]" | ||
} | ||
} | ||
}, | ||
"error": { | ||
"cannot_connect": "[%key:common::config_flow::error::cannot_connect%]", | ||
"invalid_auth": "[%key:common::config_flow::error::invalid_auth%]", | ||
"unknown": "[%key:common::config_flow::error::unknown%]" | ||
}, | ||
"abort": { | ||
"already_configured": "[%key:common::config_flow::abort::already_configured_service%]", | ||
"reauth_successful": "[%key:common::config_flow::abort::reauth_successful%]" | ||
} | ||
} | ||
} | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
{ | ||
"config": { | ||
"abort": { | ||
"already_configured": "Service is already configured", | ||
"reauth_successful": "Re-authentication was successful" | ||
}, | ||
"error": { | ||
"cannot_connect": "Failed to connect", | ||
"invalid_auth": "Invalid authentication", | ||
"unknown": "Unexpected error" | ||
}, | ||
"step": { | ||
"user": { | ||
"data": { | ||
"api_token": "Token", | ||
"name": "Name" | ||
}, | ||
"description": "Refer to the documentation on getting your Discord bot key.\n\nhttps://www.home-assistant.io/integrations/discord", | ||
"title": "Discord Notifications" | ||
}, | ||
"reauth_confirm": { | ||
"data": { | ||
"api_token": "Token" | ||
}, | ||
"description": "Refer to the documentation on getting your Discord bot key.\n\nhttps://www.home-assistant.io/integrations/discord", | ||
"title": "Discord Notifications" | ||
} | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -71,6 +71,7 @@ | |
"dexcom", | ||
"dialogflow", | ||
"directv", | ||
"discord", | ||
"dlna_dmr", | ||
"dlna_dms", | ||
"dnsip", | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Same comments as for the slack config flow PR. See the Tibber integration for the correct way to call this function.