Git Product home page Git Product logo

jokeapi-python's Introduction

Sv443's Joke API Wrapper

Downloads Downloads Downloads CircleCI

An API wrapper for Sv443's joke api which provides simple yet versatile functionality, while also maintaining a readable codebase.

Install

You can install jokeapi through pip by using pip install jokeapi


get_joke

The wrapper is structured in such a way that the end-user should only ever have to interact with one function to get a joke. This function is get_joke().

Please note that urllib3, the core dependency of this wrapper automatically abides by Retry-After headers, which means you may have to wait a long time for a joke if you have made a lot of requests recently


submit_joke

The wrapper also provides simple access to the submit endpoint through the submit_joke() function.

Note that joke submissions are manually checked and you will be ratelimited.


get_joke

Example

from jokeapi import Jokes # Import the Jokes class
import asyncio

async def print_joke():
    j = await Jokes()  # Initialise the class
    joke = await j.get_joke()  # Retrieve a random joke
    if joke["type"] == "single": # Print the joke
        print(joke["joke"])
    else:
        print(joke["setup"])
        print(joke["delivery"])

asyncio.run(print_joke())

Parameters


category

A list of categories that the returned joke should fit in. Options are: programming, miscellaneous, dark, pun

If left blank it will default to use Any.

Example
  joke = await j.get_joke(category=['programming', 'dark'])  # Will return a joke that fits in either the programming or dark category.

blacklist

A list of properties that the joke shouldn't have. Options are: nsfw, religious, political, racist, sexist

If left blank it will default to None.

Example
  joke = await j.get_joke(blacklist=['nsfw', 'racist'])  # Will return a joke that does not have either the flag "nsfw" or "racist".

response_format

The format in which the API should respond. Options are: json, yaml, xml, txt

If left blank it will default to json.

Example
  joke = await j.get_joke(response_format="xml")  # Will return a joke in xml format.

joke_type

The type of joke returned. Options are: single, twopart, Any

If left blank it will default to Any

Example
  joke = await j.get_joke(joke_type="twopart")  # Will return a twopart joke; both a setup and a delivery.

search_string

A string to search for in jokes.

If left blank it will default to None

Example
  joke = await j.get_joke(search_string="the")  # Will return a joke with the word "the" in it.
  # If there are no jokes then it will return the error from the API.

id_range

The range in which the selected joke should fall. ID's are decided by the order in which jokes are submitted. The argument passes should be in form of list or tuple, and should not exceed length of 2 items. First item should be minimum 0. Maximum value can be determined here

If left blank it will default to the maximum range.

Example
  joke = await j.get_joke(id_range=[10,100])  # Will return a joke with the ID between 10 and 100.

amount

The amount of jokes you want the api to return. Will return them in a list. Maximum number is 10 jokes, and the api defaults to 1 if you use a number larger than the maximum. Defaults to 1.

Example
  joke = await j.get_joke(amount=2) # Will return 2 jokes.

lang

The language that the joke and response should be in. Currently supported languages are in the official api documentation. Defaults to en.

Example
  joke = await j.get_joke(lang="de")

auth_token

A string token provided by the api owner. Using it will mean you are whitelisted by the api and can make more requests than normal users. Defaults to None

Example
  joke = await j.get_joke(auth_token="aaaaaaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbb") # Will send the token to the api in a header.

user_agent

A string sent the the api that tells the api what browser you are (pretending to be). The default user agent is Mozilla Firefox from Windows 10 and should work fine, but the functionality is provided in case you wish to change it

Example
  joke = await j.get_joke(user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:77.0) Gecko/20100101 Firefox/77.0")
  # This is in fact the default user agent, and tells the API that we are visitng the page from a Firefox 77.0
  # browser using Windows 10 64bit.

return_headers

A boolean value (True or False) that tells the wrapper if you wish to receive headers in the return from the function. Will return a list instead of a single value Defaults to False.

Example
  response = await j.get_joke(return_headers=True)
  joke = response[0]
  headers = response[1]

  print(f"Joke: {joke}")
  print(f"Headers: {headers}")

Returns

Depending on what format is chosen different things will be returned.

json

A succesful API call will return:

  {
      "category": "Miscellaneous",
      "type": "twopart",
      "setup": "I told my psychiatrist I got suicidal tendencies.",
      "delivery": "He said from now on I have to pay in advance.",
      "flags": {
          "nsfw": false,
          "religious": false,
          "political": false,
          "racist": false,
          "sexist": false
      },
      "id": 94,
      "error": false
  }

xml

A succesful API call will return:

<?xml version='1.0'?>
<data>
    <category>Dark</category>
    <type>single</type>
    <joke>My ex had an accident. I told the paramedics the wrong blood type for her. She'll finally experience what rejection is really like.</joke>
    <flags>
        <nsfw>false</nsfw>
        <religious>false</religious>
        <political>false</political>
        <racist>false</racist>
        <sexist>false</sexist>
    </flags>
    <id>154</id>
    <error>false</error>
</data>

yaml

A succesful API call will return:

category: "Programming"
type: "single"
joke: "Your momma is so fat, you need to switch to NTFS to store a picture of her."
flags:
  nsfw: false
  religious: false
  political: false
  racist: false
  sexist: false
id: 56
error: false

txt

A succesful API call will return:

Why does no one like SQLrillex?

He keeps dropping the database.

Errors

