aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorGravatar Shom770 <[email protected]>2021-10-17 23:10:15 -0400
committerGravatar Shom770 <[email protected]>2022-02-09 18:13:36 -0500
commit9d347be892925f7bc431ae7177e54fee0503996d (patch)
tree37c5e8ce280bb886d97079ed1c0dd82c8be30ff3
parentorganizing score board (scoreboard.py) (diff)
question view shell finished
-rw-r--r--bot/exts/events/trivianight/questions.py71
-rw-r--r--bot/exts/events/trivianight/scoreboard.py34
2 files changed, 99 insertions, 6 deletions
diff --git a/bot/exts/events/trivianight/questions.py b/bot/exts/events/trivianight/questions.py
new file mode 100644
index 00000000..21277ce9
--- /dev/null
+++ b/bot/exts/events/trivianight/questions.py
@@ -0,0 +1,71 @@
+from random import choice
+from time import perf_counter
+
+from discord import ButtonStyle, Embed, Interaction
+from discord.ui import Button, View
+
+from bot.constants import Colours, NEGATIVE_REPLIES
+from .scoreboard import Scoreboard
+
+
+class QuestionButton(Button):
+ """Button subclass for the options of the questions."""
+
+ def __init__(self, label: str):
+ self._time = perf_counter()
+ self.users_picked = {}
+ super().__init__(label=label, style=ButtonStyle.green)
+
+ def answer(self, label: str) -> dict:
+ """Returns the dictionary of the users who picked the answer only if it was correct."""
+ return self.users_picked if label == self.label else {}
+
+ async def callback(self, interaction: Interaction) -> None:
+ """When a user interacts with the button, this will be called."""
+ if interaction.user.id not in self.users_picked.keys():
+ self.users_picked[interaction.user.id] = [self.label, 1, perf_counter() - self._time]
+ elif self.users_picked[interaction.user.id][1] < 3:
+ self.users_picked[interaction.user.id] = [
+ self.label, self.users_picked[interaction.user.id][0] + 1, perf_counter() - self._time
+ ]
+ else:
+ await interaction.response.send_message(
+ embed=Embed(
+ title=choice(NEGATIVE_REPLIES),
+ description="You've already changed your answer more than once!",
+ color=Colours.soft_red
+ ),
+ ephemeral=True
+ )
+
+
+class QuestionView(View):
+ """View for the questions."""
+
+ def __init__(self, scoreboard: Scoreboard):
+ self.scoreboard = scoreboard
+ self.current_question = {}
+ self._users_picked = {}
+
+ def _create_current_question(self) -> Embed:
+ """Helper function to create the embed for the current question."""
+ question_embed = Embed(
+ title=f"Question {self.current_question['number']}",
+ description=self.current_question["description"],
+ color=Colours.python_yellow
+ )
+ for label, answer in zip(("A", "B", "C", "D"), self.current_question["answers"]):
+ question_embed.add_field(name=label, value=answer, inline=False)
+
+ self.buttons = [QuestionButton(label) for label in ("A", "B", "C", "D")]
+ return question_embed
+
+ def end_question(self) -> dict:
+ """Returns the dictionaries from the corresponding buttons for those who got it correct."""
+ labels = ("A", "B", "C", "D")
+ label = labels[self.current_question["correct"].index(self.current_question["answers"])]
+ return_dict = {}
+ for button in self.buttons:
+ return_dict.update(button.answer(label))
+
+ return return_dict
diff --git a/bot/exts/events/trivianight/scoreboard.py b/bot/exts/events/trivianight/scoreboard.py
index 4e94e361..34535690 100644
--- a/bot/exts/events/trivianight/scoreboard.py
+++ b/bot/exts/events/trivianight/scoreboard.py
@@ -1,18 +1,34 @@
+from typing import Union
+
import discord.ui
from discord import ButtonStyle, Embed, Interaction
from discord.ui import Button, View
+from bot.bot import Bot
from bot.constants import Colours
class ScoreboardView(View):
"""View for the scoreboard."""
- def __init__(self):
+ def __init__(self, bot: Bot):
+ self.bot = bot
self.points = {}
self.speed = {}
- def create_speed_embed(self) -> None:
+ def create_main_leaderboard(self) -> Embed:
+ """Helper function that iterates through `self.points` to generate the main leaderboard embed."""
+ main_embed = Embed(
+ title="Winners of the Trivia Night",
+ description="See the leaderboard for who got the most points during the Trivia Night!",
+ color=Colours.python_blue,
+ )
+ for user, points in list(self.points.items())[:10]:
+ main_embed.add_field(name=self.bot.get_user(user), value=f"`{points}` pts", inline=False)
+
+ return main_embed
+
+ def _create_speed_embed(self) -> Embed:
"""Helper function that iterates through `self.speed` to generate a leaderboard embed."""
speed_embed = Embed(
title="Average Time Taken to Answer a Question",
@@ -21,7 +37,9 @@ class ScoreboardView(View):
)
for user, time_taken in list(self.speed.items())[:10]:
speed_embed.add_field(
- name=user, value=f"`{(time_taken[1] / time_taken[0]):.3f}s` (on average)", inline=False
+ name=self.bot.get_user(user),
+ value=f"`{(time_taken[1] / time_taken[0]):.3f}s` (on average)",
+ inline=False
)
return speed_embed
@@ -29,14 +47,14 @@ class ScoreboardView(View):
@discord.ui.button(label="Scoreboard for Speed", style=ButtonStyle.green)
async def speed_leaderboard(self, button: Button, interaction: Interaction) -> None:
"""Send an ephemeral message with the speed leaderboard embed."""
- await interaction.response.send_message(embed=self.create_speed_embed(), ephemeral=True)
+ await interaction.response.send_message(embed=self._create_speed_embed(), ephemeral=True)
class Scoreboard:
"""Class for the scoreboard for the trivianight event."""
- def __init__(self, view: View):
- self.view = view
+ def __init__(self):
+ self.view = ScoreboardView()
def __setitem__(self, key: str, value: int):
if key.startswith("points: "):
@@ -57,3 +75,7 @@ class Scoreboard:
return self.view.points[item.removeprefix("points: ")]
elif item.startswith("speed: "):
return self.view.speed[item.removepreix("speed: ")]
+
+ def display(self) -> Union[Embed, View]:
+ """Returns the embed of the main leaderboard along with the ScoreboardView."""
+ return self.view.create_main_leaderboard(), self.view