From 7ffd3442c24bb22ff15e31fe6b85dd4dc7fec450 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Beatrice=20Dellac=C3=A0?= Date: Sun, 20 Nov 2022 22:23:26 +0100 Subject: [PATCH] Remove code duplication in coinflip command --- .../commands/slash/CoinFlipCommand.java | 38 +++++++++---------- 1 file changed, 18 insertions(+), 20 deletions(-) diff --git a/src/main/java/wtf/beatrice/hidekobot/commands/slash/CoinFlipCommand.java b/src/main/java/wtf/beatrice/hidekobot/commands/slash/CoinFlipCommand.java index f2c52ef..02493fc 100644 --- a/src/main/java/wtf/beatrice/hidekobot/commands/slash/CoinFlipCommand.java +++ b/src/main/java/wtf/beatrice/hidekobot/commands/slash/CoinFlipCommand.java @@ -1,7 +1,6 @@ package wtf.beatrice.hidekobot.commands.slash; 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.component.ButtonInteractionEvent; import net.dv8tion.jda.api.interactions.components.ActionRow; @@ -14,30 +13,32 @@ import java.util.List; public class CoinFlipCommand { + private final Button reflipButton = Button.primary("coinflip_reflip", "Flip again") + .withEmoji(Emoji.fromFormatted("\uD83E\uDE99")); + public void runSlashCommand(@NotNull SlashCommandInteractionEvent event) { - int rand = RandomUtil.getRandomNumber(0, 1); - String msg; - - if(rand == 1) - { - 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(); + // perform coin flip + event.reply(genRandom()) + .addActionRow(reflipButton) + .queue(); } - public void buttonReflip(ButtonInteractionEvent event) + public void buttonReFlip(ButtonInteractionEvent event) { + // set old message's button as disabled List actionRows = event.getMessage().getActionRows(); actionRows.set(0, actionRows.get(0).asDisabled()); event.editComponents(actionRows).queue(); + // perform coin flip + event.getHook().sendMessage(genRandom()) + .addActionRow(reflipButton) + .queue(); + } + + private String genRandom() + { int rand = RandomUtil.getRandomNumber(0, 1); String msg; @@ -48,10 +49,7 @@ public class CoinFlipCommand msg = "It's **Tails**! :coin:"; } - event.getHook().sendMessage(msg) - .addActionRow(Button.primary("reflip", "Flip again") - .withEmoji(Emoji.fromFormatted("\uD83E\uDE99")) // coin emoji - ).queue(); + return msg; } }