Home Assistant Unofficial Reference 2024.12.1
config_flow.py
Go to the documentation of this file.
1 """Config flow for Slack integration."""
2 
3 from __future__ import annotations
4 
5 import logging
6 
7 from slack import WebClient
8 from slack.errors import SlackApiError
9 import voluptuous as vol
10 
11 from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
12 from homeassistant.const import CONF_API_KEY, CONF_ICON, CONF_NAME, CONF_USERNAME
13 from homeassistant.helpers import aiohttp_client
14 
15 from .const import CONF_DEFAULT_CHANNEL, DOMAIN
16 
17 _LOGGER = logging.getLogger(__name__)
18 
19 CONFIG_SCHEMA = vol.Schema(
20  {
21  vol.Required(CONF_API_KEY): str,
22  vol.Required(CONF_DEFAULT_CHANNEL): str,
23  vol.Optional(CONF_ICON): str,
24  vol.Optional(CONF_USERNAME): str,
25  }
26 )
27 
28 
29 class SlackFlowHandler(ConfigFlow, domain=DOMAIN):
30  """Handle a config flow for Slack."""
31 
32  async def async_step_user(
33  self, user_input: dict[str, str] | None = None
34  ) -> ConfigFlowResult:
35  """Handle a flow initiated by the user."""
36  errors = {}
37 
38  if user_input is not None:
39  error, info = await self._async_try_connect(user_input[CONF_API_KEY])
40  if error is not None:
41  errors["base"] = error
42  elif info is not None:
43  await self.async_set_unique_idasync_set_unique_id(info["team_id"].lower())
44  self._abort_if_unique_id_configured_abort_if_unique_id_configured()
45  return self.async_create_entryasync_create_entryasync_create_entry(
46  title=user_input.get(CONF_NAME, info["team"]),
47  data={CONF_NAME: user_input.get(CONF_NAME, info["team"])}
48  | user_input,
49  )
50 
51  user_input = user_input or {}
52  return self.async_show_formasync_show_formasync_show_form(
53  step_id="user",
54  data_schema=CONFIG_SCHEMA,
55  errors=errors,
56  )
57 
58  async def _async_try_connect(
59  self, token: str
60  ) -> tuple[str, None] | tuple[None, dict[str, str]]:
61  """Try connecting to Slack."""
62  session = aiohttp_client.async_get_clientsession(self.hass)
63  client = WebClient(token=token, run_async=True, session=session)
64 
65  try:
66  info = await client.auth_test()
67  except SlackApiError as ex:
68  if ex.response["error"] == "invalid_auth":
69  return "invalid_auth", None
70  return "cannot_connect", None
71  except Exception:
72  _LOGGER.exception("Unexpected exception")
73  return "unknown", None
74  return None, info
ConfigFlowResult async_step_user(self, dict[str, str]|None user_input=None)
Definition: config_flow.py:34
None _abort_if_unique_id_configured(self, dict[str, Any]|None updates=None, bool reload_on_update=True, *str error="already_configured")
ConfigEntry|None async_set_unique_id(self, str|None unique_id=None, *bool raise_on_progress=True)
ConfigFlowResult async_create_entry(self, *str title, Mapping[str, Any] data, str|None description=None, Mapping[str, str]|None description_placeholders=None, Mapping[str, Any]|None options=None)
ConfigFlowResult async_show_form(self, *str|None step_id=None, vol.Schema|None data_schema=None, dict[str, str]|None errors=None, Mapping[str, str]|None description_placeholders=None, bool|None last_step=None, str|None preview=None)
_FlowResultT async_show_form(self, *str|None step_id=None, vol.Schema|None data_schema=None, dict[str, str]|None errors=None, Mapping[str, str]|None description_placeholders=None, bool|None last_step=None, str|None preview=None)
_FlowResultT async_create_entry(self, *str|None title=None, Mapping[str, Any] data, str|None description=None, Mapping[str, str]|None description_placeholders=None)
tuple[str|None, nextcord.AppInfo|None] _async_try_connect(str token)
Definition: config_flow.py:82