-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
161 lines (128 loc) · 5.17 KB
/
Copy pathscript.js
File metadata and controls
161 lines (128 loc) · 5.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
// Global variables
let currentAnswer
// Function to generate the API token
async function generateToken () {
const url = 'https://opentdb.com/api_token.php?command=request';
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error('HTTP error! status: ${response.status}');
}
const data = await response.json();
// Extracting token
const tokenlocation = data.token;
console.log('Token:', tokenlocation);
return tokenlocation;
} catch (error) {
console.error('Error fetching token:', error);
}
}
// Handle API response codes
function responseCodes(responseCode) {
console.log('Response Code:', responseCode)
if (responseCode == 0) {
console.log('Returned results successfully.')
} else if (responseCode == 1) {
console.log('Could not return results. The API doesnt have enough questions for your query. (Ex. Asking for 50 Questions in a Category that only has 20.)')
} else if (responseCode == 2) {
console.log('Contains an invalid parameter. Arguements passed in arent valid. (Ex. Amount = Five)')
} else if (responseCode == 3) {
console.log('Session Token does not exist.')
} else if (responseCode == 4) {
console.log('Session Token has returned all possible questions for the specified query. Resetting the Token is necessary.')
} else if (responseCode == 5) {
console.log('Too many requests have occurred. Each IP can only access the API once every 5 seconds.')
}
}
var token = generateToken();
// Reset API Token
function resetToken() {
token.then(async function tokenResetSubFunction(token) {
document.getElementById("question").innerHTML = "Question:"
document.getElementById("answer").innerHTML = "Answer:"
document.getElementById("category").innerHTML = "Category:"
const url = 'https://opentdb.com/api_token.php?command=reset&token=' + token;
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error('HTTP error! status: ${response.status}');
}
const data = await response.json();
// Extracting Result
const resetResult = data.response_code;
responseCodes(resetResult);
} catch (error) {
console.error('Error resetting token:', error);
}
});
}
let cooldownInterval = "null"
// Cooldown
function startCooldown(seconds) {
const timer = document.getElementById("timer");
let remaining = seconds;
timer.textContent = `Cooldown: ${remaining}s`;
// Clear any existing interval
if (cooldownInterval) clearInterval(cooldownInterval);
cooldownInterval = setInterval(() => {
remaining--;
if (remaining > 0) {
timer.textContent = `Cooldown: ${remaining}s`;
} else {
timer.textContent = ""
clearInterval(cooldownInterval);
}
}, 1000);
}
let isOnCooldown = false;
// QnA Retrieving
function retrieveQuestion() {
token.then(async function retrieveSubFunction(token) {
// Check if cooldown requirement is right
if (isOnCooldown) {
console.log('Please wait for cooldown to finish');
const errorID = document.getElementById("error");
errorID.style.display = "block";
} else {
const errorID = document.getElementById("error");
errorID.style.display = "none";
// Start Cooldown
isOnCooldown = true;
const url = 'https://opentdb.com/api.php?amount=1&type=multiple&token=' + token;
try {
const response = await fetch(url);
if (!response) {
throw new Error('HTTP error! status: ${response.status}');
}
const data = await response.json();
// Extracting question and answer
const result = data.results[0];
const question = result.question;
const answer = result.correct_answer;
const category = result.category;
currentAnswer = answer;
console.log(question);
console.log(answer);
console.log(category)
const questionID = document.getElementById("question");
const answerID = document.getElementById("answer");
const categoryID = document.getElementById("category");
questionID.innerHTML = `Question: ${question}`;
answerID.innerHTML = `Answer: ???`;
categoryID.innerHTML = `Category: ${category}`;
} catch (error) {
console.error('Error retrieving QnA:', error)
}
// Start 5 second cooldown
startCooldown(5);
setTimeout(() => {
isOnCooldown = false;
console.log('Cooldown finished. Fetching can now take place again.');
}, 5000); // 5000ms/5s
}
});
}
function showAnswer() {
const answerID = document.getElementById("answer");
answerID.innerHTML = `Answer: ${currentAnswer}`;
}