Remove code duplication in coinflip command

This commit is contained in:
Bea 2022-11-20 22:23:26 +01:00
parent 3a5b2a23c1
commit 7ffd3442c2
1 changed files with 18 additions and 20 deletions

View File

@ -1,7 +1,6 @@
package wtf.beatrice.hidekobot.commands.slash; package wtf.beatrice.hidekobot.commands.slash;
import net.dv8tion.jda.api.entities.emoji.Emoji; import net.dv8tion.jda.api.entities.emoji.Emoji;
import net.dv8tion.jda.api.events.interaction.GenericInteractionCreateEvent;
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
import net.dv8tion.jda.api.events.interaction.component.ButtonInteractionEvent; import net.dv8tion.jda.api.events.interaction.component.ButtonInteractionEvent;
import net.dv8tion.jda.api.interactions.components.ActionRow; import net.dv8tion.jda.api.interactions.components.ActionRow;
@ -14,30 +13,32 @@ import java.util.List;
public class CoinFlipCommand public class CoinFlipCommand
{ {
private final Button reflipButton = Button.primary("coinflip_reflip", "Flip again")
.withEmoji(Emoji.fromFormatted("\uD83E\uDE99"));
public void runSlashCommand(@NotNull SlashCommandInteractionEvent event) public void runSlashCommand(@NotNull SlashCommandInteractionEvent event)
{ {
int rand = RandomUtil.getRandomNumber(0, 1); // perform coin flip
String msg; event.reply(genRandom())
.addActionRow(reflipButton)
if(rand == 1) .queue();
{
msg = ":coin: It's **Heads**!";
} else {
msg = "It's **Tails**! :coin:";
}
event.reply(msg)
.addActionRow(Button.primary("reflip", "Flip again")
.withEmoji(Emoji.fromFormatted("\uD83E\uDE99")) // coin emoji
).queue();
} }
public void buttonReflip(ButtonInteractionEvent event) public void buttonReFlip(ButtonInteractionEvent event)
{ {
// set old message's button as disabled
List<ActionRow> actionRows = event.getMessage().getActionRows(); List<ActionRow> actionRows = event.getMessage().getActionRows();
actionRows.set(0, actionRows.get(0).asDisabled()); actionRows.set(0, actionRows.get(0).asDisabled());
event.editComponents(actionRows).queue(); event.editComponents(actionRows).queue();
// perform coin flip
event.getHook().sendMessage(genRandom())
.addActionRow(reflipButton)
.queue();
}
private String genRandom()
{
int rand = RandomUtil.getRandomNumber(0, 1); int rand = RandomUtil.getRandomNumber(0, 1);
String msg; String msg;
@ -48,10 +49,7 @@ public class CoinFlipCommand
msg = "It's **Tails**! :coin:"; msg = "It's **Tails**! :coin:";
} }
event.getHook().sendMessage(msg) return msg;
.addActionRow(Button.primary("reflip", "Flip again")
.withEmoji(Emoji.fromFormatted("\uD83E\uDE99")) // coin emoji
).queue();
} }
} }