TriviaAPI
TriviaAPI is a way you can get questions from a site called opentdb (Open Trivia DB).
Open Trivia Provides…
-
4,000+ questions
-
Different type of questions (multiple choice, true-false)
-
User-friendly questions
Benefits
-
Easily get random questions without making your own
-
Unique and fun questions
-
Easily retrieve questions
-
Errors if giving wrong parameters
-
Uses Promises
-
Already made for you
-
Multiple Difficulty Settings
API
GetQuestions(amount_of_questions: number, difficulty: “easy” or “medium” or “hard”): {} or undefined
ExampleCode
local TriviaAPI = require(game.ReplicatedStorage.TriviaAPI)
TriviaAPI:GetQuestions(10, "easy")
Module Code
local module = {}
local HTTPService = game:GetService("HttpService")
-- Modules
local Promise = require(script.Promise)
--Default URL (DO NOT CHANGE)
module.URLTemplate = "https://opentdb.com/api.php?amount="
-- Settings
module.Settings = {
Difficulty = {
"easy",
"medium",
"hard",
}
}
function DifficultyExist(difficulty)
local not_similar = 0
local lower_cased_difficulty = string.lower(difficulty)
for _,v in ipairs(module.Settings.Difficulty) do
if (lower_cased_difficulty ~= v) then
not_similar += 1
end
end
if (not_similar == 3) then
warn("This difficulty doesn't exist please write it correctly! (Sending easy questions instead)")
return ""
else
return string.lower(difficulty)
end
end
function module:httpGet(URL)
return Promise.new(function(resolve, reject)
print(HTTPService, HTTPService.PostAsync, URL)
local ok, result = pcall(HTTPService.GetAsync, HTTPService, URL)
if (ok) then
resolve(result)
else
reject(result)
end
end)
end
function module:GetQuestions(amn, difficulty)
assert(type(amn) == "number", "Amount of questions must be a number!")
assert(amn < 50, "The number of questions asked must be under 50!")
assert(type(difficulty) == "string", "Difficulty is supposed to be a string!")
local difficulty_response = DifficultyExist(difficulty)
local response = self:httpGet(module.URLTemplate .. tostring(amn))
response:andThen(function(result)
local data = HTTPService:JSONDecode(result)
print(data)
return data
end)
response:catch(function(err)
warn(err)
return err
end)
end
return module
File
TriviaAPI.rbxm (16.6 KB)