1 """Support for Reddit."""
3 from __future__
import annotations
5 from datetime
import timedelta
9 import voluptuous
as vol
12 PLATFORM_SCHEMA
as SENSOR_PLATFORM_SCHEMA,
28 _LOGGER = logging.getLogger(__name__)
30 CONF_SORT_BY =
"sort_by"
31 CONF_SUBREDDITS =
"subreddits"
34 ATTR_COMMENTS_NUMBER =
"comms_num"
35 ATTR_CREATED =
"created"
37 ATTR_SUBREDDIT =
"subreddit"
42 DEFAULT_NAME =
"Reddit"
46 LIST_TYPES = [
"top",
"controversial",
"hot",
"new"]
50 PLATFORM_SCHEMA = SENSOR_PLATFORM_SCHEMA.extend(
52 vol.Required(CONF_CLIENT_ID): cv.string,
53 vol.Required(CONF_CLIENT_SECRET): cv.string,
54 vol.Required(CONF_USERNAME): cv.string,
55 vol.Required(CONF_PASSWORD): cv.string,
56 vol.Required(CONF_SUBREDDITS): vol.All(cv.ensure_list, [cv.string]),
57 vol.Optional(CONF_SORT_BY, default=
"hot"): vol.All(
58 cv.string, vol.In(LIST_TYPES)
60 vol.Optional(CONF_MAXIMUM, default=10): cv.positive_int,
68 add_entities: AddEntitiesCallback,
69 discovery_info: DiscoveryInfoType |
None =
None,
71 """Set up the Reddit sensor platform."""
72 subreddits = config[CONF_SUBREDDITS]
73 user_agent = f
"{config[CONF_USERNAME]}_home_assistant_sensor"
74 limit = config[CONF_MAXIMUM]
75 sort_by = config[CONF_SORT_BY]
79 client_id=config[CONF_CLIENT_ID],
80 client_secret=config[CONF_CLIENT_SECRET],
81 username=config[CONF_USERNAME],
82 password=config[CONF_PASSWORD],
83 user_agent=user_agent,
86 _LOGGER.debug(
"Connected to praw")
88 except praw.exceptions.PRAWException
as err:
89 _LOGGER.error(
"Reddit error %s", err)
93 RedditSensor(reddit, subreddit, limit, sort_by)
for subreddit
in subreddits
99 """Representation of a Reddit sensor."""
101 def __init__(self, reddit, subreddit: str, limit: int, sort_by: str) ->
None:
102 """Initialize the Reddit sensor."""
112 """Return the name of the sensor."""
113 return f
"reddit_{self._subreddit}"
117 """Return the state of the sensor."""
122 """Return the state attributes."""
126 CONF_SORT_BY: self.
_sort_by_sort_by,
131 """Return the icon to use in the frontend."""
135 """Update data from Reddit API."""
140 if hasattr(subreddit, self.
_sort_by_sort_by):
141 method_to_call = getattr(subreddit, self.
_sort_by_sort_by)
143 for submission
in method_to_call(limit=self.
_limit_limit):
146 ATTR_ID: submission.id,
147 ATTR_URL: submission.url,
148 ATTR_TITLE: submission.title,
149 ATTR_SCORE: submission.score,
150 ATTR_COMMENTS_NUMBER: submission.num_comments,
151 ATTR_CREATED: submission.created,
152 ATTR_BODY: submission.selftext,
156 except praw.exceptions.PRAWException
as err:
157 _LOGGER.error(
"Reddit error %s", err)
def extra_state_attributes(self)
None __init__(self, reddit, str subreddit, int limit, str sort_by)
def add_entities(account, async_add_entities, tracked)
None setup_platform(HomeAssistant hass, ConfigType config, AddEntitiesCallback add_entities, DiscoveryInfoType|None discovery_info=None)