"""
title: Joke API Tool
author: Peter De-Ath
funding_url: https://github.com/open-webui
version: 0.1.0
license: MIT
description: API provided by https://github.com/15Dkatz/official_joke_api
"""
class Tools:
def get_joke(
self, category: str = None, id: str = None, number_of_jokes: int = 1
) -> str:
"""
Gets a joke from the joke api.
:param category: The category of joke to get.
:param id: The id of the joke to get.
:param number_of_jokes: The number of jokes to get.
:return: The joke.
"""
import requests
import json
headers = {"Content-Type": "application/json"}
try:
url = "https://official-joke-api.appspot.com"
if id:
response = requests.get(
f"{url}/jokes/{str(id)}", headers=headers
)
elif category:
response = requests.get(
f"{url}/jokes/{category}/random",
headers=headers,
)
else:
response = requests.get(
f"{url}/jokes/random/{number_of_jokes}",
headers=headers,
)
if response.status_code == 200:
try:
data = json.loads(response.text)
print(f"---data---\n{data}\n---")
jokes_output = "Jokes:\n\n"
i = 0
if id:
jokes_output += "Here is joke id " + str(id) + ":\n"
if isinstance(data, dict):
data = [data]
for joke in data:
if isinstance(joke, dict):
i = i + 1
extra = "\n---\n\n" if len(data) > 1 else ""
jokes_output += (
f"{i}.\nSetup: "
+ joke["setup"]
+ "\nPunchline: "
+ joke["punchline"]
+ extra
)
if category and number_of_jokes > 1:
jokes_output += "\nSorry, when specifying a category, only one joke can be returned."
return jokes_output
except Exception as e:
print(e)
except Exception as e:
print(e)
return "Sorry unable to get joke."