From 26db9428fd3d40ed070b3433794a194919277c8b Mon Sep 17 00:00:00 2001 From: EthanC <16727756+EthanC@users.noreply.github.com> Date: Fri, 3 May 2024 21:03:12 -0500 Subject: [PATCH] Avoid KeyErrors in parsing post result --- services/x.py | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/services/x.py b/services/x.py index eb45202..4b3c821 100644 --- a/services/x.py +++ b/services/x.py @@ -173,7 +173,10 @@ def GetUserPosts( continue try: - result: dict = content["itemContent"]["tweet_results"]["result"] + result: dict = content["itemContent"]["tweet_results"].get("result") + + if not result: + raise RuntimeError("unable to locate data in tweet_results") if not includeReposts: if result["legacy"].get("retweeted_status_result"): @@ -184,7 +187,9 @@ def GetUserPosts( continue if onlyMedia: - if not result["legacy"]["entities"].get("media"): + legacy: dict = result.get("legacy") + + if (legacy) and (not legacy["entities"].get("media")): logger.debug( f"[@{username}] Skipped {entry["entryId"]} due to lack of media" ) @@ -193,7 +198,10 @@ def GetUserPosts( # result data is sometimes within a tweet object. if (not result.get("rest_id")) or (not result.get("legacy")): - result = result["tweet"] + result = result.get("tweet") + + if not result: + raise RuntimeError("unable to locate post data in result") posts.append( {