From 8d66b52512fa2ba1fe6f1596fdd3686c9214a417 Mon Sep 17 00:00:00 2001 From: Eric Gustin <34000337+EricGustin@users.noreply.github.com> Date: Tue, 24 Sep 2024 09:31:10 -0700 Subject: [PATCH] Fix empty X search result bug (#54) Before: ![image](https://github.com/user-attachments/assets/4419dee1-bbfb-4fc3-a3bd-882e13f12919) Now: ![image](https://github.com/user-attachments/assets/00cd1fe6-7766-4d51-a328-af2211b9c1ac) --- toolkits/x/arcade_x/tools/utils.py | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/toolkits/x/arcade_x/tools/utils.py b/toolkits/x/arcade_x/tools/utils.py index 5b511653..0b78afd6 100644 --- a/toolkits/x/arcade_x/tools/utils.py +++ b/toolkits/x/arcade_x/tools/utils.py @@ -9,7 +9,7 @@ def get_tweet_url(tweet_id: str) -> str: def parse_search_recent_tweets_response(response: Response) -> str: """ - Parse the response from the X API search recent tweets endpoint. + Parses response from the X API search recent tweets endpoint. Returns a JSON string with the tweets data. Example parsed response: @@ -27,7 +27,14 @@ def parse_search_recent_tweets_response(response: Response) -> str: }, ] """ + if response.status_code != 200: + return json.dumps({"tweets": []}) + tweets_data = json.loads(response.text) + + if not sanity_check_tweets_data(tweets_data): + return json.dumps({"tweets": []}) + for tweet in tweets_data["data"]: tweet["tweet_url"] = get_tweet_url(tweet["id"]) @@ -38,3 +45,15 @@ def parse_search_recent_tweets_response(response: Response) -> str: tweet_data["author_name"] = user_data["name"] return json.dumps({"tweets": tweets_data["data"]}) + + +def sanity_check_tweets_data(tweets_data: dict) -> bool: + """ + Sanity check the tweets data. + Returns True if the tweets data is valid and contains tweets, False otherwise. + """ + if not tweets_data.get("data", []): + return False + if not tweets_data.get("includes", {}).get("users", []): + return False + return True