|
| 1 | +package technobot.commands.fun; |
| 2 | + |
| 3 | +import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; |
| 4 | +import okhttp3.Call; |
| 5 | +import okhttp3.Callback; |
| 6 | +import okhttp3.Request; |
| 7 | +import okhttp3.Response; |
| 8 | +import technobot.TechnoBot; |
| 9 | +import technobot.commands.Category; |
| 10 | +import technobot.commands.Command; |
| 11 | +import technobot.util.embeds.EmbedUtils; |
| 12 | + |
| 13 | +import java.io.IOException; |
| 14 | +import java.util.List; |
| 15 | +import java.util.concurrent.ThreadLocalRandom; |
| 16 | + |
| 17 | +/** |
| 18 | + * Command that generates a link from uselessweb. |
| 19 | + * |
| 20 | + * @author TechnoVision |
| 21 | + */ |
| 22 | +public class SurpriseCommand extends Command { |
| 23 | + |
| 24 | + public SurpriseCommand(TechnoBot bot) { |
| 25 | + super(bot); |
| 26 | + this.name = "surprise"; |
| 27 | + this.description = "Get a fun and unique surprise."; |
| 28 | + this.category = Category.FUN; |
| 29 | + } |
| 30 | + |
| 31 | + @Override |
| 32 | + public void execute(SlashCommandInteractionEvent event) { |
| 33 | + event.deferReply().queue(); |
| 34 | + Request request = new Request.Builder() |
| 35 | + .url("https://gist.githubusercontent.com/quest/07bbc6908f84b50a9fc8/raw/d8983a0723d07203816b78953ff52f07423c808d/uselessweb.json") |
| 36 | + .build(); |
| 37 | + |
| 38 | + // Asynchronous API call |
| 39 | + bot.httpClient.newCall(request).enqueue(new Callback() { |
| 40 | + @Override |
| 41 | + public void onFailure(Call call, IOException e) { |
| 42 | + String text = "I was unable to fetch any surprises!"; |
| 43 | + event.getHook().sendMessageEmbeds(EmbedUtils.createError(text)).queue(); |
| 44 | + } |
| 45 | + |
| 46 | + @Override |
| 47 | + public void onResponse(Call call, final Response response) throws IOException { |
| 48 | + if (!response.isSuccessful()) throw new IOException(); |
| 49 | + SiteList entity = bot.gson.fromJson(response.body().string(), SiteList.class); |
| 50 | + int index = ThreadLocalRandom.current().nextInt(entity.uselessweb.size()); |
| 51 | + event.getHook().sendMessage(entity.uselessweb.get(index)).queue(); |
| 52 | + } |
| 53 | + }); |
| 54 | + } |
| 55 | + |
| 56 | + /** |
| 57 | + * Represents a joke retrieved from the joke api. |
| 58 | + * Used by OkHttp and Gson to convert JSON to java code. |
| 59 | + */ |
| 60 | + private class SiteList { |
| 61 | + |
| 62 | + public List<String> uselessweb; |
| 63 | + |
| 64 | + public SiteList(List<String> uselessweb) { |
| 65 | + this.uselessweb = uselessweb; |
| 66 | + } |
| 67 | + } |
| 68 | +} |
0 commit comments