From 59b3916b877a2d012d250a2f68d58947f609efc6 Mon Sep 17 00:00:00 2001 From: Baptiste D <63651713+Bapt5@users.noreply.github.com> Date: Thu, 23 Jun 2022 00:29:29 +0200 Subject: [PATCH] better get data by user id --- duolingo.py | 24 ++++++++++++++++-------- 1 file changed, 16 insertions(+), 8 deletions(-) diff --git a/duolingo.py b/duolingo.py index e29c6f9..d66a4c3 100644 --- a/duolingo.py +++ b/duolingo.py @@ -256,20 +256,27 @@ def switch_language(self, lang): except ValueError: raise DuolingoException('Failed to switch language') - def _get_data_by_user_id(self, user_id=None, fields=None): + def _get_data_by_user_id(self, user_id=None, fields=None, to_dict=False): """ Get user's data from ``https://www.duolingo.com/2017-06-30/users/``. """ if user_id is None: user_id = self.user_id + params = {} if fields: params["fields"] = ','.join(fields) get = self._make_req(f"https://www.duolingo.com/2017-06-30/users/{user_id}", params=params) if get.status_code == 404: raise DuolingoException('User not found') - else: - return get.json() + + data = get.json() + + if to_dict or len(fields) == 0: + return data + if len(fields) == 1: + return data.get(fields[0]) + return tuple(data.get(field) for field in fields) def _get_data(self, username=None): """ @@ -277,6 +284,7 @@ def _get_data(self, username=None): """ if username is None: username = self.username + get = self._make_req(f"https://duolingo.com/users/{username}") if get.status_code == 404: raise Exception('User not found') @@ -699,7 +707,7 @@ def get_word_definition_by_id(self, lexeme_id): raise Exception('Could not get word definition') def get_daily_xp_progress(self): - daily_progress = self._get_data_by_user_id(fields=["xpGoal", "xpGains", "streakData"]) + xpGoal, xpGains, streakData = self._get_data_by_user_id(fields=["xpGoal", "xpGains", "streakData"]) if not daily_progress: raise DuolingoException( @@ -708,7 +716,7 @@ def get_daily_xp_progress(self): # xpGains lists the lessons completed on the last day where lessons were done. # We use the streakData.updatedTimestamp to get the last "midnight", and get lessons after that. - reported_timestamp = daily_progress['streakData']['updatedTimestamp'] + reported_timestamp = streakData['updatedTimestamp'] reported_midnight = datetime.fromtimestamp(reported_timestamp) midnight = datetime.fromordinal(datetime.today().date().toordinal()) @@ -717,11 +725,11 @@ def get_daily_xp_progress(self): time_discrepancy = min(midnight - reported_midnight, timedelta(0)) update_cutoff = round((reported_midnight + time_discrepancy).timestamp()) - lessons = [lesson for lesson in daily_progress['xpGains'] if - lesson['time'] > update_cutoff] + lessons = [lesson for lesson in xpGains if + lesson['time'] > update_cutoff] return { - "xp_goal": daily_progress['xpGoal'], + "xp_goal": xpGoal, "lessons_today": lessons, "xp_today": sum(x['xp'] for x in lessons) }