Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,10 +1,6 @@
package net.javadiscord.javabot.systems.qotw.commands.view;

import java.util.List;
import java.util.stream.Collectors;

import com.dynxsty.dih4jda.interactions.commands.SlashCommand;

import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.entities.TextChannel;
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
Expand All @@ -18,20 +14,39 @@
import net.javadiscord.javabot.systems.qotw.submissions.model.QOTWSubmission;
import net.javadiscord.javabot.systems.qotw.submissions.subcommands.MarkBestAnswerSubcommand;
import net.javadiscord.javabot.util.Responses;
import org.jetbrains.annotations.NotNull;

import java.util.List;
import java.util.stream.Collectors;

/**
* Represents the `/qotw-view list-answers` subcommand. It allows for listing answers to a specific QOTW.
*/
public class QOTWListAnswersSubcommand extends SlashCommand.Subcommand{
public class QOTWListAnswersSubcommand extends SlashCommand.Subcommand {
/**
* The constructor of this class, which sets the corresponding {@link SubcommandData}.
*/
public QOTWListAnswersSubcommand() {
setSubcommandData(new SubcommandData("list-answers", "Lists answers to (previous) questions of the week")
.addOption(OptionType.INTEGER, "question", "The question number",true));
.addOption(OptionType.INTEGER, "question", "The question number", true)
);
}

/**
* Checks whether a submission is visible to a specific user.
*
* @param submission the {@link QOTWSubmission} to be checked
* @param viewerId the user to check against
* @return {@code true} if the submission is visible, else {@code false}}
*/
public static boolean isSubmissionVisible(@NotNull QOTWSubmission submission, long viewerId) {
return submission.getStatus() == SubmissionStatus.ACCEPTED || submission.getAuthorId() == viewerId;
}

@Override
public void execute(SlashCommandInteractionEvent event) {
public void execute(@NotNull SlashCommandInteractionEvent event) {
if (!event.isFromGuild()) {
Responses.replyGuildOnly(event).setEphemeral(true).queue();
Responses.replyGuildOnly(event).queue();
return;
}
OptionMapping questionNumOption = event.getOption("question");
Expand All @@ -45,18 +60,18 @@ public void execute(SlashCommandInteractionEvent event) {
DbActions.doAsyncDaoAction(QOTWSubmissionRepository::new, repo -> {
List<QOTWSubmission> submissions = repo.getSubmissionsByQuestionNumber(event.getGuild().getIdLong(), questionNum);
EmbedBuilder eb = new EmbedBuilder()
.setDescription("**Answers of Question of the week #" + questionNum + "**\n")
.setColor(Responses.Type.DEFAULT.getColor())
.setFooter("Results may not be accurate due to historic data.");
.setTitle("Answers of Question of the Week #" + questionNum)
.setColor(Responses.Type.DEFAULT.getColor())
.setFooter("Results may not be accurate due to historic data.");
TextChannel submissionChannel = Bot.getConfig().get(event.getGuild()).getQotwConfig().getSubmissionChannel();
String allAnswers = submissions
.stream()
.filter(submission -> isSubmissionVisible(submission, event.getUser().getIdLong()))
.filter(submission -> submission.getQuestionNumber() == questionNum)
.map(s -> (isBestAnswer(submissionChannel,s) ?
"best " : s.getStatus() == SubmissionStatus.ACCEPTED ? "accepted " : "")+
"Answer by <@" + s.getAuthorId() + ">")
.collect(Collectors.joining("\n"));
.stream()
.filter(submission -> isSubmissionVisible(submission, event.getUser().getIdLong()))
.filter(submission -> submission.getQuestionNumber() == questionNum)
.map(s -> (isBestAnswer(submissionChannel,s) ?
"**Best** " : s.getStatus() == SubmissionStatus.ACCEPTED ? "Accepted " : "") +
"Answer by <@" + s.getAuthorId() + ">")
.collect(Collectors.joining("\n"));
if (allAnswers.isEmpty()) {
allAnswers = "No accepted answers found.";
}
Expand All @@ -65,23 +80,13 @@ public void execute(SlashCommandInteractionEvent event) {
});
}

/**
* Checks whether a submission is visible to a specific user.
* @param submission the {@link QOTWSubmission} to be checked
* @param viewerID the user to check against
* @return {@code true} if the submission is visible, else {@code false}}
*/
public static boolean isSubmissionVisible(QOTWSubmission submission, long viewerID) {
return submission.getStatus() == SubmissionStatus.ACCEPTED || submission.getAuthorId() == viewerID;
}

private boolean isBestAnswer(TextChannel submissionChannel, QOTWSubmission submission) {
return submissionChannel
.retrieveArchivedPrivateThreadChannels()
.stream()
.filter(t -> t.getIdLong() == submission.getThreadId())
.findAny()
.map(t -> MarkBestAnswerSubcommand.isSubmissionThreadABestAnswer(t))
.orElse(false);
.retrieveArchivedPrivateThreadChannels()
.stream()
.filter(t -> t.getIdLong() == submission.getThreadId())
.findAny()
.map(MarkBestAnswerSubcommand::isSubmissionThreadABestAnswer)
.orElse(false);
}
}
Original file line number Diff line number Diff line change
@@ -1,17 +1,8 @@
package net.javadiscord.javabot.systems.qotw.commands.view;

import java.sql.SQLException;
import java.util.Comparator;
import java.util.List;

import javax.annotation.Nonnull;

import org.jetbrains.annotations.NotNull;

import com.dynxsty.dih4jda.interactions.ComponentIdBuilder;
import com.dynxsty.dih4jda.interactions.commands.SlashCommand;
import com.dynxsty.dih4jda.interactions.components.ButtonHandler;

import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.entities.MessageEmbed;
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
Expand All @@ -26,11 +17,17 @@
import net.javadiscord.javabot.systems.qotw.dao.QuestionQueueRepository;
import net.javadiscord.javabot.systems.qotw.model.QOTWQuestion;
import net.javadiscord.javabot.util.Responses;
import org.jetbrains.annotations.NotNull;

import javax.annotation.Nonnull;
import java.sql.SQLException;
import java.util.Comparator;
import java.util.List;

/**
* Represents the `/qotw-view query` subcommand. It allows for listing filtering QOTWs.
*/
public class QOTWQuerySubcommand extends SlashCommand.Subcommand implements ButtonHandler{
public class QOTWQuerySubcommand extends SlashCommand.Subcommand implements ButtonHandler {

private static final int MAX_BUTTON_QUERY_LENGTH = 10;
private static final int PAGE_LIMIT = 20;
Expand All @@ -39,30 +36,31 @@ public class QOTWQuerySubcommand extends SlashCommand.Subcommand implements Butt
* The constructor of this class, which sets the corresponding {@link SubcommandData}.
*/
public QOTWQuerySubcommand() {
setSubcommandData(new SubcommandData("list-questions", "Lists previous questions of the week")
setSubcommandData(new SubcommandData("list-questions", "Lists previous 'Questions of the Week'")
.addOption(OptionType.STRING, "query", "Only queries questions that contain a specific query", false)
.addOption(OptionType.INTEGER, "page", "The page to show, starting with 1", false));
.addOption(OptionType.INTEGER, "page", "The page to show, starting with 1", false)
);
}

@Override
public void execute(SlashCommandInteractionEvent event) {
if(!event.isFromGuild()) {
if (!event.isFromGuild()) {
Responses.replyGuildOnly(event).setEphemeral(true).queue();
return;
}
String query = event.getOption("query", "", OptionMapping::getAsString);
int page = event.getOption("page", 1, OptionMapping::getAsInt) -1;
int page = event.getOption("page", 1, OptionMapping::getAsInt) - 1;
if (page < 0) {
Responses.error(event, "Invalid page - must be >= 1").queue();
Responses.error(event, "The page must be equal to or greater than 1!").queue();
return;
}
event.deferReply(true).queue();
DbActions.doAsyncDaoAction(QuestionQueueRepository::new, repo-> {
DbActions.doAsyncDaoAction(QuestionQueueRepository::new, repo -> {
MessageEmbed embed = buildListQuestionsEmbed(repo, event.getGuild().getIdLong(), query, page);
event.getHook()
.sendMessageEmbeds(embed)
.addActionRows(buildPageControls(query, page, embed))
.queue();
.sendMessageEmbeds(embed)
.addActionRows(buildPageControls(query, page, embed))
.queue();
});
}

Expand All @@ -73,50 +71,47 @@ public void handleButton(@Nonnull ButtonInteractionEvent event, @Nonnull Button
int page = Integer.parseInt(id[1]);
String query = id.length == 2 ? "" : id[2];
if (page < 0) {
Responses.error(event.getHook(), "Invalid page - must be >= 1").queue();
Responses.error(event.getHook(), "The page must be equal to or greater than 1!").queue();
return;
}
DbHelper.doDaoAction(QuestionQueueRepository::new, repo -> {
MessageEmbed embed = buildListQuestionsEmbed(repo, event.getGuild().getIdLong(), query, page);
event.getHook()
.editOriginalEmbeds(embed)
.setActionRows(buildPageControls(query, page, embed))
.queue();
.editOriginalEmbeds(embed)
.setActionRows(buildPageControls(query, page, embed))
.queue();
});
}

@NotNull
private ActionRow buildPageControls(String query, int page, MessageEmbed embed) {
private ActionRow buildPageControls(@NotNull String query, int page, MessageEmbed embed) {
if (query.length() > MAX_BUTTON_QUERY_LENGTH) {
query = query.substring(0,MAX_BUTTON_QUERY_LENGTH);
query = query.substring(0, MAX_BUTTON_QUERY_LENGTH);
}
return ActionRow.of(
Button.primary(ComponentIdBuilder.build("qotw-list-questions", page - 1 + "", query), "Previous Page")
.withDisabled(page <= 0),
Button.primary(ComponentIdBuilder.build("qotw-list-questions", page + 1 + "", query), "Next Page")
.withDisabled(embed.getFields().size() < PAGE_LIMIT)
Button.primary(ComponentIdBuilder.build("qotw-list-questions", page - 1 + "", query), "Previous Page")
.withDisabled(page <= 0),
Button.primary(ComponentIdBuilder.build("qotw-list-questions", page + 1 + "", query), "Next Page")
.withDisabled(embed.getFields().size() < PAGE_LIMIT)
);
}

private MessageEmbed buildListQuestionsEmbed(QuestionQueueRepository repo, long guildId, String query, int page) throws SQLException {
List<QOTWQuestion> questions = repo.getUsedQuestionsWithQuery(guildId, query, page*PAGE_LIMIT, PAGE_LIMIT);
EmbedBuilder eb = new EmbedBuilder();
eb.setDescription("**Questions of the week"+(query.isEmpty()?"":" matching '"+query+"'")+"**");
questions
.stream()
.sorted(Comparator.comparingInt(QOTWQuestion::getQuestionNumber))
.map(q -> new MessageEmbed.Field("Question #" + q.getQuestionNumber(), q.getText(), true))
.forEach(eb::addField);
if(eb.getFields().isEmpty()) {
private @NotNull MessageEmbed buildListQuestionsEmbed(@NotNull QuestionQueueRepository repo, long guildId, String query, int page) throws SQLException {
List<QOTWQuestion> questions = repo.getUsedQuestionsWithQuery(guildId, query, page * PAGE_LIMIT, PAGE_LIMIT);
EmbedBuilder eb = new EmbedBuilder()
.setDescription("**Questions of the Week" + (query.isEmpty() ? "" : " matching '" + query + "'") + "**")
.setColor(Responses.Type.DEFAULT.getColor())
.setFooter("Page " + (page + 1));
questions.stream()
.sorted(Comparator.comparingInt(QOTWQuestion::getQuestionNumber))
.map(q -> new MessageEmbed.Field("Question #" + q.getQuestionNumber(), q.getText(), true))
.forEach(eb::addField);
if (eb.getFields().isEmpty()) {
eb.appendDescription("\nNo questions found");
if(page != 0) {
if (page != 0) {
eb.appendDescription(" on this page");
}
}
eb.setFooter("Page " + (page+1));
eb.setColor(Responses.Type.DEFAULT.getColor());
return eb.build();
}


}
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
package net.javadiscord.javabot.systems.qotw.commands.view;

import org.jetbrains.annotations.NotNull;

import com.dynxsty.dih4jda.interactions.commands.SlashCommand;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.entities.MessageEmbed;
Expand All @@ -15,23 +13,25 @@
import net.javadiscord.javabot.systems.qotw.submissions.model.QOTWSubmission;
import net.javadiscord.javabot.util.MessageActionUtils;
import net.javadiscord.javabot.util.Responses;
import org.jetbrains.annotations.NotNull;

/**
* Represents the `/qotw-view answer` subcommand. It allows for viewing an answer to a QOTW.
*/
public class QOTWViewAnswerSubcommand extends SlashCommand.Subcommand{
public class QOTWViewAnswerSubcommand extends SlashCommand.Subcommand {

/**
* The constructor of this class, which sets the corresponding {@link SubcommandData}.
*/
public QOTWViewAnswerSubcommand() {
setSubcommandData(new SubcommandData("answer", "Views the content of an answer to the Question of the Week")
.addOption(OptionType.INTEGER, "question", "The question number the answer has been submitted to", true)
.addOption(OptionType.USER, "answerer", "The user who answered the question", true));
.addOption(OptionType.USER, "answerer", "The user who answered the question", true)
);
}

@Override
public void execute(SlashCommandInteractionEvent event) {
public void execute(@NotNull SlashCommandInteractionEvent event) {
if (!event.isFromGuild()) {
Responses.replyGuildOnly(event).setEphemeral(true).queue();
return;
Expand All @@ -54,24 +54,22 @@ public void execute(SlashCommandInteractionEvent event) {
return;
}
Bot.getConfig().get(event.getGuild()).getQotwConfig()
.getSubmissionChannel().retrieveArchivedPrivateThreadChannels().queue(threadChannels->{
threadChannels
.stream()
.filter(c->c.getIdLong() == submission.getThreadId())
.findAny()
.ifPresentOrElse(submissionChannel->
submissionChannel.getHistoryFromBeginning(100).queue(history->
MessageActionUtils.copyMessagesToNewThread(event.getGuildChannel().asStandardGuildMessageChannel(),
buildQOTWInfoEmbed(submission, event.getMember()==null?event.getUser().getName():event.getMember().getEffectiveName()),
"QOTW #"+submission.getQuestionNumber(),
history.getRetrievedHistory(),
() -> Responses.success(event.getHook(), "View Answer", "Answer copied successfully").setEphemeral(true))),
() -> Responses.error(event.getHook(), "The QOTW submission thread was not found.").queue());
});
.getSubmissionChannel().retrieveArchivedPrivateThreadChannels().queue(threadChannels -> threadChannels
.stream()
.filter(c -> c.getIdLong() == submission.getThreadId())
.findAny()
.ifPresentOrElse(submissionChannel ->
submissionChannel.getHistoryFromBeginning(100).queue(history ->
MessageActionUtils.copyMessagesToNewThread(event.getGuildChannel().asStandardGuildMessageChannel(),
buildQOTWInfoEmbed(submission, event.getMember() == null ? event.getUser().getName() : event.getMember().getEffectiveName()),
"QOTW #" + submission.getQuestionNumber(),
history.getRetrievedHistory(),
() -> Responses.success(event.getHook(), "View Answer", "Answer copied successfully"))),
() -> Responses.error(event.getHook(), "The QOTW-Submission thread was not found.").queue()));
});
}

private @NotNull MessageEmbed buildQOTWInfoEmbed(QOTWSubmission submission, String requester) {
private @NotNull MessageEmbed buildQOTWInfoEmbed(@NotNull QOTWSubmission submission, String requester) {
return new EmbedBuilder()
.setTitle("Answer to Question of the Week #" + submission.getQuestionNumber())
.setDescription("Answer by <@" + submission.getAuthorId() + ">")
Expand Down
Original file line number Diff line number Diff line change
@@ -1,23 +1,23 @@
package net.javadiscord.javabot.systems.qotw.commands.view;

import com.dynxsty.dih4jda.interactions.commands.SlashCommand;

import net.dv8tion.jda.api.interactions.commands.DefaultMemberPermissions;
import net.dv8tion.jda.api.interactions.commands.build.Commands;

/**
* Represents the `/qotw-view` command.
* It allows to view previous QOTWs and their answers.
*/
public class QOTWViewCommand extends SlashCommand{
public class QOTWViewCommand extends SlashCommand {
/**
* This classes constructor which sets the {@link net.dv8tion.jda.api.interactions.commands.build.SlashCommandData} and
* adds the corresponding {@link net.dv8tion.jda.api.interactions.commands.Command.SubcommandGroup}s.
*/
public QOTWViewCommand() {
setSlashCommandData(Commands.slash("qotw-view", "Query questions of the week and their answers")
setSlashCommandData(Commands.slash("qotw-view", "Query 'Questions of the Week' and their answers")
.setDefaultPermissions(DefaultMemberPermissions.ENABLED)
.setGuildOnly(true));
.setGuildOnly(true)
);
addSubcommands(new QOTWQuerySubcommand(), new QOTWListAnswersSubcommand(), new QOTWViewAnswerSubcommand());

}
Expand Down