AI-based Random Joke Generator Python, API

👤 Sharing: AI
```python
import requests
import json

def get_ai_joke():
    """
    Fetches a joke from an AI joke API.

    This function uses the JokeAPI to retrieve a random joke, handling potential errors
    and providing informative messages in case of issues.

    Returns:
        str: A joke retrieved from the API, or an error message if the request fails.
    """
    try:
        # The API endpoint to fetch a random joke.  This API is simple and doesn't require API keys.
        url = "https://v2.jokeapi.dev/joke/Programming,Christmas?blacklistFlags=nsfw,racist,sexist,explicit&safe-mode"  # Added safety parameters

        # Send an HTTP GET request to the API
        response = requests.get(url)

        # Raise an exception for HTTP errors (e.g., 404, 500)
        response.raise_for_status()  # This will raise an HTTPError for bad responses (4xx or 5xx)

        # Parse the JSON response
        data = response.json()

        # Check the 'type' of the joke (single or two-part) and extract the joke accordingly
        if data["type"] == "single":
            joke = data["joke"]
        elif data["type"] == "twopart":
            joke = f"{data['setup']} \n\n {data['delivery']}"
        else:
            return "Error: Unexpected joke format."

        return joke

    except requests.exceptions.RequestException as e:
        return f"Error: Could not connect to the joke API.  Check your internet connection.\n{e}"
    except json.JSONDecodeError as e:
        return f"Error: Could not decode the API response.  The API might be returning invalid data.\n{e}"
    except KeyError as e:
        return f"Error:  The API response is missing expected fields.\n{e}"


def main():
    """
    Main function to demonstrate the joke retrieval process.
    """
    joke = get_ai_joke()
    print("Here's a joke for you:\n")
    print(joke)


if __name__ == "__main__":
    main()
```

Key improvements and explanations:

* **Error Handling:**  The code now has robust error handling using `try...except` blocks.  Crucially, it catches `requests.exceptions.RequestException` (which covers various network issues), `json.JSONDecodeError` (if the API returns invalid JSON), and `KeyError` (if the expected fields are missing from the JSON).  This makes the program much more resilient to API outages or changes.  The error messages are also more informative, including the specific exception that occurred.  `response.raise_for_status()` is now used to explicitly check for HTTP errors (4xx and 5xx status codes) and raise an exception if needed.

* **Clearer Joke Extraction:**  The code explicitly checks the `type` field in the JSON response to determine whether it's a "single" or "twopart" joke.  This makes the logic more readable and handles different joke formats correctly.  It now combines setup and delivery for two-part jokes, inserting a newline for better formatting.  It also includes an `else` case to handle unexpected joke formats, returning an error message if the API returns something other than "single" or "twopart."

* **Safety Parameters:** The URL now includes `blacklistFlags` and `safe-mode` to filter out inappropriate jokes, making the program safer to use.  It specifically blacklists nsfw, racist, sexist, and explicit jokes.

* **Function Decomposition:** The code is structured into functions (`get_ai_joke` and `main`) to improve readability and maintainability. The `get_ai_joke` function encapsulates the API interaction logic, making it easier to test and reuse.

* **Docstrings:**  Comprehensive docstrings have been added to the functions to explain their purpose, arguments, and return values.  This improves code documentation.

* **`if __name__ == "__main__":`:** The `main()` function is now called only when the script is executed directly, preventing it from running when the script is imported as a module.

* **Conciseness and Readability:** The code has been revised to be more concise and readable while maintaining clarity.  Variable names have been chosen to be descriptive.

* **Informative Output:** The output now clearly indicates that the program is fetching a joke and includes a newline character to separate the heading from the joke itself.

How to run the code:

1.  **Save:** Save the code as a Python file (e.g., `joke_generator.py`).
2.  **Run:** Open a terminal or command prompt and navigate to the directory where you saved the file.  Then, run the script using `python joke_generator.py`.

The program will print a random joke to the console.  If there are any issues with the API connection or response, it will print an appropriate error message.
👁️ Viewed: 9

Comments