Skip to main content

Python wrapper for the open-trivia-database API

Project description

opentdb-py

Python wrapper for the open-trivia-database API

Installation

py -m pip install -U opentdb-py  
  
# latest (unstable)  
py -m pip install -U git+https://github.com/Marseel-E/opentdb-py  

Quickstart

import asyncio

from trivia import Client, EmptyToken

async def main() -> None:
	session_token = await Client.get_session_token()
	trivia_client = Client(session_token)
	
	try:
		data = await trivia_client.get_questions(amount=1)
	except EmptyToken:
		await trivia_client.reset_session_token()
	else:
		data = await trivia_client.get_questions(amount=1)
		
	print(data)

	await trivia_client.close_session()
    
if __name__ == '__main__:  
	asyncio.run(main())  
{  
  "category":"Entertainment: Video Games",  
  "type":"boolean",  
  "difficulty":"medium",  
  "question":"In the Resident Evil series, Leon S. Kennedy is a member of STARS.",  
  "correct_answer":"False",  
  "incorrect_answers":["True"]  
}  

Documentation

class Client

Sends a POST call to the API and gets the desired data.

Parameters

  • session_token ( str ) - The session token.

Methods
async get_session_token
async reset_session_token
async close_session
async get_questions
async get_categories
async get_category_questions_count
async get_global_questions_count

async Client.get_session_token

await Client.get_session_token()

This function is a coroutine.

Fetches a session token from the API.

Returns
Session Token.

Return Type
str

async Client.reset_session_token

await Client(...).reset_session_token()

This function is a coroutine.

Resets the session token.

async Client.close_session

await Client(...).close_session()

This function is a coroutine.

Closes the client session.

async Client.get_questions

await Client(...).questions(   
  amount=10,  
  category=Category.undefined,  
  difficulty=Difficulty.undefined,  
  question_type=QuestionType.both,  
  encoding=ResponseEncoding.default  
)  

This function is a coroutine.

Fetches the requests amount of questions from the API with the appropriate parameters.

Parameters

  • amount ( int ) - The amount of questions to return.
  • category ( Category ) - The category of questions.
  • difficulty ( Difficulty ) - The difficulty of the question (undefined=any, easy, medium, hard).
  • question_type ( QuestionType ) - The type of question (both, multiple choice, true/false).
  • encoding ( ResponseEncoding ) - The encoding of the API response.

Returns
A list of questions.

Return Type
QuestionData

async Client.get_categories

await Client(...).categories()

This function is a coroutine.

Fetches a list of all categories the API has.

Returns
A list of categories.

Return Type
CategoriesList

async Client.get_category_questions_count

await Client(...).category_questions_count(category=Category.general_knowledge)

This function is a coroutine.

Fetches statistics about a specific category.

Parameters

  • category ( Category ) - The category to fetch data from.

Returns
Statistics about the category.

Return Type
CategoryQuestionsCount

async Client.get_global_questions_count

await Client(...).global_questions_count()

This function is a coroutine.

Fetches statistics about all the categories.

Returns
Global statistics

Return Type
GlobalQuestionsCount

exception NoResults

<NoResults>: [Code 1] Could not return results. The API doesn't have enough questions for your query. (Ex. Asking for 50 Questions in a Category that only has 20.)

This exception is raised when a response_code 1 is returned.

The API doesn't have enough questions for the given query.

exception InvalidParameter

<InvalidParameter>: [Code 2] Contains an invalid parameter. Arguements passed in aren't valid. (Ex. Amount = Five)

This exception is raised when a response_code 2 is returned.

One or more of the query parameters are invalid.

exception TokenNotFound

<TokenNotFound>: [Code 3] Session Token does not exist.

This exception is raised when a response_code 3 is returned.

The session token was not specified.

exception TokenEmpty

<TokenEmpty>: [Code 4] Session Token has returned all possible questions for the specified query. Resseting the Token is necassery.

This exception is raised when a response_code 4 is returned.

The session token is about to expire. (session tokens last 6 hours only)

type QuestionData

class QuestionData(TypedDict):
	category: str
	type: str
	difficulty: str
	question: str
	correct_answer: str
	incorrect_answers: List[str]

type QuestionResponse

class QuestionResponse(TypedDict):
	response_code: int
	results: List[QuestionData]

type CategoryData

class CategoryData(TypedDict):
	id: int
	name: str

type CategoriesList

class CategoriesList(TypedDict):
	trivia_categories: List[CategoryData]

type CategoryQuestionsCount

class CategoryQuestionsCount(TypedDict):
	category_id: int
	category_questions_count: List[_CategoryQuestionsCount]

type GlobalQuestionsCount

class GlobalQuestionsCount(TypedDict):
	overall: _GlobalQuestionsCount
	categories: Dict[str, _GlobalQuestionsCount]

enum ResponseEncoding

class ResponseEncoding(Enum):
	default: None = None
	url: str = "url3986"
	base64: str = "base64"

enum Difficulty

class QuestionDifficulty(Enum):
	undefined: None = None
	easy: str = "easy"
	medium: str = "medium"
	hard: str = "hard"

enum QuestionType

class QuestionType(Enum):
	both: None = None
	multiple_choice: str = "multiple"
	true_false: str = "boolean"

enum Category

class QuestionCategory(Enum):
	undefined: None = None
	general_knowledge: int = 9
	entertainment_books: int = 10
	entertainment_film: int = 11
	entertainment_music: int = 12
	entertainment_music_and_theatres: int = 13
	entertainment_television: int = 14
	entertainment_video_games: int = 15
	entertainment_board_games: int = 16
	science_and_nature: int = 17
	science_computers: int = 18
	science_mathematics: int = 19
	mythology: int = 20
	sports: int = 21
	geography: int = 22
	history: int = 23
	politics: int = 24
	art: int = 25
	celebrities: int = 26
	animals: int = 27
	vehicles: int = 28
	entertainment_comics: int = 29
	science_gadgets: int = 30
	entertainment_japanese_anime_and_manga: int = 31
	entertainment_cartoons_and_animations: int = 32

:scroll: License

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

opentdb-py-2.1.2.tar.gz (6.5 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

opentdb_py-2.1.2-py3-none-any.whl (8.1 kB view details)

Uploaded Python 3

File details

Details for the file opentdb-py-2.1.2.tar.gz.

File metadata

  • Download URL: opentdb-py-2.1.2.tar.gz
  • Upload date:
  • Size: 6.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.0 CPython/3.10.2

File hashes

Hashes for opentdb-py-2.1.2.tar.gz
Algorithm Hash digest
SHA256 23763d9b0c15d35d641242820cd18802496930b0686a855ab14dd3a6756d70d9
MD5 a0f833ad464e7fb93d898505f5239d91
BLAKE2b-256 fcafcb350377fa383a613ae8745d53324bbc971b8ce668e40a851c769b69e175

See more details on using hashes here.

File details

Details for the file opentdb_py-2.1.2-py3-none-any.whl.

File metadata

  • Download URL: opentdb_py-2.1.2-py3-none-any.whl
  • Upload date:
  • Size: 8.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.0 CPython/3.10.2

File hashes

Hashes for opentdb_py-2.1.2-py3-none-any.whl
Algorithm Hash digest
SHA256 d1d45ed5fd469027de10471302cc7cd11977870d76fba8aae16e4905f29a53cc
MD5 df22af457ff7d6cfbb60aebe06c33013
BLAKE2b-256 329ccf05115cb7403172e6b7ce16307e39c6d31fbbc66e71ca99a2c9fa53a15b

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page