Skip to content

Commit 37843cc

Browse files
authored
Merge pull request #296 from denzio231/Main
Add Trivia cog
2 parents d43e545 + f298828 commit 37843cc

File tree

1 file changed

+83
-0
lines changed

1 file changed

+83
-0
lines changed
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
"""
2+
A trivia command.
3+
"""
4+
import logging
5+
import json
6+
from discord.ui.item import Item
7+
import requests
8+
import urllib
9+
import html
10+
from discord.ext import commands
11+
import discord
12+
import random
13+
logger = logging.getLogger(__name__)
14+
15+
class GeneralTrivia(commands.Cog):
16+
"""
17+
# Hits the trivia API and returns the response
18+
"""
19+
20+
def __init__(self, bot):
21+
self.bot = bot
22+
23+
@commands.slash_command()
24+
async def trivia_cmd(self, ctx):
25+
"""
26+
Sends a trivia using an API
27+
"""
28+
logger.info("%s used the %s command."
29+
, ctx.author.name
30+
, ctx.command)
31+
req = requests.get("https://opentdb.com/api.php?amount=1&category=18&difficulty=medium&type=multiple")
32+
if req.json()['response_code'] == 0:
33+
34+
await ctx.respond(html.unescape(req.json()['results'][0]['question']))
35+
view = discord.ui.View()
36+
answer_list = []
37+
for i in req.json()['results'][0]['incorrect_answers']:
38+
answer_list.append((i,False))
39+
answer_list.append((req.json()['results'][0]['correct_answer'],True))
40+
al = answer_list[:]
41+
correct_ans = len(answer_list)-1
42+
button_list = []
43+
async def empty(interaction:discord.Interaction):
44+
pass
45+
async def correct(interaction:discord.Interaction):
46+
if interaction.user == ctx.author:
47+
await interaction.response.defer()
48+
await interaction.followup.send(content="The answer is correct, good job human")
49+
for i in button_list:
50+
i.callback = empty
51+
52+
async def wrong(interaction:discord.Interaction):
53+
if interaction.user == ctx.author:
54+
await interaction.response.defer()
55+
await interaction.followup.send(content=f"Wrong answer, the answer was {answer_list[correct_ans][0]}")
56+
await interaction.edit_original_response()
57+
for i in button_list:
58+
i.callback = empty
59+
for i in range(correct_ans+1):
60+
index = random.randint(0,len(al)-1)
61+
label = html.unescape(al[index][0])
62+
button = discord.ui.Button(label=label)
63+
button_list.append(button)
64+
#print(button.callback)
65+
if al[index][1]:
66+
67+
button.callback = correct
68+
else:
69+
button.callback = wrong
70+
del al[index]
71+
view.add_item(button)
72+
msg = await ctx.send(view=view)
73+
74+
else:
75+
await ctx.respond('Oops the server seems to have made a mistake, try the command again')
76+
77+
78+
79+
def setup(bot):
80+
"""
81+
Required.
82+
"""
83+
bot.add_cog(GeneralTrivia(bot))

0 commit comments

Comments
 (0)