diff --git a/homeassistant/components/twitch/sensor.py b/homeassistant/components/twitch/sensor.py index 771f88f0ef1..95006a4cab7 100644 --- a/homeassistant/components/twitch/sensor.py +++ b/homeassistant/components/twitch/sensor.py @@ -62,13 +62,16 @@ def setup_platform( client_id = config[CONF_CLIENT_ID] client_secret = config[CONF_CLIENT_SECRET] oauth_token = config.get(CONF_TOKEN) - client = Twitch(app_id=client_id, app_secret=client_secret) - client.auto_refresh_auth = False try: - client.authenticate_app(scope=OAUTH_SCOPES) + client = Twitch( + app_id=client_id, + app_secret=client_secret, + target_app_auth_scope=OAUTH_SCOPES, + ) + client.auto_refresh_auth = False except TwitchAuthorizationException: - _LOGGER.error("INvalid client ID or client secret") + _LOGGER.error("Invalid client ID or client secret") return if oauth_token: @@ -86,7 +89,7 @@ def setup_platform( channels = client.get_users(logins=channels) add_entities( - [TwitchSensor(channel=channel, client=client) for channel in channels["data"]], + [TwitchSensor(channel, client) for channel in channels["data"]], True, ) @@ -94,80 +97,38 @@ def setup_platform( class TwitchSensor(SensorEntity): """Representation of an Twitch channel.""" - def __init__(self, channel, client: Twitch): + _attr_icon = ICON + + def __init__(self, channel: dict[str, str], client: Twitch) -> None: """Initialize the sensor.""" self._client = client - self._channel = channel self._enable_user_auth = client.has_required_auth(AuthType.USER, OAUTH_SCOPES) - self._state = None - self._preview = None - self._game = None - self._title = None - self._subscription = None - self._follow = None - self._statistics = None + self._attr_name = channel["display_name"] + self._attr_unique_id = channel["id"] - @property - def name(self): - """Return the name of the sensor.""" - return self._channel["display_name"] - - @property - def native_value(self): - """Return the state of the sensor.""" - return self._state - - @property - def entity_picture(self): - """Return preview of current game.""" - return self._preview - - @property - def extra_state_attributes(self): - """Return the state attributes.""" - attr = dict(self._statistics) - - if self._enable_user_auth: - attr.update(self._subscription) - attr.update(self._follow) - - if self._state == STATE_STREAMING: - attr.update({ATTR_GAME: self._game, ATTR_TITLE: self._title}) - return attr - - @property - def unique_id(self): - """Return unique ID for this sensor.""" - return self._channel["id"] - - @property - def icon(self): - """Icon to use in the frontend, if any.""" - return ICON - - def update(self): + def update(self) -> None: """Update device state.""" - followers = self._client.get_users_follows(to_id=self._channel["id"])["total"] - channel = self._client.get_users(user_ids=[self._channel["id"]])["data"][0] + followers = self._client.get_users_follows(to_id=self.unique_id)["total"] + channel = self._client.get_users(user_ids=[self.unique_id])["data"][0] - self._statistics = { + self._attr_extra_state_attributes = { ATTR_FOLLOWING: followers, ATTR_VIEWS: channel["view_count"], } if self._enable_user_auth: - user = self._client.get_users()["data"][0] + user = self._client.get_users()["data"][0]["id"] subs = self._client.check_user_subscription( - user_id=user["id"], broadcaster_id=self._channel["id"] + user_id=user, broadcaster_id=self.unique_id ) if "data" in subs: - self._subscription = { - ATTR_SUBSCRIPTION: True, - ATTR_SUBSCRIPTION_GIFTED: subs["data"][0]["is_gift"], - } + self._attr_extra_state_attributes[ATTR_SUBSCRIPTION] = True + self._attr_extra_state_attributes[ATTR_SUBSCRIPTION_GIFTED] = subs[ + "data" + ][0]["is_gift"] elif "status" in subs and subs["status"] == 404: - self._subscription = {ATTR_SUBSCRIPTION: False} + self._attr_extra_state_attributes[ATTR_SUBSCRIPTION] = False elif "error" in subs: raise Exception( f"Error response on check_user_subscription: {subs['error']}" @@ -176,23 +137,22 @@ class TwitchSensor(SensorEntity): raise Exception("Unknown error response on check_user_subscription") follows = self._client.get_users_follows( - from_id=user["id"], to_id=self._channel["id"] + from_id=user, to_id=self.unique_id )["data"] - if len(follows) > 0: - self._follow = { - ATTR_FOLLOW: True, - ATTR_FOLLOW_SINCE: follows[0]["followed_at"], - } - else: - self._follow = {ATTR_FOLLOW: False} + self._attr_extra_state_attributes[ATTR_FOLLOW] = len(follows) > 0 + if len(follows): + self._attr_extra_state_attributes[ATTR_FOLLOW_SINCE] = follows[0][ + "followed_at" + ] - streams = self._client.get_streams(user_id=[self._channel["id"]])["data"] - if len(streams) > 0: + if streams := self._client.get_streams(user_id=[self.unique_id])["data"]: stream = streams[0] - self._game = stream["game_name"] - self._title = stream["title"] - self._preview = stream["thumbnail_url"] - self._state = STATE_STREAMING + self._attr_native_value = STATE_STREAMING + self._attr_extra_state_attributes[ATTR_GAME] = stream["game_name"] + self._attr_extra_state_attributes[ATTR_TITLE] = stream["title"] + self._attr_entity_picture = stream["thumbnail_url"] else: - self._preview = channel["offline_image_url"] - self._state = STATE_OFFLINE + self._attr_native_value = STATE_OFFLINE + self._attr_extra_state_attributes[ATTR_GAME] = None + self._attr_extra_state_attributes[ATTR_TITLE] = None + self._attr_entity_picture = channel["offline_image_url"]