The wrapper can raise multiple different errors depending on what you did wrong.

The errors are descriptive enough that you should be able to solve them with the information provided in the error message. If not, feel free to ask me through one of the channels provided below.


submit_joke

Example

from jokeapi import Jokes
import asyncio

async def submit_new_joke():
	j = await Jokes()

	await j.submit_joke("Miscellaneous", "funny haha", {
	    "nsfw": False,
	    "religious": False,
	    "political": False,
	    "racist": False,
	    "sexist": False
	}, lang="de")

asyncio.run(submit_new_joke())

Parameters


category

The category the joke is. Options are: programming, miscellaneous, dark, pun

Has no default value.


joke

The joke itself. Can either be a single string or a list/tuple, for the setup and delivery. Setup should be at index 0 in the tuple, delivery at 1.

Has no default value.


flags

The flags that the joke should have. Options are: nsfw, religious, political, racist, sexist

Has no default value.

lang

The language code for the language the joke it written in. E.g en for english, de for german.

Defaults to en


Contributors

ThatCopy

kdiri

Developer contact

DiscordDiscord

Issue Tracker

e-mail

jokeapi-python's People

Contributors

benjhar avatar thatcopy avatar kdiri avatar sv443 avatar dependabot[bot] avatar

Stargazers

Jim Haff avatar  avatar  avatar LeadBlackTech avatar duskygloom avatar Martin Wong avatar Roberto avatar Butch Ewing avatar  avatar Shree Chatane avatar Wouter Van Goey avatar  avatar  avatar Jennifer Langford avatar Neos21 avatar Ratul Roy avatar Ratul avatar Nitin Singh Rawat avatar MOURAD avatar Simon Law avatar MuffinDev avatar  avatar WANG SHAOYU avatar  avatar  avatar JDJG avatar Mark Valdez avatar  avatar  avatar Krishp avatar  avatar

Watchers

Kyle avatar  avatar

jokeapi-python's Issues

Example in readme doesn't work

Describe the bug
The example in the README.md doesn't work and throws an error

To Reproduce
Run the example in README.md

Expected behavior
Return a joke

Error and/or code snippet

Traceback (most recent call last): File "main.py", line 5, in <module> if joke["type"] == "single": # Print the joke TypeError: list indices must be integers or slices, not str

Please complete the following information:

  • OS: Win 10 (2004)
  • Python version 3.8
  • Version 0.2.2
  • Installed with pip

Typo in build_request for the Parameter idRange

Describe the bug
There is a typo within the file main.py on line 160.
When using an IdRange the string 'i&dRange' is appended to the request.
But instead of 'i&dRange' the value '&idRange' needs to be added.
This renders the Range-Feature useless and jokes with random IDs are returned.

To Reproduce
Steps to reproduce the behavior:

  1. Use the optional IdRange Parameter

Expected behavior
The idRange should be applied as a filter. Only jokes that have their IDs within the requested range should be returned.

**Error and/or code snippet **
if id_range:
r += f"i&dRange={id_range[0]}-{id_range[1]}"

Needs to be changed into:
if id_range:
r += f"i&dRange={id_range[0]}-{id_range[1]}"

Thanks very much!

README example broken: TypeError: object Jokes can't be used in 'await' expression

$ ./joke.py
Sv443's JokeAPI
Traceback (most recent call last):
  File "./joke.py", line 16, in <module>
    asyncio.run(print_joke())
  File "/usr/local/lib/python3.8/asyncio/runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "/usr/local/lib/python3.8/asyncio/base_events.py", line 616, in run_until_complete
    return future.result()
  File "./joke.py", line 7, in print_joke
    j = await Jokes()  # Initialise the class
TypeError: object Jokes can't be used in 'await' expression
  • OS: FreeBSD 13.0
  • Python version 3.8.13
  • jokeapi-0.2.11, installed via sudo pip install jokeapi

Make a native aiohttp async mode too.

Is your feature request related to a problem? Please describe.
Basically there's no native async branch sure you could do an executor, but it's not as useful as native async.

Describe the solution you'd like
make it mutlisync a way to do it with either aiohttp or requests, I guess?
just both sync and sync.

Describe alternatives you've considered
I currently use aiohttp session's directly.

Additional context
Add any other context or screenshots about the feature request here.

pip doesnt install dependencies

pip install jokeapi doesnt install simplejson or urllib3

pip install jokeapi

It should install simplejson and urllib3

image
The setuptools.find_packages() probbably fails

  • OS: Win 10 (2004)
  • Python version 3.8
  • Version 0.2.2

get_joke() Example

Hi. I was trying to use the Python wrapper of Joke API. I was going through the README.md when I came across this get_joke() example:

from jokeapi import Jokes # Import the Jokes class
import asyncio

async def print_joke():
    j = await Jokes()  # Initialise the class
    await j.get_joke()  # Retrieve a random joke
    if joke["type"] == "single": # Print the joke
        print(joke["joke"])
    else:
        print(joke["setup"])
        print(joke["delivery"])

asyncio.run(print_joke())

Bugs:

  • NameError: name 'joke' is not defined
  • Even if I correct the name error by adding joke = await j.get_joke() in the second line of the function it still gives me an error along with the joke: RuntimeError: Event loop is closed

To Reproduce

  1. Just copy the example under the README.md and run it.
  2. See error

Expected behavior

I expected the function to return a joke after each call.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.