|
| 1 | +from plugin import plugin |
| 2 | +from plugin import complete |
| 3 | +import requests |
| 4 | + |
| 5 | + |
| 6 | +@complete("fruit") |
| 7 | +@plugin("fruit") |
| 8 | +def fruit(jarvis, s: str) -> None: |
| 9 | + """ |
| 10 | + Retrieves information about a specific fruit from the Fruityvice API and outputs it to the user. |
| 11 | +
|
| 12 | + Parameters: |
| 13 | + jarvis (obj): Jarvis assistant object |
| 14 | + s (str): Fruit name entered by the user |
| 15 | +
|
| 16 | + Returns: |
| 17 | + None |
| 18 | +
|
| 19 | + Example Usage: |
| 20 | + fruit apple |
| 21 | + """ |
| 22 | + API_URL_SINGLE_FRUIT = "https://fruityvice.com/api/fruit/" |
| 23 | + |
| 24 | + try: |
| 25 | + # Validate user input |
| 26 | + if not s: |
| 27 | + jarvis.say("Please input a fruit. Usage: fruit [fruit]") |
| 28 | + return |
| 29 | + |
| 30 | + # Rename and format user input |
| 31 | + s = s.strip().lower() |
| 32 | + |
| 33 | + # Query the API for the requested fruit |
| 34 | + response = requests.get(API_URL_SINGLE_FRUIT + s) |
| 35 | + |
| 36 | + # Handle invalid or nonexistent fruit names |
| 37 | + if response.status_code == 404: |
| 38 | + jarvis.say("Invalid fruit name. Please enter a valid fruit name.") |
| 39 | + return |
| 40 | + response.raise_for_status() |
| 41 | + |
| 42 | + # Parse JSON response |
| 43 | + fruit = response.json() |
| 44 | + |
| 45 | + # Output fruit information to the user |
| 46 | + jarvis.say(f"{fruit['name']}\n") |
| 47 | + jarvis.say("Nutritional Facts Per 100 grams") |
| 48 | + for fact, value in fruit["nutritions"].items(): |
| 49 | + jarvis.say(f"{fact}: {value}") |
| 50 | + jarvis.say("\nSpecies Classifications") |
| 51 | + jarvis.say(f"Order: {fruit['order']}") |
| 52 | + jarvis.say(f"Family: {fruit['family']}") |
| 53 | + jarvis.say(f"Genus: {fruit['genus']}") |
| 54 | + |
| 55 | + # Handle errors |
| 56 | + except (requests.exceptions.RequestException, KeyError, ValueError): |
| 57 | + jarvis.say("Error occurred while fetching the fruit information. Please try again.") |
0 commit comments