From 30e5205a0e4925750b45c0dddb8eea5c2e5f6263 Mon Sep 17 00:00:00 2001 From: Andre601 <11576465+Andre601@users.noreply.github.com> Date: Wed, 10 Aug 2022 18:21:20 +0200 Subject: [PATCH 1/6] v3 rewrite --- build.gradle | 9 +- src/main/java/site/purrbot/bot/PurrBot.java | 432 +-------------- .../site/purrbot/bot/commands/Command.java | 50 -- .../purrbot/bot/commands/CommandListener.java | 163 ------ .../purrbot/bot/commands/CommandLoader.java | 116 ---- .../purrbot/bot/commands/fun/CmdBite.java | 106 ---- .../purrbot/bot/commands/fun/CmdBlush.java | 55 -- .../purrbot/bot/commands/fun/CmdComfy.java | 55 -- .../site/purrbot/bot/commands/fun/CmdCry.java | 55 -- .../purrbot/bot/commands/fun/CmdCuddle.java | 100 ---- .../purrbot/bot/commands/fun/CmdDance.java | 55 -- .../purrbot/bot/commands/fun/CmdEevee.java | 59 -- .../purrbot/bot/commands/fun/CmdFeed.java | 93 ---- .../purrbot/bot/commands/fun/CmdFluff.java | 99 ---- .../purrbot/bot/commands/fun/CmdHolo.java | 55 -- .../site/purrbot/bot/commands/fun/CmdHug.java | 100 ---- .../purrbot/bot/commands/fun/CmdKiss.java | 105 ---- .../purrbot/bot/commands/fun/CmdKitsune.java | 55 -- .../purrbot/bot/commands/fun/CmdLick.java | 106 ---- .../purrbot/bot/commands/fun/CmdNeko.java | 59 -- .../purrbot/bot/commands/fun/CmdOkami.java | 54 -- .../site/purrbot/bot/commands/fun/CmdPat.java | 100 ---- .../purrbot/bot/commands/fun/CmdPoke.java | 100 ---- .../purrbot/bot/commands/fun/CmdSenko.java | 55 -- .../purrbot/bot/commands/fun/CmdShip.java | 224 -------- .../purrbot/bot/commands/fun/CmdSlap.java | 100 ---- .../purrbot/bot/commands/fun/CmdSmile.java | 55 -- .../purrbot/bot/commands/fun/CmdTail.java | 55 -- .../purrbot/bot/commands/fun/CmdTickle.java | 100 ---- .../bot/commands/guild/CmdLanguage.java | 133 ----- .../purrbot/bot/commands/guild/CmdPrefix.java | 95 ---- .../bot/commands/guild/CmdWelcome.java | 510 ------------------ .../purrbot/bot/commands/info/CmdDonate.java | 141 ----- .../purrbot/bot/commands/info/CmdEmote.java | 187 ------- .../purrbot/bot/commands/info/CmdGuild.java | 323 ----------- .../purrbot/bot/commands/info/CmdHelp.java | 342 ------------ .../purrbot/bot/commands/info/CmdInfo.java | 157 ------ .../purrbot/bot/commands/info/CmdInvite.java | 129 ----- .../purrbot/bot/commands/info/CmdPing.java | 68 --- .../purrbot/bot/commands/info/CmdQuote.java | 127 ----- .../purrbot/bot/commands/info/CmdShards.java | 170 ------ .../purrbot/bot/commands/info/CmdStats.java | 167 ------ .../purrbot/bot/commands/info/CmdUser.java | 250 --------- .../purrbot/bot/commands/nsfw/CmdBlowjob.java | 103 ---- .../purrbot/bot/commands/nsfw/CmdCum.java | 57 -- .../purrbot/bot/commands/nsfw/CmdFuck.java | 354 ------------ .../purrbot/bot/commands/nsfw/CmdLewd.java | 59 -- .../bot/commands/nsfw/CmdPussylick.java | 92 ---- .../purrbot/bot/commands/nsfw/CmdSolo.java | 55 -- .../purrbot/bot/commands/nsfw/CmdSpank.java | 120 ----- .../bot/commands/nsfw/CmdThreesome.java | 227 -------- .../purrbot/bot/commands/owner/CmdCheck.java | 97 ---- .../purrbot/bot/commands/owner/CmdEval.java | 122 ----- .../purrbot/bot/commands/owner/CmdLeave.java | 94 ---- .../bot/commands/owner/CmdListEmotes.java | 117 ---- .../purrbot/bot/commands/owner/CmdMsg.java | 97 ---- .../bot/commands/owner/CmdShutdown.java | 64 --- .../site/purrbot/bot/constants/Emotes.java | 153 ------ .../java/site/purrbot/bot/constants/IDs.java | 40 -- .../site/purrbot/bot/constants/Links.java | 43 -- .../bot/listener/ConnectionListener.java | 116 ---- .../purrbot/bot/listener/GuildListener.java | 218 -------- .../purrbot/bot/listener/MemberListener.java | 92 ---- .../purrbot/bot/listener/ReadyListener.java | 117 ---- .../java/site/purrbot/bot/util/CheckUtil.java | 188 ------- .../java/site/purrbot/bot/util/DBUtil.java | 96 ---- .../site/purrbot/bot/util/GuildSettings.java | 126 ----- .../java/site/purrbot/bot/util/HttpUtil.java | 356 ------------ .../java/site/purrbot/bot/util/ImageUtil.java | 236 -------- .../site/purrbot/bot/util/RequestUtil.java | 252 --------- .../purrbot/bot/util/file/FileManager.java | 199 ------- .../purrbot/bot/util/file/lang/LangUtils.java | 112 ---- .../purrbot/bot/util/message/EmbedUtil.java | 142 ----- .../purrbot/bot/util/message/MessageUtil.java | 290 ---------- .../purrbot/bot/util/message/WebhookUtil.java | 50 -- 75 files changed, 24 insertions(+), 10029 deletions(-) delete mode 100644 src/main/java/site/purrbot/bot/commands/Command.java delete mode 100644 src/main/java/site/purrbot/bot/commands/CommandListener.java delete mode 100644 src/main/java/site/purrbot/bot/commands/CommandLoader.java delete mode 100644 src/main/java/site/purrbot/bot/commands/fun/CmdBite.java delete mode 100644 src/main/java/site/purrbot/bot/commands/fun/CmdBlush.java delete mode 100644 src/main/java/site/purrbot/bot/commands/fun/CmdComfy.java delete mode 100644 src/main/java/site/purrbot/bot/commands/fun/CmdCry.java delete mode 100644 src/main/java/site/purrbot/bot/commands/fun/CmdCuddle.java delete mode 100644 src/main/java/site/purrbot/bot/commands/fun/CmdDance.java delete mode 100644 src/main/java/site/purrbot/bot/commands/fun/CmdEevee.java delete mode 100644 src/main/java/site/purrbot/bot/commands/fun/CmdFeed.java delete mode 100644 src/main/java/site/purrbot/bot/commands/fun/CmdFluff.java delete mode 100644 src/main/java/site/purrbot/bot/commands/fun/CmdHolo.java delete mode 100644 src/main/java/site/purrbot/bot/commands/fun/CmdHug.java delete mode 100644 src/main/java/site/purrbot/bot/commands/fun/CmdKiss.java delete mode 100644 src/main/java/site/purrbot/bot/commands/fun/CmdKitsune.java delete mode 100644 src/main/java/site/purrbot/bot/commands/fun/CmdLick.java delete mode 100644 src/main/java/site/purrbot/bot/commands/fun/CmdNeko.java delete mode 100644 src/main/java/site/purrbot/bot/commands/fun/CmdOkami.java delete mode 100644 src/main/java/site/purrbot/bot/commands/fun/CmdPat.java delete mode 100644 src/main/java/site/purrbot/bot/commands/fun/CmdPoke.java delete mode 100644 src/main/java/site/purrbot/bot/commands/fun/CmdSenko.java delete mode 100644 src/main/java/site/purrbot/bot/commands/fun/CmdShip.java delete mode 100644 src/main/java/site/purrbot/bot/commands/fun/CmdSlap.java delete mode 100644 src/main/java/site/purrbot/bot/commands/fun/CmdSmile.java delete mode 100644 src/main/java/site/purrbot/bot/commands/fun/CmdTail.java delete mode 100644 src/main/java/site/purrbot/bot/commands/fun/CmdTickle.java delete mode 100644 src/main/java/site/purrbot/bot/commands/guild/CmdLanguage.java delete mode 100644 src/main/java/site/purrbot/bot/commands/guild/CmdPrefix.java delete mode 100644 src/main/java/site/purrbot/bot/commands/guild/CmdWelcome.java delete mode 100644 src/main/java/site/purrbot/bot/commands/info/CmdDonate.java delete mode 100644 src/main/java/site/purrbot/bot/commands/info/CmdEmote.java delete mode 100644 src/main/java/site/purrbot/bot/commands/info/CmdGuild.java delete mode 100644 src/main/java/site/purrbot/bot/commands/info/CmdHelp.java delete mode 100644 src/main/java/site/purrbot/bot/commands/info/CmdInfo.java delete mode 100644 src/main/java/site/purrbot/bot/commands/info/CmdInvite.java delete mode 100644 src/main/java/site/purrbot/bot/commands/info/CmdPing.java delete mode 100644 src/main/java/site/purrbot/bot/commands/info/CmdQuote.java delete mode 100644 src/main/java/site/purrbot/bot/commands/info/CmdShards.java delete mode 100644 src/main/java/site/purrbot/bot/commands/info/CmdStats.java delete mode 100644 src/main/java/site/purrbot/bot/commands/info/CmdUser.java delete mode 100644 src/main/java/site/purrbot/bot/commands/nsfw/CmdBlowjob.java delete mode 100644 src/main/java/site/purrbot/bot/commands/nsfw/CmdCum.java delete mode 100644 src/main/java/site/purrbot/bot/commands/nsfw/CmdFuck.java delete mode 100644 src/main/java/site/purrbot/bot/commands/nsfw/CmdLewd.java delete mode 100644 src/main/java/site/purrbot/bot/commands/nsfw/CmdPussylick.java delete mode 100644 src/main/java/site/purrbot/bot/commands/nsfw/CmdSolo.java delete mode 100644 src/main/java/site/purrbot/bot/commands/nsfw/CmdSpank.java delete mode 100644 src/main/java/site/purrbot/bot/commands/nsfw/CmdThreesome.java delete mode 100644 src/main/java/site/purrbot/bot/commands/owner/CmdCheck.java delete mode 100644 src/main/java/site/purrbot/bot/commands/owner/CmdEval.java delete mode 100644 src/main/java/site/purrbot/bot/commands/owner/CmdLeave.java delete mode 100644 src/main/java/site/purrbot/bot/commands/owner/CmdListEmotes.java delete mode 100644 src/main/java/site/purrbot/bot/commands/owner/CmdMsg.java delete mode 100644 src/main/java/site/purrbot/bot/commands/owner/CmdShutdown.java delete mode 100644 src/main/java/site/purrbot/bot/constants/Emotes.java delete mode 100644 src/main/java/site/purrbot/bot/constants/IDs.java delete mode 100644 src/main/java/site/purrbot/bot/constants/Links.java delete mode 100644 src/main/java/site/purrbot/bot/listener/ConnectionListener.java delete mode 100644 src/main/java/site/purrbot/bot/listener/GuildListener.java delete mode 100644 src/main/java/site/purrbot/bot/listener/MemberListener.java delete mode 100644 src/main/java/site/purrbot/bot/listener/ReadyListener.java delete mode 100644 src/main/java/site/purrbot/bot/util/CheckUtil.java delete mode 100644 src/main/java/site/purrbot/bot/util/DBUtil.java delete mode 100644 src/main/java/site/purrbot/bot/util/GuildSettings.java delete mode 100644 src/main/java/site/purrbot/bot/util/HttpUtil.java delete mode 100644 src/main/java/site/purrbot/bot/util/ImageUtil.java delete mode 100644 src/main/java/site/purrbot/bot/util/RequestUtil.java delete mode 100644 src/main/java/site/purrbot/bot/util/file/FileManager.java delete mode 100644 src/main/java/site/purrbot/bot/util/file/lang/LangUtils.java delete mode 100644 src/main/java/site/purrbot/bot/util/message/EmbedUtil.java delete mode 100644 src/main/java/site/purrbot/bot/util/message/MessageUtil.java delete mode 100644 src/main/java/site/purrbot/bot/util/message/WebhookUtil.java diff --git a/build.gradle b/build.gradle index 8224028af..81f807177 100644 --- a/build.gradle +++ b/build.gradle @@ -46,20 +46,13 @@ dependencies { compile group: 'ch.qos.logback', name: 'logback-classic', version: '1.2.11' compile group: 'pw.chew', name: 'jda-chewtils-commons', version: '2.0-SNAPSHOT' compile group: 'pw.chew', name: 'jda-chewtils-menu', version: '2.0-SNAPSHOT' + compile group: 'pw.chew', name: 'jda-chewtils-command', version: '2.0-SNAPSHOT' compile group: 'com.rethinkdb', name: 'rethinkdb-driver', version:'2.4.4' - compile group: 'com.google.code.gson', name: 'gson', version: '2.9.1' compile(group: 'net.dv8tion', name: 'JDA', version:'5.0.0-alpha.17'){ exclude(module: 'opus-java') } compile group: 'club.minnced', name: 'discord-webhooks', version: '0.8.2' - compile group: 'commons-io', name: 'commons-io', version: '2.11.0' - compile group: 'commons-lang', name: 'commons-lang', version: '2.6' - compile group: 'com.mashape.unirest', name: 'unirest-java', version: '1.4.9' - compile group: 'com.github.rainestormee', name: 'jda-command', version: '1.1.5' compile group: 'com.github.ben-manes.caffeine', name: 'caffeine', version: '3.1.1' - compile group: 'org.projectlombok', name: 'lombok', version: '1.18.24' - compile group: 'io.javalin', name: 'javalin', version: '4.6.4' - compile group: 'org.json', name: 'json', version: '20220320' compile group: 'com.squareup.okhttp3', name: 'okhttp', version: '4.10.0' } diff --git a/src/main/java/site/purrbot/bot/PurrBot.java b/src/main/java/site/purrbot/bot/PurrBot.java index d4dd1b2f5..caf539c69 100644 --- a/src/main/java/site/purrbot/bot/PurrBot.java +++ b/src/main/java/site/purrbot/bot/PurrBot.java @@ -1,5 +1,5 @@ /* - * Copyright 2018 - 2021 Andre601 + * Copyright 2018 - 2022 Andre601 * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation @@ -19,430 +19,44 @@ package site.purrbot.bot; import ch.qos.logback.classic.Logger; -import com.github.benmanes.caffeine.cache.Cache; -import com.github.benmanes.caffeine.cache.Caffeine; -import com.github.rainestormee.jdacommand.CommandHandler; +import com.jagrosh.jdautilities.command.CommandClient; import com.jagrosh.jdautilities.commons.waiter.EventWaiter; -import io.javalin.Javalin; -import net.dv8tion.jda.api.JDA; -import net.dv8tion.jda.api.OnlineStatus; -import net.dv8tion.jda.api.entities.Activity; -import net.dv8tion.jda.api.entities.Message; -import net.dv8tion.jda.api.requests.GatewayIntent; -import net.dv8tion.jda.api.requests.restaction.MessageAction; -import net.dv8tion.jda.api.sharding.DefaultShardManagerBuilder; import net.dv8tion.jda.api.sharding.ShardManager; -import net.dv8tion.jda.api.utils.ChunkingFilter; -import net.dv8tion.jda.api.utils.MemberCachePolicy; -import net.dv8tion.jda.api.utils.cache.CacheFlag; -import org.jetbrains.annotations.NotNull; -import org.json.JSONArray; -import org.json.JSONObject; import org.slf4j.LoggerFactory; -import site.purrbot.bot.commands.CommandListener; -import site.purrbot.bot.commands.CommandLoader; -import site.purrbot.bot.constants.Emotes; -import site.purrbot.bot.constants.IDs; -import site.purrbot.bot.constants.Links; -import site.purrbot.bot.listener.ConnectionListener; -import site.purrbot.bot.listener.GuildListener; -import site.purrbot.bot.listener.MemberListener; -import site.purrbot.bot.listener.ReadyListener; -import site.purrbot.bot.util.*; -import site.purrbot.bot.util.file.FileManager; -import site.purrbot.bot.util.file.lang.LangUtils; -import site.purrbot.bot.util.message.EmbedUtil; -import site.purrbot.bot.util.message.MessageUtil; import javax.security.auth.login.LoginException; -import java.util.*; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeUnit; -import java.util.function.BiConsumer; +import java.util.Random; -public class PurrBot { - - private final Logger logger = (Logger)LoggerFactory.getLogger(PurrBot.class); - - private ShardManager shardManager = null; - - private final Random random = new Random(); - - private final FileManager fileManager = new FileManager(); - private final HttpUtil httpUtil = new HttpUtil(); - private final CommandLoader commandLoader = new CommandLoader(this); - - private DBUtil dbUtil; - private MessageUtil messageUtil; - private EmbedUtil embedUtil; - private ImageUtil imageUtil; - private LangUtils langUtils; - private CheckUtil checkUtil; - private RequestUtil requestUtil; - - private boolean beta = false; - - private final CommandHandler CMD_HANDLER = new CommandHandler<>(); - private final EventWaiter waiter = new EventWaiter(); - private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(); - - private final Cache<@NotNull String, @NotNull GuildSettings> guildSettings = Caffeine.newBuilder() - .expireAfterWrite(10, TimeUnit.MINUTES) - .build(); - - public static void main(String[] args){ - try{ - new PurrBot().setup(); - }catch(LoginException ex){ - new PurrBot().logger.error("Couldn't login to Discord!", ex); - } - } - - private void setup() throws LoginException{ - getFileManager().addFile("config", "/config.json", "./config.json") - .addFile("data", "/data.json", "./data.json") - .addFile("random", "/random.json", "./random.json") - .addLang("de-CH") - .addLang("de-DE") - .addLang("en") - .addLang("en-OWO") - .addLang("es-ES") - .addLang("fr-FR") - //.addLang("it-IT") // Discontinued at the moment. - .addLang("ko-KR") - .addLang("pt-BR") - .addLang("ru-RU") - .addLang("tr-TR"); - - dbUtil = new DBUtil(this); - messageUtil = new MessageUtil(this); - embedUtil = new EmbedUtil(this); - imageUtil = new ImageUtil(this); - langUtils = new LangUtils(this); - checkUtil = new CheckUtil(this); - requestUtil = new RequestUtil(this); - - beta = getFileManager().getBoolean("config", "beta"); - - CMD_HANDLER.registerCommands(new HashSet<>(commandLoader.getCommands())); - - MessageAction.setDefaultMentions(EnumSet.of( - Message.MentionType.ROLE, - Message.MentionType.USER - )); - shardManager = DefaultShardManagerBuilder - .createDefault(getFileManager().getString("config", "bot-token")) - .disableIntents(GatewayIntent.GUILD_VOICE_STATES) - .enableIntents(GatewayIntent.GUILD_MEMBERS, GatewayIntent.GUILD_MESSAGES, GatewayIntent.MESSAGE_CONTENT) - .disableCache(CacheFlag.VOICE_STATE) - .setChunkingFilter(ChunkingFilter.include(Long.parseLong(IDs.GUILD))) - .setMemberCachePolicy(beta ? MemberCachePolicy.ALL : MemberCachePolicy.OWNER) - .addEventListeners( - new ReadyListener(this), - new ConnectionListener(this), - new GuildListener(this), - new MemberListener(this), - new CommandListener(this, CMD_HANDLER), - waiter - ) - .setShardsTotal(-1) - .setActivity(Activity.of(Activity.ActivityType.PLAYING, getMessageUtil().getRandomStartupMsg())) - .setStatus(OnlineStatus.DO_NOT_DISTURB) - .build(); - - setupStatusAPI(); - } - - public Random getRandom(){ - return random; - } - - public ShardManager getShardManager(){ - return shardManager; - } - public DBUtil getDbUtil(){ - return dbUtil; - } - public CheckUtil getCheckUtil(){ - return checkUtil; - } - public FileManager getFileManager(){ - return fileManager; - } - public MessageUtil getMessageUtil(){ - return messageUtil; - } - public EmbedUtil getEmbedUtil(){ - return embedUtil; - } - public HttpUtil getHttpUtil(){ - return httpUtil; - } - public ImageUtil getImageUtil(){ - return imageUtil; - } - public RequestUtil getRequestUtil(){ - return requestUtil; - } - - public boolean isBeta(){ - return beta; - } - public boolean isSpecial(String id){ - return getFileManager().getStringlist("data", "special").contains(id); - } - - public CommandHandler getCmdHandler(){ - return CMD_HANDLER; - } - public EventWaiter getWaiter(){ - return waiter; - } - - public String getLanguage(String id){ - return getGuildSettings(id).getLanguage(); - } - public String getPrefix(String id){ - return getGuildSettings(id).getPrefix(); - } - public String getWelcomeBg(String id){ - return getGuildSettings(id).getWelcomeBackground(); - } - public String getWelcomeChannel(String id){ - return getGuildSettings(id).getWelcomeChannel(); - } - public String getWelcomeColor(String id){ - return getGuildSettings(id).getWelcomeColor(); - } - public String getWelcomeIcon(String id){ - return getGuildSettings(id).getWelcomeIcon(); - } - public String getWelcomeMsg(String id){ - return getGuildSettings(id).getWelcomeMessage(); - } - - public void setLanguage(String id, String value){ - updateGuild(id, GuildSettings.LANGUAGE, value, GuildSettings::setLanguage); - } - public void setPrefix(String id, String value){ - updateGuild(id, GuildSettings.PREFIX, value, GuildSettings::setPrefix); - } - public void setWelcomeBg(String id, String value){ - updateGuild(id, GuildSettings.WELCOME_BACKGROUND, value, GuildSettings::setWelcomeBackground); - } - public void setWelcomeChannel(String id, String value){ - updateGuild(id, GuildSettings.WELCOME_CHANNEL, value, GuildSettings::setWelcomeChannel); - } - public void setWelcomeColor(String id, String value){ - updateGuild(id, GuildSettings.WELCOME_COLOR, value, GuildSettings::setWelcomeColor); - } - public void setWelcomeIcon(String id, String value){ - updateGuild(id, GuildSettings.WELCOME_ICON, value, GuildSettings::setWelcomeIcon); - } - public void setWelcomeMsg(String id, String value){ - updateGuild(id, GuildSettings.WELCOME_MESSAGE, value, GuildSettings::setWelcomeMessage); - } - - public void invalidateCache(String id){ - guildSettings.invalidate(id); - } - - public List getBlacklist(){ - return getFileManager().getStringlist("data", "blacklist"); - } - public List getDonators(){ - return getFileManager().getStringlist("data", "donators"); - } - public List getShutdownImg(){ - return getFileManager().getStringlist("random", "shutdown_img"); - } - public List getShutdownMsg(){ - return getFileManager().getStringlist("random", "shutdown_msg"); - } - public List getStartupMsg(){ - return getFileManager().getStringlist("random", "startup_msg"); - } - public List getWelcomeBg(){ - return getFileManager().getStringlist("data", "welcome.background"); - } - public List getWelcomeIcon(){ - return getFileManager().getStringlist("data", "welcome.icon"); - } - - public String getMsg(String id, String path, String user, String target){ - target = target == null ? "null" : target; - - return getMsg(id, path, user, Collections.singletonList(target)); - } - - public String getMsg(String id, String path, String user, List targets){ - String targetReplacement = targets.isEmpty() ? "null" : getMessageUtil().getFormattedMembers(id, targets.toArray(new String[0])); - - return getMsg(id, path, user) - .replace("{target}", targetReplacement) - .replace("{targets}", targetReplacement); - } - - public String getMsg(String id, String path, String user){ - return getMsg(id, path, user, true); - } - - public String getMsg(String id, String path, String user, boolean format){ - if(format) - user = getMessageUtil().getFormattedMembers(id, user); - - return getMsg(id, path).replace("{user}", user); - } - - public String getMsg(String id, String path){ - return setPlaceholders(langUtils.getString(getLanguage(id), path)) - .replace("{prefix}", getPrefix(id)); - } +public class PurrBot{ - public String getRandomMsg(String id, String path, String user){ - user = getMessageUtil().getFormattedMembers(id, user); - - return getRandomMsg(id, path).replace("{user}", user); - } + // Bot Instance + private static PurrBot bot; - public String getRandomMsg(String id, String path){ - List list = langUtils.getStringList(getLanguage(id), path); - - return list.isEmpty() ? "" : setPlaceholders(list.get(getRandom().nextInt(list.size()))); - } + // Bot classes - public void startUpdater(){ - scheduler.scheduleAtFixedRate(() -> { - getShardManager().setActivity(Activity.of( - Activity.ActivityType.WATCHING, - getMessageUtil().getBotGame(getShardManager().getGuildCache().size()) - )); - - if(isBeta()) - return; - - long guilds = getShardManager().getGuildCache().size(); - long shards = getShardManager().getShardCache().size(); - - logger.info("Posting Guild Stats to Bot lists..."); - for(HttpUtil.BotList botList : HttpUtil.BotList.values()){ - getHttpUtil().postServerStats( - "*Purr*", - "6875", - guilds, - shards, - botList, - getFileManager().getString("config", botList.getTokenPath()) - ).whenComplete((botListResult, ex) -> { - if(botListResult == null || !botListResult.isSuccess() || ex != null){ - logger.warn("Error while posting Guild stats to bot list {}!", botList.getName()); - if(botListResult == null){ - logger.warn("BotListResult is null!"); - return; - } - - if(ex != null){ - ex.printStackTrace(); - return; - } - - logger.info("Response Code: {}", botListResult.getResponseCode()); - logger.info("Response Message: {}", botListResult.getResponseMessage()); - return; - } - - logger.info("Successfully posted stats to {}!", botListResult.getBotList()); - }); - } - }, 1, 5, TimeUnit.MINUTES); - } - public void disable(){ - scheduler.shutdown(); - shardManager.shutdown(); - System.exit(0); - } + // JDA + private ShardManager shardManager = null; - private String setPlaceholders(String msg){ - return Emotes.getWithEmotes(msg) - // Guild link - .replace("{guild_invite}", Links.DISCORD) - - // Wiki pages - .replace("{wiki}", Links.WIKI) - .replace("{wiki_bg}", Links.WIKI + "/welcome-images#backgrounds") - .replace("{wiki_icon}", Links.WIKI + "/welcome-images#icons") - .replace("{wiki_welcome}", Links.WIKI + "/welcome-channel") - - // Other pages - .replace("{github_url}", Links.GITHUB) - .replace("{twitter_url}", Links.TWITTER) - .replace("{website_url}", Links.WEBSITE) - .replace("{policy_url}", Links.POLICY) - .replace("{paypal_url}", Links.PAYPAL) - .replace("{patreon_url}", Links.PATREON) - .replace("{kofi_url}", Links.KOFI); - } + // JDA-Chewtils + private CommandClient commandClient; + private final EventWaiter eventWaiter = new EventWaiter(); - private void setupStatusAPI(){ - if(this.isBeta()) - return; - - Javalin app = Javalin.create(config -> config.defaultContentType = "application/json") - .start(7000); - - app.get("shards", response -> response.status(200).result(getShardInfo())); - } + // Java + private final Random random = new Random(); + private final Logger logger = (Logger)LoggerFactory.getLogger(PurrBot.class); - private String getShardInfo(){ - JSONArray array = new JSONArray(); - List shards = new ArrayList<>(shardManager.getShards()); - - shards.sort(Comparator.comparing(jda -> jda.getShardInfo().getShardId())); - - shards.stream().map( - shard -> new JSONObject() - .put("id", shard.getShardInfo().getShardId()) - .put("status", shard.getStatus()) - .put("guilds", shard.getGuildCache().size()) - ).forEach(array::put); - - JSONObject result = new JSONObject() - .put("shard_count", shardManager.getShardCache().size()) - .put("guilds", shardManager.getGuildCache().size()) - .put("timestamp", System.currentTimeMillis()) - .put("shards", array); - - return result.toString(2); - } + // Start Code - private void updateGuild(String id, String key, String value, BiConsumer mutator){ - GuildSettings settings = getGuildSettings(id); - - mutator.accept(settings, value); - getDbUtil().updateSettings(id, key, value); - - guildSettings.put(id, settings); + public static void main(String[] args){ + try{ + (bot = new PurrBot()).startBot(); + }catch(LoginException ex){ + new PurrBot().logger.warn("Cannot connect to Discord.", ex); + } } - private GuildSettings getGuildSettings(String id){ - return guildSettings.get(id, k -> { - Map guild = getDbUtil().getGuild(id); - if(guild == null){ - getDbUtil().addGuild(id); + private void startBot() throws LoginException{ - return GuildSettings.createDefault(isBeta()); - } - - return new GuildSettings() - .setLanguage(guild.getOrDefault(GuildSettings.LANGUAGE, GuildSettings.DEF_LANGUAGE)) - .setPrefix(guild.getOrDefault(GuildSettings.PREFIX, isBeta() ? GuildSettings.DEF_PREFIX_BETA : GuildSettings.DEF_PREFIX)) - .setWelcomeBackground(guild.getOrDefault(GuildSettings.WELCOME_BACKGROUND, GuildSettings.DEF_BACKGROUND)) - .setWelcomeChannel(guild.getOrDefault(GuildSettings.WELCOME_CHANNEL, GuildSettings.DEF_CHANNEL)) - .setWelcomeColor(guild.getOrDefault(GuildSettings.WELCOME_COLOR, GuildSettings.DEF_COLOR)) - .setWelcomeIcon(guild.getOrDefault(GuildSettings.WELCOME_ICON, GuildSettings.DEF_ICON)) - .setWelcomeMessage(guild.getOrDefault(GuildSettings.WELCOME_MESSAGE, GuildSettings.DEF_MESSAGE)); - }); } } diff --git a/src/main/java/site/purrbot/bot/commands/Command.java b/src/main/java/site/purrbot/bot/commands/Command.java deleted file mode 100644 index ace0b7ff8..000000000 --- a/src/main/java/site/purrbot/bot/commands/Command.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright 2018 - 2021 Andre601 - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated - * documentation files (the "Software"), to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, - * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or substantial - * portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package site.purrbot.bot.commands; - -import com.github.rainestormee.jdacommand.AbstractCommand; -import net.dv8tion.jda.api.entities.Guild; -import net.dv8tion.jda.api.entities.Member; -import net.dv8tion.jda.api.entities.Message; -import net.dv8tion.jda.api.entities.TextChannel; - -public interface Command extends AbstractCommand{ - - /* - * We convert the default "execute(Message, String, String)" to our own "run(Guild, TextChannel, Message, Member, String...)" - * method to have a better command system. - * - * This method isn't automatically implemented into the classes, since it's being overridden here. - */ - @Override - default void execute(Message message, String s, String trigger){ - String[] args = s.isEmpty() ? new String[0] : s.split("\\s+", 3); - - if(message.getMember() == null) - return; - - // We trigger the below method to run the commands. - run(message.getGuild(), message.getChannel().asTextChannel(), message, message.getMember(), args); - } - - /* - * This is the method we use in the commands to provide the information for easier handling. - */ - void run(Guild guild, TextChannel tc, Message msg, Member member, String... args); -} diff --git a/src/main/java/site/purrbot/bot/commands/CommandListener.java b/src/main/java/site/purrbot/bot/commands/CommandListener.java deleted file mode 100644 index 75ddd2bfd..000000000 --- a/src/main/java/site/purrbot/bot/commands/CommandListener.java +++ /dev/null @@ -1,163 +0,0 @@ -/* - * Copyright 2018 - 2021 Andre601 - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated - * documentation files (the "Software"), to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, - * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or substantial - * portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package site.purrbot.bot.commands; - -import ch.qos.logback.classic.Logger; -import com.github.rainestormee.jdacommand.CommandHandler; -import net.dv8tion.jda.api.Permission; -import net.dv8tion.jda.api.entities.*; -import net.dv8tion.jda.api.entities.emoji.Emoji; -import net.dv8tion.jda.api.events.message.MessageReceivedEvent; -import net.dv8tion.jda.api.hooks.ListenerAdapter; -import org.jetbrains.annotations.NotNull; -import org.slf4j.LoggerFactory; -import site.purrbot.bot.PurrBot; -import site.purrbot.bot.constants.Emotes; -import site.purrbot.bot.constants.IDs; - -import java.util.Arrays; -import java.util.concurrent.Executor; -import java.util.concurrent.Executors; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -public class CommandListener extends ListenerAdapter{ - - private final Logger logger = (Logger)LoggerFactory.getLogger(CommandListener.class); - - private final ThreadGroup CMD_THREAD = new ThreadGroup("CommandThread"); - private final Executor CMD_EXECUTOR = Executors.newCachedThreadPool( - r -> new Thread(CMD_THREAD, r, "CommandPool") - ); - - private final PurrBot bot; - private final CommandHandler HANDLER; - - public CommandListener(PurrBot bot, CommandHandler handler){ - this.bot = bot; - this.HANDLER = handler; - } - - @Override - public void onMessageReceived(@NotNull MessageReceivedEvent event){ - CMD_EXECUTOR.execute(() -> { - if(!event.isFromGuild() || event.getChannel().getType() != ChannelType.TEXT) - return; - - Message msg = event.getMessage(); - Guild guild = event.getGuild(); - User user = event.getAuthor(); - - if(user.isBot()) - return; - - if(event.getChannel().getId().equals(IDs.SUGGESTIONS)) - return; - - if(event.getChannel().getType() == ChannelType.NEWS) - return; - - Pattern prefixPattern = Pattern.compile( - Pattern.quote(bot.getPrefix(guild.getId())) + "(?[^\\s].*)", - Pattern.DOTALL | Pattern.CASE_INSENSITIVE - ); - - String raw = msg.getContentRaw(); - - Matcher commandMatcher = prefixPattern.matcher(raw); - Matcher mentionMatcher = Message.MentionType.USER.getPattern().matcher(raw); - - if(!commandMatcher.matches() && !mentionMatcher.matches()) - return; - - TextChannel tc = event.getChannel().asTextChannel(); - Member self = guild.getSelfMember(); - - Member member = msg.getMember(); - if(member == null) - return; - - if(mentionMatcher.matches()){ - if(!self.hasPermission(tc, Permission.MESSAGE_SEND)) - return; - - if(!mentionMatcher.group(1).equalsIgnoreCase(self.getId())) - return; - - msg.reply(bot.getMsg(guild.getId(), "misc.info", member.getEffectiveName())).queue(); - return; - } - - raw = commandMatcher.group("command"); - - String[] args = Arrays.copyOf(raw.split("\\s+", 2), 2); - - if(args[0] == null) - return; - - Command command = (Command)HANDLER.findCommand(args[0].toLowerCase()); - - if(command == null) - return; - - if(!self.hasPermission(tc, Permission.MESSAGE_SEND)){ - if(self.hasPermission(tc, Permission.MESSAGE_ADD_REACTION, Permission.MESSAGE_EXT_EMOJI, Permission.MESSAGE_HISTORY)) - msg.addReaction(Emoji.fromFormatted(Emotes.DENY.getEmote())).queue(); - - return; - } - - if(command.getAttribute("category").equals("owner") && !bot.getCheckUtil().isDeveloper(member)) - return; - - if(bot.getCheckUtil().hasAdmin(member, tc)) - return; - - if(bot.getCheckUtil().lacksPermission(tc, member, true, tc, Permission.MESSAGE_EMBED_LINKS)) - return; - - if(bot.getCheckUtil().lacksPermission(tc, member, true, tc, Permission.MESSAGE_HISTORY)) - return; - - if(bot.getCheckUtil().lacksPermission(tc, member, true, tc, Permission.MESSAGE_ADD_REACTION)) - return; - - if(bot.getCheckUtil().lacksPermission(tc, member, true, tc, Permission.MESSAGE_EXT_EMOJI)) - return; - - if(command.getAttribute("category").equals("nsfw") && !tc.isNSFW()){ - bot.getEmbedUtil().sendError(tc, member, "errors.nsfw_random", true); - return; - } - - if(command.hasAttribute("manage_server")){ - if(bot.getCheckUtil().lacksPermission(tc, member, Permission.MANAGE_SERVER)) - return; - } - - try{ - String arguments = args[1] == null ? "" : args[1]; - HANDLER.execute(command, msg, arguments, args[0]); - }catch(Exception ex){ - logger.error("Couldn't perform command {}!", args[0], ex); - bot.getEmbedUtil().sendError(tc, member, "errors.unknown", ex.getMessage(), false); - } - }); - } -} diff --git a/src/main/java/site/purrbot/bot/commands/CommandLoader.java b/src/main/java/site/purrbot/bot/commands/CommandLoader.java deleted file mode 100644 index ab717aa10..000000000 --- a/src/main/java/site/purrbot/bot/commands/CommandLoader.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * Copyright 2018 - 2021 Andre601 - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated - * documentation files (the "Software"), to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, - * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or substantial - * portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package site.purrbot.bot.commands; - -import ch.qos.logback.classic.Logger; -import org.slf4j.LoggerFactory; -import site.purrbot.bot.PurrBot; -import site.purrbot.bot.commands.fun.*; -import site.purrbot.bot.commands.guild.CmdLanguage; -import site.purrbot.bot.commands.guild.CmdPrefix; -import site.purrbot.bot.commands.guild.CmdWelcome; -import site.purrbot.bot.commands.info.*; -import site.purrbot.bot.commands.nsfw.*; -import site.purrbot.bot.commands.owner.*; - -import java.util.Arrays; -import java.util.HashSet; -import java.util.Set; - -public class CommandLoader { - - private final Set COMMANDS = new HashSet<>(); - - public CommandLoader(PurrBot bot){ - final Logger logger = (Logger)LoggerFactory.getLogger(CommandLoader.class); - loadCommands( - // Fun - new CmdBite(bot), - new CmdBlush(bot), - new CmdComfy(bot), - new CmdCry(bot), - new CmdCuddle(bot), - new CmdDance(bot), - new CmdEevee(bot), - new CmdFeed(bot), - new CmdFluff(bot), - new CmdHolo(bot), - new CmdHug(bot), - new CmdKiss(bot), - new CmdKitsune(bot), - new CmdLick(bot), - new CmdNeko(bot), - new CmdOkami(bot), - new CmdPat(bot), - new CmdPoke(bot), - new CmdSenko(bot), - new CmdShip(bot), - new CmdSlap(bot), - new CmdSmile(bot), - new CmdTail(bot), - new CmdTickle(bot), - - // Guild - new CmdLanguage(bot), - new CmdPrefix(bot), - new CmdWelcome(bot), - - // Info - new CmdDonate(bot), - new CmdEmote(bot), - new CmdGuild(bot), - new CmdHelp(bot), - new CmdInfo(bot), - new CmdInvite(bot), - new CmdPing(bot), - new CmdQuote(bot), - new CmdShards(bot), - new CmdStats(bot), - new CmdUser(bot), - - // NSFW - new CmdBlowjob(bot), - new CmdCum(bot), - new CmdFuck(bot), - new CmdLewd(bot), - new CmdPussylick(bot), - new CmdSolo(bot), - new CmdSpank(bot), - new CmdThreesome(bot), - - // Owner - new CmdCheck(bot), - new CmdEval(bot), - new CmdLeave(bot), - new CmdListEmotes(bot), - new CmdMsg(bot), - new CmdShutdown(bot) - ); - - logger.info("Loaded {} commands!", COMMANDS.size()); - } - - public Set getCommands(){ - return COMMANDS; - } - - private void loadCommands(Command... commands){ - COMMANDS.addAll(Arrays.asList(commands)); - } -} diff --git a/src/main/java/site/purrbot/bot/commands/fun/CmdBite.java b/src/main/java/site/purrbot/bot/commands/fun/CmdBite.java deleted file mode 100644 index b220174b2..000000000 --- a/src/main/java/site/purrbot/bot/commands/fun/CmdBite.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * Copyright 2018 - 2021 Andre601 - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated - * documentation files (the "Software"), to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, - * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or substantial - * portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package site.purrbot.bot.commands.fun; - -import ch.qos.logback.classic.Logger; -import com.github.rainestormee.jdacommand.CommandAttribute; -import com.github.rainestormee.jdacommand.CommandDescription; -import net.dv8tion.jda.api.entities.Guild; -import net.dv8tion.jda.api.entities.Member; -import net.dv8tion.jda.api.entities.Message; -import net.dv8tion.jda.api.entities.TextChannel; -import net.dv8tion.jda.api.entities.emoji.Emoji; -import org.slf4j.LoggerFactory; -import site.purrbot.bot.PurrBot; -import site.purrbot.bot.commands.Command; -import site.purrbot.bot.util.HttpUtil; - -import java.util.List; -import java.util.stream.Collectors; - -@CommandDescription( - name = "Bite", - description = "purr.fun.bite.description", - triggers = {"bite", "nibble", "nom"}, - attributes = { - @CommandAttribute(key = "category", value = "fun"), - @CommandAttribute(key = "usage", value = "{p}bite <@user> [@user ...]"), - @CommandAttribute(key = "help", value = "{p}bite <@user> [@user ...]") - } -) -public class CmdBite implements Command{ - - private final PurrBot bot; - private final Logger logger = (Logger)LoggerFactory.getLogger("Command - Bite"); - - public CmdBite(PurrBot bot){ - this.bot = bot; - } - - @Override - public void run(Guild guild, TextChannel tc, Message msg, Member member, String... args){ - List members = msg.getMentions().getMembers(); - - if(members.isEmpty()){ - bot.getEmbedUtil().sendError(tc, member, "purr.fun.bite.no_mention"); - return; - } - - if(members.contains(guild.getSelfMember())){ - if(bot.isBeta()){ - tc.sendMessage( - bot.getRandomMsg(guild.getId(), "snuggle.fun.bite.mention_snuggle", member.getAsMention()) - ).queue(); - }else{ - if(bot.isSpecial(member.getId())){ - tc.sendMessage( - bot.getMsg(guild.getId(), "purr.fun.bite.special_user", member.getAsMention()) - ).queue(); - }else{ - tc.sendMessage( - bot.getRandomMsg(guild.getId(), "purr.fun.bite.mention_purr", member.getAsMention()) - ).queue(); - } - } - msg.addReaction(Emoji.fromUnicode("\uD83D\uDE16")).queue( - null, - e -> logger.warn("Couldn't add a Reaction to a message.") - ); - } - - if(members.contains(member)){ - tc.sendMessage( - bot.getMsg(guild.getId(), "purr.fun.bite.mention_self", member.getAsMention()) - ).queue(); - } - - List targets = members.stream() - .filter(mem -> !mem.equals(guild.getSelfMember())) - .filter(mem -> !mem.equals(member)) - .map(Member::getEffectiveName) - .collect(Collectors.toList()); - - if(targets.isEmpty()) - return; - - tc.sendMessage(bot.getMsg(guild.getId(), "purr.fun.bite.loading")).queue(message -> - bot.getRequestUtil().handleEdit(tc, message, HttpUtil.ImageAPI.BITE, member, targets) - ); - } -} diff --git a/src/main/java/site/purrbot/bot/commands/fun/CmdBlush.java b/src/main/java/site/purrbot/bot/commands/fun/CmdBlush.java deleted file mode 100644 index 7831d324d..000000000 --- a/src/main/java/site/purrbot/bot/commands/fun/CmdBlush.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright 2018 - 2021 Andre601 - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated - * documentation files (the "Software"), to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, - * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or substantial - * portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package site.purrbot.bot.commands.fun; - -import com.github.rainestormee.jdacommand.CommandAttribute; -import com.github.rainestormee.jdacommand.CommandDescription; -import net.dv8tion.jda.api.entities.Guild; -import net.dv8tion.jda.api.entities.Member; -import net.dv8tion.jda.api.entities.Message; -import net.dv8tion.jda.api.entities.TextChannel; -import site.purrbot.bot.PurrBot; -import site.purrbot.bot.commands.Command; -import site.purrbot.bot.util.HttpUtil; - -@CommandDescription( - name = "Blush", - description = "purr.fun.blush.description", - triggers = {"blush", "blushing"}, - attributes = { - @CommandAttribute(key = "category", value = "fun"), - @CommandAttribute(key = "usage", value = "{p}blush"), - @CommandAttribute(key = "help", value = "{p}blush") - } -) -public class CmdBlush implements Command{ - - private final PurrBot bot; - - public CmdBlush(PurrBot bot){ - this.bot = bot; - } - - @Override - public void run(Guild guild, TextChannel tc, Message msg, Member member, String... args){ - tc.sendMessage(bot.getMsg(guild.getId(), "purr.fun.blush.loading")).queue(message -> - bot.getRequestUtil().handleEdit(tc, message, HttpUtil.ImageAPI.BLUSH, member) - ); - } -} diff --git a/src/main/java/site/purrbot/bot/commands/fun/CmdComfy.java b/src/main/java/site/purrbot/bot/commands/fun/CmdComfy.java deleted file mode 100644 index 63ad652ab..000000000 --- a/src/main/java/site/purrbot/bot/commands/fun/CmdComfy.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright 2018 - 2022 Andre601 - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated - * documentation files (the "Software"), to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, - * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or substantial - * portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package site.purrbot.bot.commands.fun; - -import com.github.rainestormee.jdacommand.CommandAttribute; -import com.github.rainestormee.jdacommand.CommandDescription; -import net.dv8tion.jda.api.entities.Guild; -import net.dv8tion.jda.api.entities.Member; -import net.dv8tion.jda.api.entities.Message; -import net.dv8tion.jda.api.entities.TextChannel; -import site.purrbot.bot.PurrBot; -import site.purrbot.bot.commands.Command; -import site.purrbot.bot.util.HttpUtil; - -@CommandDescription( - name = "Comfy", - description = "purr.fun.comfy.description", - triggers = {"comfy"}, - attributes = { - @CommandAttribute(key = "category", value = "fun"), - @CommandAttribute(key = "usage", value = "{p}comfy"), - @CommandAttribute(key = "help", value = "{p}comfy") - } -) -public class CmdComfy implements Command{ - - private final PurrBot bot; - - public CmdComfy(PurrBot bot){ - this.bot = bot; - } - - @Override - public void run(Guild guild, TextChannel tc, Message msg, Member member, String... args){ - tc.sendMessage(bot.getMsg(guild.getId(), "purr.fun.comfy.loading")).queue( - message -> bot.getRequestUtil().handleEdit(tc, message, HttpUtil.ImageAPI.COMFY, member) - ); - } -} diff --git a/src/main/java/site/purrbot/bot/commands/fun/CmdCry.java b/src/main/java/site/purrbot/bot/commands/fun/CmdCry.java deleted file mode 100644 index bf11918d5..000000000 --- a/src/main/java/site/purrbot/bot/commands/fun/CmdCry.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright 2018 - 2021 Andre601 - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated - * documentation files (the "Software"), to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, - * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or substantial - * portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package site.purrbot.bot.commands.fun; - -import com.github.rainestormee.jdacommand.CommandAttribute; -import com.github.rainestormee.jdacommand.CommandDescription; -import net.dv8tion.jda.api.entities.Guild; -import net.dv8tion.jda.api.entities.Member; -import net.dv8tion.jda.api.entities.Message; -import net.dv8tion.jda.api.entities.TextChannel; -import site.purrbot.bot.PurrBot; -import site.purrbot.bot.commands.Command; -import site.purrbot.bot.util.HttpUtil; - -@CommandDescription( - name = "Cry", - description = "purr.fun.cry.description", - triggers = {"cry", "sob"}, - attributes = { - @CommandAttribute(key = "category", value = "fun"), - @CommandAttribute(key = "usage", value = "{p}cry"), - @CommandAttribute(key = "help", value = "{p}cry") - } -) -public class CmdCry implements Command{ - - private final PurrBot bot; - - public CmdCry(PurrBot bot){ - this.bot = bot; - } - - @Override - public void run(Guild guild, TextChannel tc, Message msg, Member member, String... args){ - tc.sendMessage(bot.getMsg(guild.getId(), "purr.fun.cry.loading")).queue(message -> - bot.getRequestUtil().handleEdit(tc, message, HttpUtil.ImageAPI.CRY, member) - ); - } -} diff --git a/src/main/java/site/purrbot/bot/commands/fun/CmdCuddle.java b/src/main/java/site/purrbot/bot/commands/fun/CmdCuddle.java deleted file mode 100644 index 47e93caba..000000000 --- a/src/main/java/site/purrbot/bot/commands/fun/CmdCuddle.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright 2018 - 2021 Andre601 - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated - * documentation files (the "Software"), to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, - * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or substantial - * portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package site.purrbot.bot.commands.fun; - -import ch.qos.logback.classic.Logger; -import com.github.rainestormee.jdacommand.CommandAttribute; -import com.github.rainestormee.jdacommand.CommandDescription; -import net.dv8tion.jda.api.entities.Guild; -import net.dv8tion.jda.api.entities.Member; -import net.dv8tion.jda.api.entities.Message; -import net.dv8tion.jda.api.entities.TextChannel; -import net.dv8tion.jda.api.entities.emoji.Emoji; -import org.slf4j.LoggerFactory; -import site.purrbot.bot.PurrBot; -import site.purrbot.bot.commands.Command; -import site.purrbot.bot.util.HttpUtil; - -import java.util.List; -import java.util.stream.Collectors; - -@CommandDescription( - name = "Cuddle", - description = "purr.fun.cuddle.description", - triggers = {"cuddle", "cuddles", "snuggle", "snuggles", "squeeze", "squish"}, - attributes = { - @CommandAttribute(key = "category", value = "fun"), - @CommandAttribute(key = "usage", value = "{p}cuddle <@user> [@user ...]"), - @CommandAttribute(key = "help", value = "{p}cuddle <@user> [@user ...]") - } -) -public class CmdCuddle implements Command{ - - private final PurrBot bot; - private final Logger logger = (Logger)LoggerFactory.getLogger("Command - Cuddle"); - - public CmdCuddle(PurrBot bot){ - this.bot = bot; - } - - @Override - public void run(Guild guild, TextChannel tc, Message msg, Member member, String... args){ - List members = msg.getMentions().getMembers(); - - if(members.isEmpty()){ - bot.getEmbedUtil().sendError(tc, member, "purr.fun.cuddle.no_mention"); - return; - } - - if(members.contains(guild.getSelfMember())){ - if(bot.isBeta()){ - tc.sendMessage( - bot.getRandomMsg(guild.getId(), "snuggle.fun.cuddle.mention_snuggle", member.getAsMention()) - ).queue(); - }else{ - tc.sendMessage( - bot.getRandomMsg(guild.getId(), "purr.fun.cuddle.mention_purr", member.getAsMention()) - ).queue(); - } - msg.addReaction(Emoji.fromUnicode("\u2764")).queue( - null, - e -> logger.warn("Couldn't add Reaction to a message.") - ); - } - - if(members.contains(member)){ - tc.sendMessage( - bot.getMsg(guild.getId(), "purr.fun.cuddle.mention_self", member.getAsMention()) - ).queue(); - } - - List targets = members.stream() - .filter(mem -> !mem.equals(guild.getSelfMember())) - .filter(mem -> !mem.equals(member)) - .map(Member::getEffectiveName) - .collect(Collectors.toList()); - - if(targets.isEmpty()) - return; - - tc.sendMessage(bot.getMsg(guild.getId(), "purr.fun.cuddle.loading")).queue(message -> - bot.getRequestUtil().handleEdit(tc, message, HttpUtil.ImageAPI.CUDDLE, member, targets) - ); - } -} diff --git a/src/main/java/site/purrbot/bot/commands/fun/CmdDance.java b/src/main/java/site/purrbot/bot/commands/fun/CmdDance.java deleted file mode 100644 index 808c754c1..000000000 --- a/src/main/java/site/purrbot/bot/commands/fun/CmdDance.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright 2018 - 2021 Andre601 - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated - * documentation files (the "Software"), to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, - * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or substantial - * portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package site.purrbot.bot.commands.fun; - -import com.github.rainestormee.jdacommand.CommandAttribute; -import com.github.rainestormee.jdacommand.CommandDescription; -import net.dv8tion.jda.api.entities.Guild; -import net.dv8tion.jda.api.entities.Member; -import net.dv8tion.jda.api.entities.Message; -import net.dv8tion.jda.api.entities.TextChannel; -import site.purrbot.bot.PurrBot; -import site.purrbot.bot.commands.Command; -import site.purrbot.bot.util.HttpUtil; - -@CommandDescription( - name = "Dance", - description = "purr.fun.dance.description", - triggers = {"dance", "dancing"}, - attributes = { - @CommandAttribute(key = "category", value = "fun"), - @CommandAttribute(key = "usage", value = "{p}dance"), - @CommandAttribute(key = "help", value = "{p}dance") - } -) -public class CmdDance implements Command{ - - private final PurrBot bot; - - public CmdDance(PurrBot bot){ - this.bot = bot; - } - - @Override - public void run(Guild guild, TextChannel tc, Message msg, Member member, String... args){ - tc.sendMessage(bot.getMsg(guild.getId(), "purr.fun.dance.loading")).queue(message -> - bot.getRequestUtil().handleEdit(tc, message, HttpUtil.ImageAPI.DANCE, member) - ); - } -} diff --git a/src/main/java/site/purrbot/bot/commands/fun/CmdEevee.java b/src/main/java/site/purrbot/bot/commands/fun/CmdEevee.java deleted file mode 100644 index 1dd03da6e..000000000 --- a/src/main/java/site/purrbot/bot/commands/fun/CmdEevee.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright 2018 - 2021 Andre601 - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated - * documentation files (the "Software"), to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, - * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or substantial - * portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package site.purrbot.bot.commands.fun; - -import com.github.rainestormee.jdacommand.CommandAttribute; -import com.github.rainestormee.jdacommand.CommandDescription; -import net.dv8tion.jda.api.entities.Guild; -import net.dv8tion.jda.api.entities.Member; -import net.dv8tion.jda.api.entities.Message; -import net.dv8tion.jda.api.entities.TextChannel; -import site.purrbot.bot.PurrBot; -import site.purrbot.bot.commands.Command; -import site.purrbot.bot.util.HttpUtil; - -@CommandDescription( - name = "Eevee", - description = "purr.fun.eevee.description", - triggers = {"eevee"}, - attributes = { - @CommandAttribute(key = "category", value = "fun"), - @CommandAttribute(key = "usage", value = "{p}eevee [--gif]"), - @CommandAttribute(key = "help", value = "{p}eevee [--gif]") - } -) -public class CmdEevee implements Command{ - - private final PurrBot bot; - - public CmdEevee(PurrBot bot){ - this.bot = bot; - } - - @Override - public void run(Guild guild, TextChannel tc, Message msg, Member member, String... args){ - tc.sendMessage(bot.getMsg(guild.getId(), "purr.fun.eevee.loading")).queue(message -> { - if(bot.getMessageUtil().hasArg("gif", args)){ - bot.getRequestUtil().handleEdit(tc, message, HttpUtil.ImageAPI.EEVEE_GIF, member); - }else{ - bot.getRequestUtil().handleEdit(tc, message, HttpUtil.ImageAPI.EEVEE_IMG, member); - } - }); - } -} diff --git a/src/main/java/site/purrbot/bot/commands/fun/CmdFeed.java b/src/main/java/site/purrbot/bot/commands/fun/CmdFeed.java deleted file mode 100644 index 577635039..000000000 --- a/src/main/java/site/purrbot/bot/commands/fun/CmdFeed.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright 2018 - 2021 Andre601 - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated - * documentation files (the "Software"), to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, - * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or substantial - * portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package site.purrbot.bot.commands.fun; - -import ch.qos.logback.classic.Logger; -import com.github.rainestormee.jdacommand.CommandAttribute; -import com.github.rainestormee.jdacommand.CommandDescription; -import net.dv8tion.jda.api.entities.Guild; -import net.dv8tion.jda.api.entities.Member; -import net.dv8tion.jda.api.entities.Message; -import net.dv8tion.jda.api.entities.TextChannel; -import net.dv8tion.jda.api.entities.emoji.Emoji; -import org.slf4j.LoggerFactory; -import site.purrbot.bot.PurrBot; -import site.purrbot.bot.commands.Command; -import site.purrbot.bot.util.HttpUtil; - -@CommandDescription( - name = "Feed", - description = "purr.fun.feed.description", - triggers = {"feed", "food", "eat"}, - attributes = { - @CommandAttribute(key = "category", value = "fun"), - @CommandAttribute(key = "usage", value = "{p}feed <@user>"), - @CommandAttribute(key = "help", value = "{p}feed <@user>") - } -) -public class CmdFeed implements Command{ - - private final PurrBot bot; - private final Logger logger = (Logger)LoggerFactory.getLogger("Command - Feed"); - - public CmdFeed(PurrBot bot){ - this.bot = bot; - } - - @Override - public void run(Guild guild, TextChannel tc, Message msg, Member member, String... args){ - if(msg.getMentions().getMembers().isEmpty()){ - bot.getEmbedUtil().sendError(tc, member, "purr.fun.feed.no_mention"); - return; - } - - Member target = msg.getMentions().getMembers().get(0); - - if(target.equals(guild.getSelfMember())){ - if(bot.isBeta()){ - tc.sendMessage( - bot.getRandomMsg(guild.getId(), "snuggle.fun.feed.mention_snuggle", member.getAsMention()) - ).queue(); - }else{ - tc.sendMessage( - bot.getRandomMsg(guild.getId(), "purr.fun.feed.mention_purr", member.getAsMention()) - ).queue(); - } - msg.addReaction(Emoji.fromUnicode("\u2764")).queue( - null, - e -> logger.warn("Couldn't add Reaction to a message.") - ); - return; - } - - if(target.equals(member)){ - tc.sendMessage( - bot.getMsg(guild.getId(), "purr.fun.feed.mention_self", member.getAsMention()) - ).queue(); - return; - } - - if(target.getUser().isBot()){ - bot.getEmbedUtil().sendError(tc, member, "purr.fun.feed.mention_bot"); - return; - } - - bot.getRequestUtil().handleButtonEvent(tc, member, target, HttpUtil.ImageAPI.FEED); - } -} diff --git a/src/main/java/site/purrbot/bot/commands/fun/CmdFluff.java b/src/main/java/site/purrbot/bot/commands/fun/CmdFluff.java deleted file mode 100644 index ac45e4b61..000000000 --- a/src/main/java/site/purrbot/bot/commands/fun/CmdFluff.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright 2018 - 2021 Andre601 - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated - * documentation files (the "Software"), to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, - * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or substantial - * portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package site.purrbot.bot.commands.fun; - -import com.github.rainestormee.jdacommand.CommandAttribute; -import com.github.rainestormee.jdacommand.CommandDescription; -import net.dv8tion.jda.api.entities.Guild; -import net.dv8tion.jda.api.entities.Member; -import net.dv8tion.jda.api.entities.Message; -import net.dv8tion.jda.api.entities.TextChannel; -import site.purrbot.bot.PurrBot; -import site.purrbot.bot.commands.Command; -import site.purrbot.bot.util.HttpUtil; - -@CommandDescription( - name = "Fluff", - description = "purr.fun.fluff.description", - triggers = {"fluff", "fluffing"}, - attributes = { - @CommandAttribute(key = "category", value = "fun"), - @CommandAttribute(key = "usage", value = "{p}fluff <@user>"), - @CommandAttribute(key = "help", value = "{p}fluff <@user>") - } -) -public class CmdFluff implements Command{ - - private final PurrBot bot; - - public CmdFluff(PurrBot bot){ - this.bot = bot; - } - - @Override - public void run(Guild guild, TextChannel tc, Message msg, Member member, String... args){ - if(msg.getMentions().getMembers().isEmpty()){ - bot.getEmbedUtil().sendError(tc, member, "purr.fun.fluff.no_mention"); - return; - } - - Member target = msg.getMentions().getMembers().get(0); - - if(target.equals(guild.getSelfMember())){ - if(bot.isSpecial(member.getId())){ - if(bot.isBeta()){ - tc.sendMessage( - bot.getMsg(guild.getId(), "snuggle.fun.fluff.special_user", member.getAsMention()) - ).queue(); - }else{ - tc.sendMessage( - bot.getMsg(guild.getId(), "purr.fun.fluff.special_user", member.getAsMention()) - ).queue(); - } - }else{ - if(bot.isBeta()){ - tc.sendMessage( - bot.getRandomMsg(guild.getId(), "snuggle.fun.fluff.mention_snuggle", member.getAsMention()) - ).queue(); - }else{ - tc.sendMessage( - bot.getRandomMsg(guild.getId(), "purr.fun.fluff.mention_purr", member.getAsMention()) - ).queue(); - } - } - return; - } - - if(target.equals(member)){ - tc.sendMessage( - bot.getMsg(guild.getId(), "purr.fun.fluff.mention_self", member.getAsMention()) - ).queue(); - return; - } - - if(target.getUser().isBot()){ - tc.sendMessage( - bot.getMsg(guild.getId(), "purr.fun.fluff.mention_bot", member.getAsMention()) - ).queue(); - return; - } - - bot.getRequestUtil().handleButtonEvent(tc, member, target, HttpUtil.ImageAPI.FLUFF); - } -} diff --git a/src/main/java/site/purrbot/bot/commands/fun/CmdHolo.java b/src/main/java/site/purrbot/bot/commands/fun/CmdHolo.java deleted file mode 100644 index 14a900c38..000000000 --- a/src/main/java/site/purrbot/bot/commands/fun/CmdHolo.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright 2018 - 2021 Andre601 - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated - * documentation files (the "Software"), to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, - * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or substantial - * portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package site.purrbot.bot.commands.fun; - -import com.github.rainestormee.jdacommand.CommandAttribute; -import com.github.rainestormee.jdacommand.CommandDescription; -import net.dv8tion.jda.api.entities.Guild; -import net.dv8tion.jda.api.entities.Member; -import net.dv8tion.jda.api.entities.Message; -import net.dv8tion.jda.api.entities.TextChannel; -import site.purrbot.bot.PurrBot; -import site.purrbot.bot.commands.Command; -import site.purrbot.bot.util.HttpUtil; - -@CommandDescription( - name = "Holo", - description = "purr.fun.holo.description", - triggers = {"holo", "spiceandwolf"}, - attributes = { - @CommandAttribute(key = "category", value = "fun"), - @CommandAttribute(key = "usage", value = "{p}holo"), - @CommandAttribute(key = "help", value = "{p}holo") - } -) -public class CmdHolo implements Command{ - - private final PurrBot bot; - - public CmdHolo(PurrBot bot){ - this.bot = bot; - } - - @Override - public void run(Guild guild, TextChannel tc, Message msg, Member member, String... args){ - tc.sendMessage(bot.getMsg(guild.getId(), "purr.fun.holo.loading")).queue(message -> - bot.getRequestUtil().handleEdit(tc, message, HttpUtil.ImageAPI.HOLO, member) - ); - } -} diff --git a/src/main/java/site/purrbot/bot/commands/fun/CmdHug.java b/src/main/java/site/purrbot/bot/commands/fun/CmdHug.java deleted file mode 100644 index df26df0ec..000000000 --- a/src/main/java/site/purrbot/bot/commands/fun/CmdHug.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright 2018 - 2021 Andre601 - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated - * documentation files (the "Software"), to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, - * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or substantial - * portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package site.purrbot.bot.commands.fun; - -import ch.qos.logback.classic.Logger; -import com.github.rainestormee.jdacommand.CommandAttribute; -import com.github.rainestormee.jdacommand.CommandDescription; -import net.dv8tion.jda.api.entities.Guild; -import net.dv8tion.jda.api.entities.Member; -import net.dv8tion.jda.api.entities.Message; -import net.dv8tion.jda.api.entities.TextChannel; -import net.dv8tion.jda.api.entities.emoji.Emoji; -import org.slf4j.LoggerFactory; -import site.purrbot.bot.PurrBot; -import site.purrbot.bot.commands.Command; -import site.purrbot.bot.util.HttpUtil; - -import java.util.List; -import java.util.stream.Collectors; - -@CommandDescription( - name = "Hug", - description = "purr.fun.hug.description", - triggers = {"hug", "hugging", "hugs"}, - attributes = { - @CommandAttribute(key = "category", value = "fun"), - @CommandAttribute(key = "usage", value = "{p}hug <@user> [@user ...]"), - @CommandAttribute(key = "help", value = "{p}hug <@user> [@user ...]") - } -) -public class CmdHug implements Command{ - - private final PurrBot bot; - private final Logger logger = (Logger)LoggerFactory.getLogger("Command - Hug"); - - public CmdHug(PurrBot bot){ - this.bot = bot; - } - - @Override - public void run(Guild guild, TextChannel tc, Message msg, Member member, String... args){ - List members = msg.getMentions().getMembers(); - - if(members.isEmpty()){ - bot.getEmbedUtil().sendError(tc, member, "purr.fun.hug.no_mention"); - return; - } - - if(members.contains(guild.getSelfMember())){ - if(bot.isBeta()){ - tc.sendMessage( - bot.getRandomMsg(guild.getId(), "snuggle.fun.hug.mention_snuggle", member.getAsMention()) - ).queue(); - }else { - tc.sendMessage( - bot.getRandomMsg(guild.getId(), "purr.fun.hug.mention_purr", member.getAsMention()) - ).queue(); - } - msg.addReaction(Emoji.fromUnicode("\u2764")).queue( - null, - e -> logger.warn("Couldn't add a Reaction to a message.") - ); - } - - if(members.contains(member)){ - tc.sendMessage( - bot.getMsg(guild.getId(), "purr.fun.hug.mention_self", member.getAsMention()) - ).queue(); - } - - List targets = members.stream() - .filter(mem -> !mem.equals(guild.getSelfMember())) - .filter(mem -> !mem.equals(member)) - .map(Member::getEffectiveName) - .collect(Collectors.toList()); - - if(targets.isEmpty()) - return; - - tc.sendMessage(bot.getMsg(guild.getId(), "purr.fun.hug.loading")).queue(message -> - bot.getRequestUtil().handleEdit(tc, message, HttpUtil.ImageAPI.HUG, member, targets) - ); - } -} diff --git a/src/main/java/site/purrbot/bot/commands/fun/CmdKiss.java b/src/main/java/site/purrbot/bot/commands/fun/CmdKiss.java deleted file mode 100644 index 03ff8bc0a..000000000 --- a/src/main/java/site/purrbot/bot/commands/fun/CmdKiss.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Copyright 2018 - 2021 Andre601 - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated - * documentation files (the "Software"), to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, - * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or substantial - * portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package site.purrbot.bot.commands.fun; - -import com.github.rainestormee.jdacommand.CommandAttribute; -import com.github.rainestormee.jdacommand.CommandDescription; -import net.dv8tion.jda.api.entities.Guild; -import net.dv8tion.jda.api.entities.Member; -import net.dv8tion.jda.api.entities.Message; -import net.dv8tion.jda.api.entities.TextChannel; -import site.purrbot.bot.PurrBot; -import site.purrbot.bot.commands.Command; -import site.purrbot.bot.constants.IDs; -import site.purrbot.bot.util.HttpUtil; - -import java.util.List; -import java.util.stream.Collectors; - -@CommandDescription( - name = "Kiss", - description = "purr.fun.kiss.description", - triggers = {"kiss", "love", "kissu"}, - attributes = { - @CommandAttribute(key = "category", value = "fun"), - @CommandAttribute(key = "usage", value = "{p}kiss <@user> [@user ...]"), - @CommandAttribute(key = "help", value = "{p}kiss <@user> [@user ...]") - } -) -public class CmdKiss implements Command{ - - private final PurrBot bot; - - public CmdKiss(PurrBot bot){ - this.bot = bot; - } - - @Override - public void run(Guild guild, TextChannel tc, Message msg, Member member, String... args){ - List members = msg.getMentions().getMembers(); - if(members.isEmpty()){ - bot.getEmbedUtil().sendError(tc, member, "purr.fun.kiss.no_mention"); - return; - } - - if(members.contains(guild.getSelfMember())){ - if(bot.isBeta()){ - if(bot.isSpecial(member.getId())){ - tc.sendMessage( - bot.getMsg(guild.getId(), "snuggle.fun.kiss.special_user", member.getAsMention()) - ).queue(); - }else{ - tc.sendMessage( - bot.getRandomMsg(guild.getId(), "snuggle.fun.kiss.mention_snuggle", member.getAsMention()) - ).queue(); - } - }else{ - if(bot.isSpecial(member.getId())){ - tc.sendMessage( - bot.getMsg(guild.getId(), "purr.fun.kiss.special_user", member.getAsMention()) - ).queue(); - }else{ - tc.sendMessage( - bot.getRandomMsg(guild.getId(), "purr.fun.kiss.mention_purr", member.getAsMention()) - ).queue(); - } - } - } - - if(members.contains(member)){ - tc.sendMessage( - bot.getMsg(guild.getId(), "purr.fun.kiss.mention_self", member.getAsMention()) - ).queue(); - } - - List targets = members.stream() - .filter(mem -> !mem.getId().equals(IDs.PURR)) - .filter(mem -> !mem.getId().equals(IDs.SNUGGLE)) - .filter(mem -> !mem.equals(member)) - .map(Member::getEffectiveName) - .collect(Collectors.toList()); - - if(targets.isEmpty()) - return; - - tc.sendMessage(bot.getMsg(guild.getId(), "purr.fun.kiss.loading")).queue(message -> - bot.getRequestUtil().handleEdit(tc, message, HttpUtil.ImageAPI.KISS, member, targets) - ); - } -} diff --git a/src/main/java/site/purrbot/bot/commands/fun/CmdKitsune.java b/src/main/java/site/purrbot/bot/commands/fun/CmdKitsune.java deleted file mode 100644 index d215c307d..000000000 --- a/src/main/java/site/purrbot/bot/commands/fun/CmdKitsune.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright 2018 - 2021 Andre601 - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated - * documentation files (the "Software"), to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, - * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or substantial - * portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package site.purrbot.bot.commands.fun; - -import com.github.rainestormee.jdacommand.CommandAttribute; -import com.github.rainestormee.jdacommand.CommandDescription; -import net.dv8tion.jda.api.entities.Guild; -import net.dv8tion.jda.api.entities.Member; -import net.dv8tion.jda.api.entities.Message; -import net.dv8tion.jda.api.entities.TextChannel; -import site.purrbot.bot.PurrBot; -import site.purrbot.bot.commands.Command; -import site.purrbot.bot.util.HttpUtil; - -@CommandDescription( - name = "Kitsune", - description = "purr.fun.kitsune.description", - triggers = {"kitsune", "foxgirl"}, - attributes = { - @CommandAttribute(key = "category", value = "fun"), - @CommandAttribute(key = "usage", value = "{p}kitsune"), - @CommandAttribute(key = "help", value = "{p}kitsune") - } -) -public class CmdKitsune implements Command{ - - private final PurrBot bot; - - public CmdKitsune(PurrBot bot){ - this.bot = bot; - } - - @Override - public void run(Guild guild, TextChannel tc, Message msg, Member member, String... args){ - tc.sendMessage(bot.getMsg(tc.getGuild().getId(), "purr.fun.kitsune.loading")).queue(message -> - bot.getRequestUtil().handleEdit(tc, message, HttpUtil.ImageAPI.KITSUNE, member) - ); - } -} diff --git a/src/main/java/site/purrbot/bot/commands/fun/CmdLick.java b/src/main/java/site/purrbot/bot/commands/fun/CmdLick.java deleted file mode 100644 index 66a7d9e12..000000000 --- a/src/main/java/site/purrbot/bot/commands/fun/CmdLick.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * Copyright 2018 - 2021 Andre601 - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated - * documentation files (the "Software"), to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, - * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or substantial - * portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package site.purrbot.bot.commands.fun; - -import ch.qos.logback.classic.Logger; -import com.github.rainestormee.jdacommand.CommandAttribute; -import com.github.rainestormee.jdacommand.CommandDescription; -import net.dv8tion.jda.api.entities.Guild; -import net.dv8tion.jda.api.entities.Member; -import net.dv8tion.jda.api.entities.Message; -import net.dv8tion.jda.api.entities.TextChannel; -import net.dv8tion.jda.api.entities.emoji.Emoji; -import org.slf4j.LoggerFactory; -import site.purrbot.bot.PurrBot; -import site.purrbot.bot.commands.Command; -import site.purrbot.bot.util.HttpUtil; - -import java.util.List; -import java.util.stream.Collectors; - -@CommandDescription( - name = "Lick", - description = "purr.fun.lick.description", - triggers = {"lick"}, - attributes = { - @CommandAttribute(key = "category", value = "fun"), - @CommandAttribute(key = "usage", value = "{p}lick <@user> [@user ...]"), - @CommandAttribute(key = "help", value = "{p}lick <@user> [@user ...]") - } -) -public class CmdLick implements Command{ - - private final PurrBot bot; - private final Logger logger = (Logger)LoggerFactory.getLogger("Command - Lick"); - - public CmdLick(PurrBot bot){ - this.bot = bot; - } - - @Override - public void run(Guild guild, TextChannel tc, Message msg, Member member, String... args) { - List members = msg.getMentions().getMembers(); - - if(members.isEmpty()){ - bot.getEmbedUtil().sendError(tc, member, "purr.fun.lick.no_mention"); - return; - } - - if(members.contains(guild.getSelfMember())){ - if(bot.isBeta()){ - tc.sendMessage( - bot.getRandomMsg(guild.getId(), "snuggle.fun.lick.mention_snuggle", member.getAsMention()) - ).queue(); - }else{ - if(bot.isSpecial(member.getId())){ - tc.sendMessage( - bot.getMsg(guild.getId(), "purr.fun.lick.special_user") - ).queue(); - }else { - tc.sendMessage( - bot.getRandomMsg(guild.getId(), "purr.fun.lick.mention_purr", member.getAsMention()) - ).queue(); - } - } - msg.addReaction(Emoji.fromUnicode("\uD83D\uDE33")).queue( - null, - e -> logger.warn("Couldn't add a Reaction to a message.") - ); - } - - if(members.contains(member)){ - tc.sendMessage( - bot.getMsg(guild.getId(), "purr.fun.lick.mention_self", member.getAsMention()) - ).queue(); - } - - List targets = members.stream() - .filter(mem -> !mem.equals(guild.getSelfMember())) - .filter(mem -> !mem.equals(member)) - .map(Member::getEffectiveName) - .collect(Collectors.toList()); - - if(targets.isEmpty()) - return; - - tc.sendMessage(bot.getMsg(guild.getId(), "purr.fun.lick.loading")).queue(message -> - bot.getRequestUtil().handleEdit(tc, message, HttpUtil.ImageAPI.LICK, member, targets) - ); - } -} diff --git a/src/main/java/site/purrbot/bot/commands/fun/CmdNeko.java b/src/main/java/site/purrbot/bot/commands/fun/CmdNeko.java deleted file mode 100644 index ddc1dc3df..000000000 --- a/src/main/java/site/purrbot/bot/commands/fun/CmdNeko.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright 2018 - 2021 Andre601 - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated - * documentation files (the "Software"), to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, - * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or substantial - * portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package site.purrbot.bot.commands.fun; - -import com.github.rainestormee.jdacommand.CommandAttribute; -import com.github.rainestormee.jdacommand.CommandDescription; -import net.dv8tion.jda.api.entities.Guild; -import net.dv8tion.jda.api.entities.Member; -import net.dv8tion.jda.api.entities.Message; -import net.dv8tion.jda.api.entities.TextChannel; -import site.purrbot.bot.PurrBot; -import site.purrbot.bot.commands.Command; -import site.purrbot.bot.util.HttpUtil; - -@CommandDescription( - name = "Neko", - description = "purr.fun.neko.description", - triggers = {"neko", "catgirl"}, - attributes = { - @CommandAttribute(key = "category", value = "fun"), - @CommandAttribute(key = "usage", value = "{p}neko [--gif]"), - @CommandAttribute(key = "help", value = "{p}neko [--gif]") - } -) -public class CmdNeko implements Command{ - - private final PurrBot bot; - - public CmdNeko(PurrBot bot){ - this.bot = bot; - } - - @Override - public void run(Guild guild, TextChannel tc, Message msg, Member member, String... args) { - tc.sendMessage(bot.getMsg(guild.getId(), "purr.fun.neko.loading")).queue(message -> { - if(bot.getMessageUtil().hasArg("gif", args)){ - bot.getRequestUtil().handleEdit(tc, message, HttpUtil.ImageAPI.NEKO_GIF, member); - }else{ - bot.getRequestUtil().handleEdit(tc, message, HttpUtil.ImageAPI.NEKO_IMG, member); - } - }); - } -} diff --git a/src/main/java/site/purrbot/bot/commands/fun/CmdOkami.java b/src/main/java/site/purrbot/bot/commands/fun/CmdOkami.java deleted file mode 100644 index 9aba3355f..000000000 --- a/src/main/java/site/purrbot/bot/commands/fun/CmdOkami.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright 2018 - 2021 Andre601 - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated - * documentation files (the "Software"), to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, - * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or substantial - * portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package site.purrbot.bot.commands.fun; - -import com.github.rainestormee.jdacommand.CommandAttribute; -import com.github.rainestormee.jdacommand.CommandDescription; -import net.dv8tion.jda.api.entities.Guild; -import net.dv8tion.jda.api.entities.Member; -import net.dv8tion.jda.api.entities.Message; -import net.dv8tion.jda.api.entities.TextChannel; -import site.purrbot.bot.PurrBot; -import site.purrbot.bot.commands.Command; -import site.purrbot.bot.util.HttpUtil; - -@CommandDescription( - name = "Okami", - description = "purr.fun.okami.description", - triggers = {"okami", "wolf", "wolfgirl"}, - attributes = { - @CommandAttribute(key = "category", value = "fun"), - @CommandAttribute(key = "usage", value = "{p}okami"), - @CommandAttribute(key = "help", value = "{p}okami") - } -) -public class CmdOkami implements Command{ - private final PurrBot bot; - - public CmdOkami(PurrBot bot){ - this.bot = bot; - } - - @Override - public void run(Guild guild, TextChannel tc, Message msg, Member member, String... args){ - tc.sendMessage(bot.getMsg(guild.getId(), "purr.fun.okami.loading")).queue(message -> - bot.getRequestUtil().handleEdit(tc, message, HttpUtil.ImageAPI.OKAMI, member) - ); - } -} diff --git a/src/main/java/site/purrbot/bot/commands/fun/CmdPat.java b/src/main/java/site/purrbot/bot/commands/fun/CmdPat.java deleted file mode 100644 index 9a2fa63a8..000000000 --- a/src/main/java/site/purrbot/bot/commands/fun/CmdPat.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright 2018 - 2021 Andre601 - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated - * documentation files (the "Software"), to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, - * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or substantial - * portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package site.purrbot.bot.commands.fun; - -import ch.qos.logback.classic.Logger; -import com.github.rainestormee.jdacommand.CommandAttribute; -import com.github.rainestormee.jdacommand.CommandDescription; -import net.dv8tion.jda.api.entities.Guild; -import net.dv8tion.jda.api.entities.Member; -import net.dv8tion.jda.api.entities.Message; -import net.dv8tion.jda.api.entities.TextChannel; -import net.dv8tion.jda.api.entities.emoji.Emoji; -import org.slf4j.LoggerFactory; -import site.purrbot.bot.PurrBot; -import site.purrbot.bot.commands.Command; -import site.purrbot.bot.util.HttpUtil; - -import java.util.List; -import java.util.stream.Collectors; - -@CommandDescription( - name = "Pat", - description = "purr.fun.pat.description", - triggers = {"pat", "patting", "pet", "patto"}, - attributes = { - @CommandAttribute(key = "category", value = "fun"), - @CommandAttribute(key = "usage", value = "{p}pat <@user> [@user ...]"), - @CommandAttribute(key = "help", value = "{p}pat <@user> [@user ...]") - } -) -public class CmdPat implements Command{ - - private final PurrBot bot; - private final Logger logger = (Logger)LoggerFactory.getLogger("Command - Pat"); - - public CmdPat(PurrBot bot){ - this.bot = bot; - } - - @Override - public void run(Guild guild, TextChannel tc, Message msg, Member member, String... args) { - List members = msg.getMentions().getMembers(); - - if(members.isEmpty()){ - bot.getEmbedUtil().sendError(tc, member, "purr.fun.pat.no_mention"); - return; - } - - if(members.contains(guild.getSelfMember())){ - if(bot.isBeta()){ - tc.sendMessage( - bot.getRandomMsg(guild.getId(), "snuggle.fun.pat.mention_snuggle", member.getAsMention()) - ).queue(); - }else{ - tc.sendMessage( - bot.getRandomMsg(guild.getId(), "purr.fun.pat.mention_purr", member.getAsMention()) - ).queue(); - } - msg.addReaction(Emoji.fromUnicode("\u2764")).queue( - null, - e -> logger.warn("Couldn't add a Reaction to a message.") - ); - } - - if(members.contains(member)){ - tc.sendMessage( - bot.getMsg(guild.getId(), "purr.fun.pat.mention_self", member.getAsMention()) - ).queue(); - } - - List targets = members.stream() - .filter(mem -> !mem.equals(guild.getSelfMember())) - .filter(mem -> !mem.equals(member)) - .map(Member::getEffectiveName) - .collect(Collectors.toList()); - - if(targets.isEmpty()) - return; - - tc.sendMessage(bot.getMsg(guild.getId(), "purr.fun.pat.loading")).queue(message -> - bot.getRequestUtil().handleEdit(tc, message, HttpUtil.ImageAPI.PAT, member, targets) - ); - } -} diff --git a/src/main/java/site/purrbot/bot/commands/fun/CmdPoke.java b/src/main/java/site/purrbot/bot/commands/fun/CmdPoke.java deleted file mode 100644 index 75ea4e24f..000000000 --- a/src/main/java/site/purrbot/bot/commands/fun/CmdPoke.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright 2018 - 2021 Andre601 - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated - * documentation files (the "Software"), to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, - * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or substantial - * portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package site.purrbot.bot.commands.fun; - -import ch.qos.logback.classic.Logger; -import com.github.rainestormee.jdacommand.CommandAttribute; -import com.github.rainestormee.jdacommand.CommandDescription; -import net.dv8tion.jda.api.entities.Guild; -import net.dv8tion.jda.api.entities.Member; -import net.dv8tion.jda.api.entities.Message; -import net.dv8tion.jda.api.entities.TextChannel; -import net.dv8tion.jda.api.entities.emoji.Emoji; -import org.slf4j.LoggerFactory; -import site.purrbot.bot.PurrBot; -import site.purrbot.bot.commands.Command; -import site.purrbot.bot.util.HttpUtil; - -import java.util.List; -import java.util.stream.Collectors; - -@CommandDescription( - name = "Poke", - description = "purr.fun.poke.description", - triggers = {"poke", "poking", "boop", "boops"}, - attributes = { - @CommandAttribute(key = "category", value = "fun"), - @CommandAttribute(key = "usage", value = "{p}poke <@user> [@user ...]"), - @CommandAttribute(key = "help", value = "{p}poke <@user> [@user ...]") - } -) -public class CmdPoke implements Command{ - - private final PurrBot bot; - private final Logger logger = (Logger)LoggerFactory.getLogger("Command - Poke"); - - public CmdPoke(PurrBot bot){ - this.bot = bot; - } - - @Override - public void run(Guild guild, TextChannel tc, Message msg, Member member, String... args) { - List members = msg.getMentions().getMembers(); - - if(members.isEmpty()){ - bot.getEmbedUtil().sendError(tc, member, "purr.fun.poke.no_mention"); - return; - } - - if(members.contains(guild.getSelfMember())){ - if(bot.isBeta()){ - tc.sendMessage( - bot.getRandomMsg(guild.getId(), "snuggle.fun.poke.mention_snuggle") - ).queue(); - }else{ - tc.sendMessage( - bot.getRandomMsg(guild.getId(), "purr.fun.poke.mention_purr") - ).queue(); - } - msg.addReaction(Emoji.fromUnicode("\uD83D\uDE16")).queue( - null, - e -> logger.warn("Couldn't add a Reaction to a message.") - ); - } - - if(members.contains(member)){ - tc.sendMessage( - bot.getMsg(guild.getId(), "purr.fun.poke.mention_self", member.getAsMention()) - ).queue(); - } - - List targets = members.stream() - .filter(mem -> !mem.equals(guild.getSelfMember())) - .filter(mem -> !mem.equals(member)) - .map(Member::getEffectiveName) - .collect(Collectors.toList()); - - if(targets.isEmpty()) - return; - - tc.sendMessage(bot.getMsg(guild.getId(), "purr.fun.poke.loading")).queue(message -> - bot.getRequestUtil().handleEdit(tc, message, HttpUtil.ImageAPI.POKE, member, targets) - ); - } -} diff --git a/src/main/java/site/purrbot/bot/commands/fun/CmdSenko.java b/src/main/java/site/purrbot/bot/commands/fun/CmdSenko.java deleted file mode 100644 index 5d94c43e3..000000000 --- a/src/main/java/site/purrbot/bot/commands/fun/CmdSenko.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright 2018 - 2021 Andre601 - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated - * documentation files (the "Software"), to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, - * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or substantial - * portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package site.purrbot.bot.commands.fun; - -import com.github.rainestormee.jdacommand.CommandAttribute; -import com.github.rainestormee.jdacommand.CommandDescription; -import net.dv8tion.jda.api.entities.Guild; -import net.dv8tion.jda.api.entities.Member; -import net.dv8tion.jda.api.entities.Message; -import net.dv8tion.jda.api.entities.TextChannel; -import site.purrbot.bot.PurrBot; -import site.purrbot.bot.commands.Command; -import site.purrbot.bot.util.HttpUtil; - -@CommandDescription( - name = "Senko", - description = "purr.fun.senko.description", - triggers = {"senko", "senko-san"}, - attributes = { - @CommandAttribute(key = "category", value = "fun"), - @CommandAttribute(key = "usage", value = "{p}senko"), - @CommandAttribute(key = "help", value = "{p}senko") - } -) -public class CmdSenko implements Command{ - - private final PurrBot bot; - - public CmdSenko(PurrBot bot){ - this.bot = bot; - } - - @Override - public void run(Guild guild, TextChannel tc, Message msg, Member member, String... args){ - tc.sendMessage(bot.getMsg(guild.getId(), "purr.fun.senko.loading")).queue(message -> - bot.getRequestUtil().handleEdit(tc, message, HttpUtil.ImageAPI.SENKO, member) - ); - } -} diff --git a/src/main/java/site/purrbot/bot/commands/fun/CmdShip.java b/src/main/java/site/purrbot/bot/commands/fun/CmdShip.java deleted file mode 100644 index 703738e33..000000000 --- a/src/main/java/site/purrbot/bot/commands/fun/CmdShip.java +++ /dev/null @@ -1,224 +0,0 @@ -/* - * Copyright 2018 - 2021 Andre601 - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated - * documentation files (the "Software"), to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, - * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or substantial - * portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package site.purrbot.bot.commands.fun; - -import com.github.benmanes.caffeine.cache.Cache; -import com.github.benmanes.caffeine.cache.Caffeine; -import com.github.rainestormee.jdacommand.CommandAttribute; -import com.github.rainestormee.jdacommand.CommandDescription; -import net.dv8tion.jda.api.MessageBuilder; -import net.dv8tion.jda.api.Permission; -import net.dv8tion.jda.api.entities.Guild; -import net.dv8tion.jda.api.entities.Member; -import net.dv8tion.jda.api.entities.Message; -import net.dv8tion.jda.api.entities.TextChannel; -import net.dv8tion.jda.api.entities.emoji.Emoji; -import site.purrbot.bot.PurrBot; -import site.purrbot.bot.commands.Command; -import site.purrbot.bot.constants.IDs; - -import java.util.List; -import java.util.Random; -import java.util.concurrent.TimeUnit; - -@CommandDescription( - name = "Ship", - description = "purr.fun.ship.description", - triggers = {"ship", "shipping"}, - attributes = { - @CommandAttribute(key = "category", value = "fun"), - @CommandAttribute(key = "usage", value = "{p}ship <@user> [@user]"), - @CommandAttribute(key = "help", value = "{p}ship <@user> [@user]") - } -) -public class CmdShip implements Command{ - - private final PurrBot bot; - private final Random random = new Random(); - - Cache cache = Caffeine.newBuilder() - .expireAfterWrite(2, TimeUnit.MINUTES) - .build(); - - public CmdShip(PurrBot bot){ - this.bot = bot; - } - - @Override - public void run(Guild guild, TextChannel tc, Message msg, Member member, String... args){ - Member member1; - Member member2; - - List members = msg.getMentions().getMembers(); - - if (members.isEmpty()){ - bot.getEmbedUtil().sendError(tc, member, "purr.fun.ship.no_mention"); - return; - } - - - if(members.size() > 1){ - member1 = members.get(0); - member2 = members.get(1); - }else{ - member1 = member; - member2 = members.get(0); - } - - if(member1 == null || member2 == null) - return; - - if(member1.getId().equals(IDs.PURR) || member2.getId().equals(IDs.PURR)){ - if(bot.isBeta()){ - if((bot.isSpecial(member1.getId()) || bot.isSpecial(member2.getId())) && bot.isSpecial(member.getId())){ - tc.sendMessage( - bot.getMsg(guild.getId(), "snuggle.fun.ship.special_user", member.getAsMention()) - ).queue(); - return; - } - tc.sendMessage( - bot.getMsg(guild.getId(), "snuggle.fun.ship.mention_purr", member.getAsMention()) - ).queue(); - }else{ - if((bot.isSpecial(member1.getId()) || bot.isSpecial(member2.getId())) && bot.isSpecial(member.getId())){ - byte[] img = bot.getImageUtil().getShipImg(member1, member2, 100); - - if(img != null && guild.getSelfMember().hasPermission(tc, Permission.MESSAGE_ATTACH_FILES)){ - tc.sendMessage( - bot.getMsg(guild.getId(), "purr.fun.ship.special_user", member.getAsMention()) - ).addFile(img, String.format( - "love_%s_%s.png", - member1.getId(), - member2.getId() - )).queue(); - return; - } - - tc.sendMessage( - bot.getMsg(guild.getId(), "purr.fun.ship.special_user", member.getAsMention()) - ).queue(); - return; - } - tc.sendMessage( - bot.getMsg(guild.getId(), "purr.fun.ship.mention_purr", member.getAsMention()) - ).queue(); - } - msg.addReaction(Emoji.fromUnicode("\uD83D\uDE33")).queue(); - - return; - } - - if(member1.getId().equals(IDs.SNUGGLE) || member2.getId().equals(IDs.SNUGGLE)){ - if(bot.isBeta()){ - tc.sendMessage( - bot.getMsg(guild.getId(), "snuggle.fun.ship.mention_snuggle", member.getAsMention()) - ).queue(); - }else{ - tc.sendMessage( - bot.getMsg(guild.getId(), "purr.fun.ship.mention_snuggle", member.getAsMention()) - ).queue(); - } - return; - } - - if(member1.equals(member) && member2.equals(member)){ - tc.sendMessage( - bot.getMsg(guild.getId(), "purr.fun.ship.mention_self", member.getAsMention()) - ).queue(); - return; - } - - if(member1.getUser().isBot() || member2.getUser().isBot()){ - bot.getEmbedUtil().sendError(tc, member, "purr.fun.ship.target_bot"); - return; - } - - Integer result = cache.get(String.format("%s:%s", member1.getId(), member2.getId()), k -> random.nextInt(101)); - if(result == null){ - result = random.nextInt(101); - cache.put(String.format("%s:%s", member1.getId(), member2.getId()), result); - } - - byte[] image; - - image = bot.getImageUtil().getShipImg(member1, member2, result); - - if(image == null || !guild.getSelfMember().hasPermission(tc, Permission.MESSAGE_ATTACH_FILES)){ - Message message = new MessageBuilder(String.format( - "`%d%%` | %s", - result, - getMessage(result, guild.getId()) - )).build(); - - tc.sendMessage(message).queue(); - return; - } - - tc.sendMessage(getMessage(result, guild.getId())).addFile(image, String.format( - "love_%s_%s.png", - member1.getId(), - member2.getId() - )).queue(); - - } - - private String getMessage(int chance, String id){ - if(chance == 100){ - return bot.getMsg(id, "purr.fun.ship.results.100"); - }else - if((chance <= 99) && (chance > 90)){ - return bot.getMsg(id, "purr.fun.ship.results.91_99"); - }else - if((chance <= 90) && (chance > 80)){ - return bot.getMsg(id, "purr.fun.ship.results.81_90"); - }else - if((chance <= 80) && (chance > 70)){ - return bot.getMsg(id, "purr.fun.ship.results.71_80"); - }else - if(chance == 70){ - return bot.getMsg(id, "purr.fun.ship.results.61_70"); - }else - if(chance == 69){ - return bot.getMsg(id, "purr.fun.ship.results.69"); - }else - if((chance <= 68) && (chance > 60)){ - return bot.getMsg(id, "purr.fun.ship.results.61_70"); - }else - if((chance <= 60) && (chance > 50)){ - return bot.getMsg(id, "purr.fun.ship.results.51_60"); - }else - if((chance <= 50) && (chance > 40)) { - return bot.getMsg(id, "purr.fun.ship.results.41_50"); - }else - if((chance <= 40) && (chance > 30)) { - return bot.getMsg(id, "purr.fun.ship.results.31_40"); - }else - if((chance <= 30) && (chance > 20)) { - return bot.getMsg(id, "purr.fun.ship.results.21_30"); - }else - if((chance <= 20) && (chance > 10)) { - return bot.getMsg(id, "purr.fun.ship.results.11_20"); - }else - if((chance <= 10) && (chance > 0)) { - return bot.getMsg(id, "purr.fun.ship.results.1_10"); - }else{ - return bot.getMsg(id, "purr.fun.ship.results.0"); - } - } -} diff --git a/src/main/java/site/purrbot/bot/commands/fun/CmdSlap.java b/src/main/java/site/purrbot/bot/commands/fun/CmdSlap.java deleted file mode 100644 index 5b44da865..000000000 --- a/src/main/java/site/purrbot/bot/commands/fun/CmdSlap.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright 2018 - 2021 Andre601 - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated - * documentation files (the "Software"), to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, - * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or substantial - * portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package site.purrbot.bot.commands.fun; - -import ch.qos.logback.classic.Logger; -import com.github.rainestormee.jdacommand.CommandAttribute; -import com.github.rainestormee.jdacommand.CommandDescription; -import net.dv8tion.jda.api.entities.Guild; -import net.dv8tion.jda.api.entities.Member; -import net.dv8tion.jda.api.entities.Message; -import net.dv8tion.jda.api.entities.TextChannel; -import net.dv8tion.jda.api.entities.emoji.Emoji; -import org.slf4j.LoggerFactory; -import site.purrbot.bot.PurrBot; -import site.purrbot.bot.commands.Command; -import site.purrbot.bot.util.HttpUtil; - -import java.util.List; -import java.util.stream.Collectors; - -@CommandDescription( - name = "Slap", - description = "purr.fun.slap.description", - triggers = {"slap"}, - attributes = { - @CommandAttribute(key = "category", value = "fun"), - @CommandAttribute(key = "usage", value = "{p}slap <@user> [@user ...]"), - @CommandAttribute(key = "help", value = "{p}slap <@user> [@user ...]") - } -) -public class CmdSlap implements Command{ - - private final PurrBot bot; - private final Logger logger = (Logger)LoggerFactory.getLogger("Command - Slap"); - - public CmdSlap(PurrBot bot){ - this.bot = bot; - } - - @Override - public void run(Guild guild, TextChannel tc, Message msg, Member member, String... args) { - List members = msg.getMentions().getMembers(); - - if(members.isEmpty()){ - bot.getEmbedUtil().sendError(tc, member, "purr.fun.slap.no_mention"); - return; - } - - if(members.contains(guild.getSelfMember())){ - if(bot.isBeta()){ - tc.sendMessage( - bot.getRandomMsg(guild.getId(), "snuggle.fun.slap.mention_snuggle", member.getAsMention()) - ).queue(); - }else{ - tc.sendMessage( - bot.getRandomMsg(guild.getId(), "purr.fun.slap.mention_purr", member.getAsMention()) - ).queue(); - } - msg.addReaction(Emoji.fromUnicode("\uD83D\uDE2D")).queue( - null, - e -> logger.warn("Couldn't add a Reaction to a message.") - ); - } - - if(members.contains(member)){ - tc.sendMessage( - bot.getMsg(guild.getId(), "purr.fun.slap.mention_self", member.getAsMention()) - ).queue(); - } - - List targets = members.stream() - .filter(mem -> !mem.equals(guild.getSelfMember())) - .filter(mem -> !mem.equals(member)) - .map(Member::getEffectiveName) - .collect(Collectors.toList()); - - if(targets.isEmpty()) - return; - - tc.sendMessage(bot.getMsg(guild.getId(), "purr.fun.slap.loading")).queue(message -> - bot.getRequestUtil().handleEdit(tc, message, HttpUtil.ImageAPI.SLAP, member, targets) - ); - } -} diff --git a/src/main/java/site/purrbot/bot/commands/fun/CmdSmile.java b/src/main/java/site/purrbot/bot/commands/fun/CmdSmile.java deleted file mode 100644 index 2595ead02..000000000 --- a/src/main/java/site/purrbot/bot/commands/fun/CmdSmile.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright 2018 - 2021 Andre601 - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated - * documentation files (the "Software"), to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, - * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or substantial - * portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package site.purrbot.bot.commands.fun; - -import com.github.rainestormee.jdacommand.CommandAttribute; -import com.github.rainestormee.jdacommand.CommandDescription; -import net.dv8tion.jda.api.entities.Guild; -import net.dv8tion.jda.api.entities.Member; -import net.dv8tion.jda.api.entities.Message; -import net.dv8tion.jda.api.entities.TextChannel; -import site.purrbot.bot.PurrBot; -import site.purrbot.bot.commands.Command; -import site.purrbot.bot.util.HttpUtil; - -@CommandDescription( - name = "Smile", - description = "purr.fun.smile.description", - triggers = {"smile", "grinning", "grin"}, - attributes = { - @CommandAttribute(key = "category", value = "fun"), - @CommandAttribute(key = "usage", value = "{p}smile"), - @CommandAttribute(key = "help", value = "{p}smile") - } -) -public class CmdSmile implements Command{ - - private final PurrBot bot; - - public CmdSmile(PurrBot bot){ - this.bot = bot; - } - - @Override - public void run(Guild guild, TextChannel tc, Message msg, Member member, String... args){ - tc.sendMessage(bot.getMsg(guild.getId(), "purr.fun.smile.loading")).queue(message -> - bot.getRequestUtil().handleEdit(tc, message, HttpUtil.ImageAPI.SMILE, member) - ); - } -} diff --git a/src/main/java/site/purrbot/bot/commands/fun/CmdTail.java b/src/main/java/site/purrbot/bot/commands/fun/CmdTail.java deleted file mode 100644 index 75f5b3f89..000000000 --- a/src/main/java/site/purrbot/bot/commands/fun/CmdTail.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright 2018 - 2021 Andre601 - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated - * documentation files (the "Software"), to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, - * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or substantial - * portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package site.purrbot.bot.commands.fun; - -import com.github.rainestormee.jdacommand.CommandAttribute; -import com.github.rainestormee.jdacommand.CommandDescription; -import net.dv8tion.jda.api.entities.Guild; -import net.dv8tion.jda.api.entities.Member; -import net.dv8tion.jda.api.entities.Message; -import net.dv8tion.jda.api.entities.TextChannel; -import site.purrbot.bot.PurrBot; -import site.purrbot.bot.commands.Command; -import site.purrbot.bot.util.HttpUtil; - -@CommandDescription( - name = "Tail", - description = "purr.fun.tail.description", - triggers = {"tail", "wag", "wagging"}, - attributes = { - @CommandAttribute(key = "category", value = "fun"), - @CommandAttribute(key = "usage", value = "{p}tail"), - @CommandAttribute(key = "help", value = "{p}tail") - } -) -public class CmdTail implements Command{ - - private final PurrBot bot; - - public CmdTail(PurrBot bot){ - this.bot = bot; - } - - @Override - public void run(Guild guild, TextChannel tc, Message msg, Member member, String... args){ - tc.sendMessage(bot.getMsg(guild.getId(), "purr.fun.tail.loading")).queue(message -> - bot.getRequestUtil().handleEdit(tc, message, HttpUtil.ImageAPI.TAIL, member) - ); - } -} diff --git a/src/main/java/site/purrbot/bot/commands/fun/CmdTickle.java b/src/main/java/site/purrbot/bot/commands/fun/CmdTickle.java deleted file mode 100644 index 49e4a0c06..000000000 --- a/src/main/java/site/purrbot/bot/commands/fun/CmdTickle.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright 2018 - 2021 Andre601 - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated - * documentation files (the "Software"), to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, - * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or substantial - * portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package site.purrbot.bot.commands.fun; - -import ch.qos.logback.classic.Logger; -import com.github.rainestormee.jdacommand.CommandAttribute; -import com.github.rainestormee.jdacommand.CommandDescription; -import net.dv8tion.jda.api.entities.Guild; -import net.dv8tion.jda.api.entities.Member; -import net.dv8tion.jda.api.entities.Message; -import net.dv8tion.jda.api.entities.TextChannel; -import net.dv8tion.jda.api.entities.emoji.Emoji; -import org.slf4j.LoggerFactory; -import site.purrbot.bot.PurrBot; -import site.purrbot.bot.commands.Command; -import site.purrbot.bot.util.HttpUtil; - -import java.util.List; -import java.util.stream.Collectors; - -@CommandDescription( - name = "Tickle", - description = "purr.fun.tickle.description", - triggers = {"tickle"}, - attributes = { - @CommandAttribute(key = "category", value = "fun"), - @CommandAttribute(key = "usage", value = "{p}tickle <@user> [@user ...]"), - @CommandAttribute(key = "help", value = "{p}tickle <@user> [@user ...]") - } -) -public class CmdTickle implements Command{ - - private final PurrBot bot; - private final Logger logger = (Logger)LoggerFactory.getLogger("Command - Tickle"); - - public CmdTickle(PurrBot bot){ - this.bot = bot; - } - - @Override - public void run(Guild guild, TextChannel tc, Message msg, Member member, String... args) { - List members = msg.getMentions().getMembers(); - - if(members.isEmpty()){ - bot.getEmbedUtil().sendError(tc, member, "purr.fun.tickle.no_mention"); - return; - } - - if(members.contains(guild.getSelfMember())){ - if(bot.isBeta()){ - tc.sendMessage( - bot.getRandomMsg(guild.getId(), "snuggle.fun.tickle.mention_snuggle") - ).queue(); - }else { - tc.sendMessage( - bot.getRandomMsg(guild.getId(), "purr.fun.tickle.mention_purr") - ).queue(); - } - msg.addReaction(Emoji.fromUnicode("\uD83D\uDE02")).queue( - null, - e -> logger.warn("Couldn't add a Reaction to a message.") - ); - } - - if(members.contains(member)){ - tc.sendMessage( - bot.getMsg(guild.getId(), "purr.fun.tickle.mention_self", member.getAsMention()) - ).queue(); - } - - List targets = members.stream() - .filter(mem -> !mem.equals(guild.getSelfMember())) - .filter(mem -> !mem.equals(member)) - .map(Member::getEffectiveName) - .collect(Collectors.toList()); - - if(targets.isEmpty()) - return; - - tc.sendMessage(bot.getMsg(guild.getId(), "purr.fun.tickle.loading")).queue(message -> - bot.getRequestUtil().handleEdit(tc, message, HttpUtil.ImageAPI.TICKLE, member, targets) - ); - } -} diff --git a/src/main/java/site/purrbot/bot/commands/guild/CmdLanguage.java b/src/main/java/site/purrbot/bot/commands/guild/CmdLanguage.java deleted file mode 100644 index add6af850..000000000 --- a/src/main/java/site/purrbot/bot/commands/guild/CmdLanguage.java +++ /dev/null @@ -1,133 +0,0 @@ -/* - * Copyright 2018 - 2021 Andre601 - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated - * documentation files (the "Software"), to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, - * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or substantial - * portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package site.purrbot.bot.commands.guild; - -import com.github.rainestormee.jdacommand.CommandAttribute; -import com.github.rainestormee.jdacommand.CommandDescription; -import net.dv8tion.jda.api.entities.*; -import site.purrbot.bot.PurrBot; -import site.purrbot.bot.commands.Command; -import site.purrbot.bot.constants.Links; -import site.purrbot.bot.util.file.lang.LangUtils; - -import java.util.Collections; -import java.util.List; - -@CommandDescription( - name = "Language", - description = "purr.guild.language.description", - triggers = {"language", "lang"}, - attributes = { - @CommandAttribute(key = "manage_server"), - @CommandAttribute(key = "category", value = "guild"), - @CommandAttribute(key = "usage", value = - "{p}language\n" + - "{p}language set \n" + - "{p}language reset" - ), - @CommandAttribute(key = "help", value = "{p}language [set |reset]") - } -) -public class CmdLanguage implements Command{ - private final PurrBot bot; - - public CmdLanguage(PurrBot bot){ - this.bot = bot; - } - - @Override - public void run(Guild guild, TextChannel tc, Message msg, Member member, String... args){ - if(args.length < 1){ - MessageEmbed embed = bot.getEmbedUtil().getEmbed(member) - .setDescription( - bot.getMsg(guild.getId(), "purr.guild.language.embed.description") - .replace("{flag}", LangUtils.Language.getEmote(bot.getLanguage(guild.getId()))) - .replace("{language}", bot.getMsg(guild.getId(), "misc.language")) - ) - .addField( - bot.getMsg(guild.getId(), "purr.guild.language.embed.available_lang_title"), - getLanguages(), - false - ) - .addField( - bot.getMsg(guild.getId(), "purr.guild.language.embed.translators_title"), - bot.getMsg(guild.getId(), "purr.guild.language.embed.translators_value") - .replace("{link}", Links.TRANSLATORS), - false - ) - .build(); - - tc.sendMessageEmbeds(embed).queue(); - }else{ - if(args[0].equalsIgnoreCase("reset")){ - bot.setLanguage(guild.getId(), "en"); - - MessageEmbed embed = bot.getEmbedUtil().getEmbed(member) - .setColor(0x00FF00) - .setDescription("Language reset back to `English (en)`!") - .build(); - - tc.sendMessageEmbeds(embed).queue(); - }else - if(args[0].equalsIgnoreCase("set")){ - if(args.length < 2){ - bot.getEmbedUtil().sendError(tc, member, "purr.guild.language.few_args"); - return; - } - - if(!getLangList().contains(args[1].toLowerCase())){ - bot.getEmbedUtil().sendError(tc, member, "purr.guild.language.invalid_lang"); - return; - } - - bot.setLanguage(guild.getId(), args[1].toLowerCase()); - - MessageEmbed embed = bot.getEmbedUtil().getEmbed(member) - .setColor(0x00FF00) - .setDescription( - bot.getMsg(guild.getId(), "purr.guild.language.language_set") - ) - .build(); - - tc.sendMessageEmbeds(embed).queue(); - }else{ - bot.getEmbedUtil().sendError(tc, member, "purr.guild.language.invalid_args"); - } - } - } - - private List getLangList(){ - return bot.getFileManager().getLanguages(); - } - - private String getLanguages(){ - List langs = getLangList(); - Collections.sort(langs); - - StringBuilder builder = new StringBuilder(); - for(String language : langs){ - if(builder.length() > 1) - builder.append("\n"); - - builder.append(LangUtils.Language.getString(language)); - } - - return builder.toString(); - } -} diff --git a/src/main/java/site/purrbot/bot/commands/guild/CmdPrefix.java b/src/main/java/site/purrbot/bot/commands/guild/CmdPrefix.java deleted file mode 100644 index c3f9aa1d7..000000000 --- a/src/main/java/site/purrbot/bot/commands/guild/CmdPrefix.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright 2018 - 2021 Andre601 - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated - * documentation files (the "Software"), to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, - * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or substantial - * portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package site.purrbot.bot.commands.guild; - -import com.github.rainestormee.jdacommand.CommandAttribute; -import com.github.rainestormee.jdacommand.CommandDescription; -import net.dv8tion.jda.api.entities.*; -import site.purrbot.bot.PurrBot; -import site.purrbot.bot.commands.Command; - -@CommandDescription( - name = "Prefix", - description = "purr.guild.prefix.description", - triggers = {"prefix"}, - attributes = { - @CommandAttribute(key = "manage_server"), - @CommandAttribute(key = "category", value = "guild"), - @CommandAttribute(key = "usage", value = - "{p}prefix set \n" + - "{p}prefix reset" - ), - @CommandAttribute(key = "help", value = "{p}prefix |reset>") - } -) -public class CmdPrefix implements Command{ - - private final PurrBot bot; - - public CmdPrefix(PurrBot bot){ - this.bot = bot; - } - - @Override - public void run(Guild guild, TextChannel tc, Message msg, Member member, String... args){ - if(args.length < 1){ - bot.getEmbedUtil().sendError(tc, member, "purr.guild.prefix.few_args"); - return; - } - - if(args[0].equalsIgnoreCase("reset")){ - resetPrefix(tc, member); - }else - if(args[0].equalsIgnoreCase("set")){ - if(args.length == 1){ - bot.getEmbedUtil().sendError(tc, member, "purr.guild.prefix.no_prefix"); - }else{ - setPrefix(tc, member, args[1].toLowerCase()); - } - }else{ - bot.getEmbedUtil().sendError(tc, member, "purr.guild.prefix.invalid_args"); - } - } - - private void setPrefix(TextChannel tc, Member member, String prefix){ - bot.setPrefix(member.getGuild().getId(), prefix); - - MessageEmbed embed = bot.getEmbedUtil().getEmbed(member) - .setColor(0x00FF00) - .setDescription( - bot.getMsg(member.getGuild().getId(), "purr.guild.prefix.set") - ) - .build(); - - tc.sendMessageEmbeds(embed).queue(); - } - - private void resetPrefix(TextChannel tc, Member member){ - bot.setPrefix(member.getGuild().getId(), bot.isBeta() ? "p.." : "p."); - - MessageEmbed embed = bot.getEmbedUtil().getEmbed(member) - .setColor(0x00FF00) - .setDescription( - bot.getMsg(member.getGuild().getId(), "purr.guild.prefix.reset") - ) - .build(); - - tc.sendMessageEmbeds(embed).queue(); - } -} diff --git a/src/main/java/site/purrbot/bot/commands/guild/CmdWelcome.java b/src/main/java/site/purrbot/bot/commands/guild/CmdWelcome.java deleted file mode 100644 index e9e5e3201..000000000 --- a/src/main/java/site/purrbot/bot/commands/guild/CmdWelcome.java +++ /dev/null @@ -1,510 +0,0 @@ -/* - * Copyright 2018 - 2021 Andre601 - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated - * documentation files (the "Software"), to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, - * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or substantial - * portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package site.purrbot.bot.commands.guild; - -import com.github.rainestormee.jdacommand.CommandAttribute; -import com.github.rainestormee.jdacommand.CommandDescription; -import net.dv8tion.jda.api.EmbedBuilder; -import net.dv8tion.jda.api.Permission; -import net.dv8tion.jda.api.entities.*; -import site.purrbot.bot.PurrBot; -import site.purrbot.bot.commands.Command; - -import java.io.InputStream; -import java.util.Locale; - -@CommandDescription( - name = "Welcome", - description = "purr.guild.welcome.description", - triggers = {"welcome"}, - attributes = { - @CommandAttribute(key = "manage_server"), - @CommandAttribute(key = "category", value = "guild"), - @CommandAttribute(key = "usage", value = - "{p}welcome\n" + - "{p}welcome bg set \n" + - "{p}welcome bg reset\n" + - "{p}welcome channel set <#channel>\n" + - "{p}welcome channel reset\n" + - "{p}welcome color set \n" + - "{p}welcome color reset\n" + - "{p}welcome icon set \n" + - "{p}welcome icon reset\n" + - "{p}welcome msg set \n" + - "{p}welcome msg reset\n" + - "{p}welcome test" - ), - @CommandAttribute(key = "help", value = "{p}welcome [options]") - } -) -public class CmdWelcome implements Command{ - - private final PurrBot bot; - - public CmdWelcome(PurrBot bot){ - this.bot = bot; - } - - @Override - public void run(Guild guild, TextChannel tc, Message msg, Member member, String... args){ - if(args.length < 1){ - tc.sendTyping().queue(v -> { - InputStream image = bot.getImageUtil().getWelcomeImg( - msg.getMember(), - bot.getWelcomeIcon(guild.getId()), - bot.getWelcomeBg(guild.getId()), - bot.getWelcomeColor(guild.getId()) - ); - - welcomeSettings(tc, member, image); - }); - return; - } - - switch (args[0].toLowerCase()){ - case "bg": - if(args.length < 2){ - bot.getEmbedUtil().sendError(tc, member, "purr.guild.welcome.few_args"); - return; - } - if(args[1].equalsIgnoreCase("reset")){ - reset(tc, member, Type.BACKGROUND); - }else - if(args[1].equalsIgnoreCase("set")){ - if(args.length < 3){ - bot.getEmbedUtil().sendError(tc, member, "purr.guild.welcome.no_bg"); - return; - } - String bg = args[2].toLowerCase(Locale.ROOT); - if((bg.startsWith("https://") || bg.startsWith("http://")) && !bot.getCheckUtil().isPatreon(tc, guild.getOwnerId())){ - bot.getEmbedUtil().sendError(tc, member, "purr.guild.welcome.no_patreon"); - return; - } - if(bg.equalsIgnoreCase("booster") && !bot.getCheckUtil().isBooster(tc, guild.getOwnerId())){ - bot.getEmbedUtil().sendError(tc, member, "purr.guild.welcome.no_booster"); - return; - } - if(!bot.getWelcomeBg().contains(bg)){ - if(bg.startsWith("https://") || bg.startsWith("http://")){ - if(!bot.getImageUtil().isValidImage(bg, 2000, 350)){ - bot.getEmbedUtil().sendError(tc, member, "purr.guild.welcome.invalid_bg_width"); - return; - } - }else{ - MessageEmbed embed = bot.getEmbedUtil().getErrorEmbed(member) - .setDescription( - bot.getMsg(guild.getId(), "purr.guild.welcome.invalid_bg") - .replace("{background}", bg) - ).build(); - - tc.sendMessageEmbeds(embed).queue(); - return; - } - } - - update(tc, member, Type.BACKGROUND, bg); - }else{ - bot.getEmbedUtil().sendError(tc, member, "purr.guild.welcome.invalid_args"); - } - break; - - case "channel": - if(args.length < 2){ - bot.getEmbedUtil().sendError(tc, member, "purr.guild.welcome.few_args"); - return; - } - if(args[1].equalsIgnoreCase("reset")){ - reset(tc, member, Type.CHANNEL); - }else - if(args[1].equalsIgnoreCase("set")){ - if(msg.getMentions().getChannels().isEmpty()){ - bot.getEmbedUtil().sendError(tc, member, "purr.guild.welcome.no_channel"); - return; - } - if(msg.getMentions().getChannels().get(0) == null){ - bot.getEmbedUtil().sendError(tc, member, "purr.guild.welcome.invalid_channel"); - return; - } - update(tc, member, Type.CHANNEL, msg.getMentions().getChannels().get(0).getId()); - }else{ - bot.getEmbedUtil().sendError(tc, member, "purr.guild.welcome.invalid_args"); - } - break; - - case "color": - if(args.length < 2){ - bot.getEmbedUtil().sendError(tc, member, "purr.guild.welcome.few_args"); - return; - } - if(args[1].equalsIgnoreCase("reset")){ - reset(tc, member, Type.COLOR); - }else - if(args[1].equalsIgnoreCase("set")){ - if(args.length < 3){ - bot.getEmbedUtil().sendError(tc, member, "purr.guild.welcome.no_color"); - return; - } - - if(bot.getMessageUtil().getColor(args[2].toLowerCase()) == null){ - bot.getEmbedUtil().sendError(tc, member, "purr.guild.welcome.invalid_color"); - return; - } - - update(tc, member, Type.COLOR, args[2].toLowerCase()); - }else{ - bot.getEmbedUtil().sendError(tc, member, "purr.guild.welcome.invalid_args"); - } - break; - - case "icon": - if(args.length < 2){ - bot.getEmbedUtil().sendError(tc, member, "purr.guild.welcome.few_args"); - return; - } - if(args[1].equalsIgnoreCase("reset")){ - reset(tc, member, Type.ICON); - }else - if(args[1].equalsIgnoreCase("set")){ - if(args.length < 3){ - bot.getEmbedUtil().sendError(tc, member, "purr.guild.welcome.no_icon"); - return; - } - String icon = args[2].toLowerCase(Locale.ROOT); - if((icon.startsWith("https://") || icon.startsWith("http://")) && !bot.getCheckUtil().isPatreon(tc, member.getId())){ - bot.getEmbedUtil().sendError(tc, member, "purr.guild.welcome.no_patreon"); - return; - } - if(icon.equalsIgnoreCase("booster") && !bot.getCheckUtil().isBooster(tc, member.getId())){ - bot.getEmbedUtil().sendError(tc, member, "purr.guild.welcome.no_booster"); - return; - } - if(!bot.getWelcomeIcon().contains(icon)){ - if(icon.startsWith("https://") || icon.startsWith("http://")){ - if(!bot.getImageUtil().isValidImage(icon, 320, 320)){ - bot.getEmbedUtil().sendError(tc, member, "purr.guild.welcome.invalid_icon_width"); - return; - } - }else{ - MessageEmbed embed = bot.getEmbedUtil().getErrorEmbed(member) - .setDescription( - bot.getMsg(guild.getId(), "purr.guild.welcome.invalid_icon") - .replace("{icon}", icon) - ).build(); - - tc.sendMessageEmbeds(embed).queue(); - return; - } - } - - update(tc, member, Type.ICON, icon); - }else{ - bot.getEmbedUtil().sendError(tc, member, "purr.guild.welcome.invalid_args"); - } - break; - - case "msg": - if(args.length == 1){ - String roleId = member.getRoles().size() >= 1 ? member.getRoles().get(0).getId() : guild.getPublicRole().getId(); - - MessageEmbed embed = bot.getEmbedUtil().getEmbed(member) - .addField( - bot.getMsg(guild.getId(), "purr.guild.welcome.placeholders.message_title"), - getMsg(bot.getWelcomeMsg(guild.getId())), - false - ) - .addField( - bot.getMsg(guild.getId(), "purr.guild.welcome.placeholders.placeholders_title"), - "`{count}`\n" + - "`{members}`\n" + - "\n" + - "`{count_formatted}`\n" + - "`{members_formatted}`\n" + - "\n" + - "`{guild}`\n" + - "`{server}`\n" + - "\n" + - "`{mention}`\n" + - "\n" + - "`{name}`\n" + - "`{username}`\n" + - "\n" + - "`{c_mention:}`\n" + - "`{c_name:}`\n" + - "\n" + - "`{r_mention:}`\n" + - "`{r_name:}`\n" + - "\n" + - "`{tag}`", - true - ) - .addField( - bot.getMsg(guild.getId(), "purr.guild.welcome.placeholders.result_title"), - bot.getMessageUtil().formatPlaceholders(String.format( - "{count}\n" + - "{members}\n" + - "\n" + - "{count_formatted}\n" + - "{members_formatted}\n" + - "\n" + - "{guild}\n" + - "{server}\n" + - "\n" + - "{mention}\n" + - "\n" + - "{name}\n" + - "{username}\n" + - "\n" + - "{c_mention:%s}\n" + - "{c_name:%s}\n" + - "\n" + - "{r_mention:%s}\n" + - "{r_name:%s}\n" + - "\n" + - "{tag}", - tc.getId(), - tc.getId(), - roleId, - roleId - ), member), - true - ) - .addField( - bot.getMsg(guild.getId(), "purr.guild.welcome.placeholders.note_title"), - bot.getMsg(guild.getId(), "purr.guild.welcome.placeholders.note_value"), - false - ) - .build(); - - tc.sendMessageEmbeds(embed).queue(); - return; - } - if(args[1].equalsIgnoreCase("reset")){ - reset(tc, member, Type.MESSAGE); - }else - if(args[1].equalsIgnoreCase("set")){ - if(args.length < 3){ - bot.getEmbedUtil().sendError(tc, member, "purr.guild.welcome.no_msg"); - return; - } - update(tc, member, Type.MESSAGE, args[2]); - } - break; - - case "test": - tc.sendTyping().queue(v -> { - InputStream image = bot.getImageUtil().getWelcomeImg( - member, - bot.getWelcomeIcon(guild.getId()), - bot.getWelcomeBg(guild.getId()), - bot.getWelcomeColor(guild.getId()) - ); - - bot.getMessageUtil().sendWelcomeMsg(tc, bot.getWelcomeMsg(guild.getId()), member, image); - }); - break; - - default: - tc.sendTyping().queue(v -> { - InputStream image = bot.getImageUtil().getWelcomeImg( - member, - bot.getWelcomeIcon(guild.getId()), - bot.getWelcomeBg(guild.getId()), - bot.getWelcomeColor(guild.getId()) - ); - - welcomeSettings(tc, member, image); - }); - } - } - - private String getMsg(String msg){ - return String.format( - "```md\n" + - "%s\n" + - "```", - msg.length() > 1000 ? msg.substring(0, 990) + "..." : msg - ); - } - - private void welcomeSettings(TextChannel tc, Member member, InputStream file){ - Guild guild = tc.getGuild(); - String welcomeChannel = getWelcomeChannel(guild.getId()); - - EmbedBuilder embed = bot.getEmbedUtil().getEmbed(member) - .setTitle( - bot.getMsg(guild.getId(), "purr.guild.welcome.embed.title") - ) - .setDescription( - bot.getMsg(guild.getId(), "purr.guild.welcome.embed.current_settings") - ) - .addField( - bot.getMsg(guild.getId(), "purr.guild.welcome.embed.subcommands_title"), - bot.getMsg(guild.getId(), "purr.guild.welcome.embed.subcommands_value"), - false - ) - .addField(bot.getMsg(guild.getId(), "purr.guild.welcome.embed.channel"), String.format( - "%s", - welcomeChannel - ), false) - .addField( - bot.getMsg(guild.getId(), "purr.guild.welcome.embed.image_title"), - bot.getMsg(guild.getId(), "purr.guild.welcome.embed.image_value") - .replace("{background}", bot.getWelcomeBg(guild.getId())) - .replace("{icon}", bot.getWelcomeIcon(guild.getId())) - .replace("{color}", bot.getWelcomeColor(guild.getId())), - false - ) - .addField( - bot.getMsg(guild.getId(), "purr.guild.welcome.embed.message_title"), - getMsg(bot.getWelcomeMsg(guild.getId())), - false - ); - - if(file == null || !guild.getSelfMember().hasPermission(tc, Permission.MESSAGE_ATTACH_FILES)){ - tc.sendMessageEmbeds(embed.build()).queue(); - }else{ - embed.addField( - bot.getMsg(guild.getId(), "purr.guild.welcome.embed.preview"), - EmbedBuilder.ZERO_WIDTH_SPACE, - false - ) - .setImage("attachment://welcome_preview.jpg"); - - tc.sendMessageEmbeds(embed.build()) - .addFile(file, "welcome_preview.jpg") - .queue(); - } - - } - - private void update(TextChannel tc, Member member, Type type, String value){ - String id = member.getGuild().getId(); - - switch(type){ - case BACKGROUND: - bot.setWelcomeBg(id, value); - if(value.startsWith("http://") || value.startsWith("https://")){ - value = String.format( - "[`%s`](%s)", - bot.getMsg(id, "purr.guild.welcome.custom"), - value - ); - }else{ - value = "`" + value + "`"; - } - break; - - case CHANNEL: - bot.setWelcomeChannel(id, value); - value = "<#" + value + ">"; - break; - - case COLOR: - bot.setWelcomeColor(id, value); - value = "`" + value + "`"; - break; - - case ICON: - bot.setWelcomeIcon(id, value); - if(value.startsWith("http://") || value.startsWith("https://")){ - value = String.format( - "[`%s`](%s)", - bot.getMsg(id, "purr.guild.welcome.custom"), - value - ); - }else{ - value = "`" + value + "`"; - } - break; - - case MESSAGE: - bot.setWelcomeMsg(id, value); - value = getMsg(value); - } - - tc.sendMessageEmbeds( - bot.getEmbedUtil().getEmbed(member) - .setColor(0x00FF00) - .setDescription( - bot.getMsg(id, "purr.guild.welcome.set") - .replace("{type}", firstUpperCase(type.name())) - .replace("{value}", value) - ) - .build() - ).queue(); - } - - private void reset(TextChannel tc, Member member, Type type){ - String id = member.getGuild().getId(); - - switch(type){ - case BACKGROUND: - bot.setWelcomeBg(id, "color_white"); - break; - - case CHANNEL: - bot.setWelcomeChannel(id, "none"); - break; - - case COLOR: - bot.setWelcomeColor(id, "hex:000000"); - break; - - case ICON: - bot.setWelcomeIcon(id, "purr"); - break; - - case MESSAGE: - bot.setWelcomeMsg(id, "Welcome {mention}!"); - } - - tc.sendMessageEmbeds( - bot.getEmbedUtil().getEmbed(member) - .setColor(0x00FF00) - .setDescription( - bot.getMsg(id, "purr.guild.welcome.reset") - .replace("{type}", firstUpperCase(type.name())) - ) - .build() - ).queue(); - } - - private String getWelcomeChannel(String id){ - if(bot.getWelcomeChannel(id).equals("none")) - return bot.getMsg(id, "purr.guild.welcome.embed.no_channel"); - - Guild guild = bot.getShardManager().getGuildById(id); - if(guild == null) - return bot.getMsg(id, "purr.guild.welcome.embed.no_channel"); - - return String.format("<#%s>", bot.getWelcomeChannel(id)); - } - - private String firstUpperCase(String word){ - return Character.toString(word.charAt(0)).toUpperCase() + word.substring(1).toLowerCase(); - } - - private enum Type{ - BACKGROUND, - CHANNEL, - COLOR, - ICON, - MESSAGE - } -} diff --git a/src/main/java/site/purrbot/bot/commands/info/CmdDonate.java b/src/main/java/site/purrbot/bot/commands/info/CmdDonate.java deleted file mode 100644 index 2a1851ca5..000000000 --- a/src/main/java/site/purrbot/bot/commands/info/CmdDonate.java +++ /dev/null @@ -1,141 +0,0 @@ -/* - * Copyright 2018 - 2021 Andre601 - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated - * documentation files (the "Software"), to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, - * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or substantial - * portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package site.purrbot.bot.commands.info; - -import com.github.rainestormee.jdacommand.CommandAttribute; -import com.github.rainestormee.jdacommand.CommandDescription; -import net.dv8tion.jda.api.EmbedBuilder; -import net.dv8tion.jda.api.entities.*; -import site.purrbot.bot.PurrBot; -import site.purrbot.bot.commands.Command; -import site.purrbot.bot.constants.IDs; - -import java.util.List; -import java.util.Objects; -import java.util.concurrent.TimeUnit; -import java.util.stream.Collectors; - -@CommandDescription( - name = "Donate", - description = "purr.info.donate.description", - triggers = {"donate", "donation", "donations", "donator"}, - attributes = { - @CommandAttribute(key = "category", value = "info"), - @CommandAttribute(key = "usage", value = "{p}donate [--dm]"), - @CommandAttribute(key = "help", value = "{p}donate [--dm]") - } -) -public class CmdDonate implements Command{ - - private final PurrBot bot; - - public CmdDonate(PurrBot bot){ - this.bot = bot; - } - - @Override - public void run(Guild guild, TextChannel tc, Message msg, Member member, String... args){ - MessageEmbed embed = bot.getEmbedUtil().getEmbed(member) - .setDescription(bot.getMsg(guild.getId(), "purr.info.donate.embed.description")) - .addField( - bot.getMsg(guild.getId(), "purr.info.donate.embed.donate_title"), - bot.getMsg(guild.getId(), "purr.info.donate.embed.donate_value"), - false - ) - .addField( - bot.getMsg(guild.getId(), "purr.info.donate.embed.donators_title"), - getDonators(guild.getId()), - false - ) - .addField( - bot.getMsg(guild.getId(), "purr.info.donate.embed.booster_title"), - getBoosters(guild.getId()), - false - ) - .build(); - - if(bot.getMessageUtil().hasArg("dm", args)){ - member.getUser().openPrivateChannel() - .flatMap(channel -> channel.sendMessageEmbeds(embed)) - .queue( - message -> tc.sendMessage( - bot.getMsg(guild.getId(), "purr.info.donate.dm_success", member.getAsMention()) - ).queue(del -> del.delete().queueAfter(5, TimeUnit.SECONDS)), - error -> tc.sendMessage( - bot.getMsg(guild.getId(), "purr.info.donate.dm_failure", member.getAsMention()) - ).queue(del -> del.delete().queueAfter(5, TimeUnit.SECONDS)) - ); - - return; - } - - tc.sendMessageEmbeds(embed).queue(); - } - - private String getDonators(String id){ - Role donator = bot.getShardManager().getRoleById(IDs.DONATOR); - if(donator == null) - return "`?`"; - - return getMembers(donator, id); - } - - private String getBoosters(String id){ - Role booster = bot.getShardManager().getRoleById("603361261043974145"); - if(booster == null) - return "`?`"; - - return getMembers(booster, id); - } - - private String getMembers(Role role, String id){ - Guild guild = bot.getShardManager().getGuildById(IDs.GUILD); - if(guild == null) - return "`?`"; - - StringBuilder builder = new StringBuilder(); - List members = guild.getMembers(); - if(members.isEmpty()) - return "`?`"; - - for(Member member : members){ - if(member == null) - continue; - - if(!member.getRoles().contains(role)) - continue; - - if(member.getId().equals(IDs.ANDRE_601)) - continue; - - String name = String.format("%s (%s)", member.getUser().getAsTag(), member.getAsMention()); - if(builder.length() + name.length() + 30 > MessageEmbed.VALUE_MAX_LENGTH){ - builder.append("\n").append(bot.getMsg(id, "purr.info.donate.embed.more")); - break; - } - - if(builder.length() > 0) - builder.append("\n"); - - builder.append(name); - } - - return builder.toString(); - } -} diff --git a/src/main/java/site/purrbot/bot/commands/info/CmdEmote.java b/src/main/java/site/purrbot/bot/commands/info/CmdEmote.java deleted file mode 100644 index c5ed62ffa..000000000 --- a/src/main/java/site/purrbot/bot/commands/info/CmdEmote.java +++ /dev/null @@ -1,187 +0,0 @@ -/* - * Copyright 2018 - 2021 Andre601 - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated - * documentation files (the "Software"), to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, - * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or substantial - * portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package site.purrbot.bot.commands.info; - -import com.github.rainestormee.jdacommand.CommandAttribute; -import com.github.rainestormee.jdacommand.CommandDescription; -import com.jagrosh.jdautilities.menu.EmbedPaginator; -import net.dv8tion.jda.api.EmbedBuilder; -import net.dv8tion.jda.api.Permission; -import net.dv8tion.jda.api.entities.*; -import net.dv8tion.jda.api.entities.emoji.CustomEmoji; -import net.dv8tion.jda.api.entities.emoji.RichCustomEmoji; -import site.purrbot.bot.PurrBot; -import site.purrbot.bot.commands.Command; - -import javax.annotation.Nullable; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.TimeUnit; -import java.util.stream.Collectors; - -import static net.dv8tion.jda.api.exceptions.ErrorResponseException.ignore; -import static net.dv8tion.jda.api.requests.ErrorResponse.UNKNOWN_MESSAGE; - -@CommandDescription( - name = "Emote", - description = "purr.info.emote.description", - triggers = {"emote", "e"}, - attributes = { - @CommandAttribute(key = "category", value = "info"), - @CommandAttribute(key = "usage", value = - "{p}emote <:emote:>\n" + - "{p}emote <--search>" - ), - @CommandAttribute(key = "help", value = "{p}emote <:emote:|--search>") - } -) -public class CmdEmote implements Command{ - - private final PurrBot bot; - - public CmdEmote(PurrBot bot){ - this.bot = bot; - } - - @Override - public void run(Guild guild, TextChannel tc, Message msg, Member member, String... args){ - if(bot.getMessageUtil().hasArg("search", args)){ - if(!guild.getSelfMember().hasPermission(tc, Permission.MESSAGE_HISTORY)){ - bot.getEmbedUtil().sendPermError(tc, member, Permission.MESSAGE_HISTORY, true); - return; - } - - EmbedPaginator.Builder builder = new EmbedPaginator.Builder().setEventWaiter(bot.getWaiter()) - .setTimeout(1, TimeUnit.MINUTES) - .setText(EmbedBuilder.ZERO_WIDTH_SPACE) - .waitOnSinglePage(true) - .addUsers(member.getUser()) - .setFinalAction(message -> { - if(guild.getSelfMember().hasPermission(message.getGuildChannel(), Permission.MESSAGE_MANAGE)) - message.clearReactions().queue(null, ignore(UNKNOWN_MESSAGE)); - }); - - if(guild.getOwner() != null) - builder.addUsers(guild.getOwner().getUser()); - - tc.getIterableHistory() - .cache(false) - .takeAsync(100) - .thenApply(List::stream) - .thenApply(stream -> stream.filter(message -> !message.getMentions().getCustomEmojis().isEmpty())) - .thenApply(stream -> stream.collect(Collectors.toMap( - Message::getJumpUrl, - m -> m.getMentions().getCustomEmojis(), - (existing, replacement) -> existing, - LinkedHashMap::new - ))) - .thenAccept(emotes -> send(builder, tc, member, emotes)); - return; - } - - if(msg.getMentions().getCustomEmojis().isEmpty()){ - bot.getEmbedUtil().sendError(tc, member, "purr.info.emote.no_args"); - return; - } - - tc.sendMessageEmbeds(emoteInfo(member, msg.getMentions().getCustomEmojis().get(0), guild, null, 1, 1)).queue(); - - } - - private void send(EmbedPaginator.Builder builder, TextChannel tc, Member member, Map> emotes){ - int pos = 0; - - int size = emotes.values().stream() - .mapToInt(List::size) - .sum(); - - for(Map.Entry> entry : emotes.entrySet()){ - for(CustomEmoji emote : entry.getValue()){ - pos++; - builder.addItems(emoteInfo( - member, - emote, - member.getGuild(), - entry.getKey(), - pos, - size - )); - } - } - - builder.build().display(tc); - } - - private MessageEmbed emoteInfo(Member member, CustomEmoji emote, Guild guild, @Nullable String link, int pos, int size){ - RichCustomEmoji e = bot.getShardManager().getEmojiById(emote.getId()); - Guild emoteGuild = null; - if(e != null) - emoteGuild = e.getGuild(); - - String path = size > 1 ? "purr.info.emote.embed.emote_multiple" : "purr.info.emote.embed.emote_single"; - - EmbedBuilder embed = bot.getEmbedUtil().getEmbed(member) - .setTitle( - bot.getMsg(guild.getId(), path) - .replace("{current}", String.valueOf(pos)) - .replace("{total}", String.valueOf(size)) - ) - .addField( - bot.getMsg(guild.getId(), "purr.info.emote.embed.name"), - String.format( - "`:%s:`", - emote.getName() - ), - true - ) - .addField( - bot.getMsg(guild.getId(), "purr.info.emote.embed.id"), - String.format( - "`%s`", - emote.getId() - ), - true - ) - .addField( - bot.getMsg(guild.getId(), "purr.info.emote.embed.guild"), - String.format( - "`%s`", - emoteGuild != null ? emoteGuild.getName() : bot.getMsg(guild.getId(), "purr.info.emote.unknown_guild") - ), - true - ) - .addField( - bot.getMsg(guild.getId(), "purr.info.emote.embed.image"), - bot.getMsg(guild.getId(), "purr.info.emote.embed.link").replace("{link}", emote.getImageUrl()), - true - ) - .setThumbnail(emote.getImageUrl()); - - if(link != null) - embed.addField( - bot.getMsg(guild.getId(), "purr.info.emote.embed.message"), - bot.getMsg(guild.getId(), "purr.info.emote.embed.link") - .replace("{link}", link), - true - ); - - return embed.build(); - } -} diff --git a/src/main/java/site/purrbot/bot/commands/info/CmdGuild.java b/src/main/java/site/purrbot/bot/commands/info/CmdGuild.java deleted file mode 100644 index f2c02227f..000000000 --- a/src/main/java/site/purrbot/bot/commands/info/CmdGuild.java +++ /dev/null @@ -1,323 +0,0 @@ -/* - * Copyright 2018 - 2021 Andre601 - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated - * documentation files (the "Software"), to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, - * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or substantial - * portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package site.purrbot.bot.commands.info; - -import com.github.rainestormee.jdacommand.CommandAttribute; -import com.github.rainestormee.jdacommand.CommandDescription; -import net.dv8tion.jda.api.EmbedBuilder; -import net.dv8tion.jda.api.entities.*; -import site.purrbot.bot.PurrBot; -import site.purrbot.bot.commands.Command; -import site.purrbot.bot.constants.Emotes; - -import java.util.List; - -@CommandDescription( - name = "Guild", - description = "purr.info.guild.description", - triggers = {"guild", "server", "guildinfo", "serverinfo"}, - attributes = { - @CommandAttribute(key = "category", value = "info"), - @CommandAttribute(key = "usage", value = "{p}guild"), - @CommandAttribute(key = "help", value = "{p}guild") - } -) -public class CmdGuild implements Command{ - - private final PurrBot bot; - - public CmdGuild(PurrBot bot){ - this.bot = bot; - } - - @Override - public void run(Guild guild, TextChannel tc, Message msg, Member member, String... args){ - guild.loadMembers().onSuccess(members -> sendGuildInfo(guild, tc, member, members)) - .onError(e -> sendGuildInfo(guild, tc, member, null)); - } - - private void sendGuildInfo(Guild guild, TextChannel tc, Member member, List members){ - EmbedBuilder info = bot.getEmbedUtil().getEmbed(member) - .setTitle(guild.getName()) - .setThumbnail(guild.getIconUrl()); - - setGenericInfo(guild, info); - setMembersAndChannels(guild, info, members); - setGuildFeatures(guild, info); - - if(guild.getBannerUrl() != null){ - info.addField( - EmbedBuilder.ZERO_WIDTH_SPACE, - "**" + bot.getMsg(guild.getId(), "purr.info.guild.embed.features.banner") + "**", - false - ).setImage(guild.getBannerUrl() + "?size=512"); - } - - tc.sendMessageEmbeds(info.build()).queue(); - } - - private void setGenericInfo(Guild guild, EmbedBuilder builder){ - builder.addField( - EmbedBuilder.ZERO_WIDTH_SPACE, - String.format( - "%s\n" + - "%s\n" + - "\n" + - "%s\n" + - "\n" + - "%s", - getOwner(guild), - getCreationDate(guild), - getVerificationLevel(guild), - getBoostLevel(guild) - ), - false - ); - } - - private void setMembersAndChannels(Guild guild, EmbedBuilder builder, List members){ - builder.addField( - EmbedBuilder.ZERO_WIDTH_SPACE, - String.format( - "%s\n" + - "\n" + - "%s", - getMembers(guild, members), - getChannels(guild) - ), - false - ); - } - - private String getOwner(Guild guild){ - Member owner = guild.getOwner(); - String unknown = bot.getMsg(guild.getId(), "misc.unknown_user"); - - return String.format( - "**%s**: %s | %s", - bot.getMsg(guild.getId(), "purr.info.guild.embed.owner"), - owner == null ? unknown : owner.getAsMention(), - owner == null ? unknown : owner.getEffectiveName() - ); - } - - private String getCreationDate(Guild guild){ - return String.format( - "**%s**: %s", - bot.getMsg(guild.getId(), "purr.info.guild.embed.created"), - bot.getMessageUtil().formatTime(guild.getTimeCreated()) - ); - } - - private String getVerificationLevel(Guild guild){ - return String.format( - "**%s**: %s", - bot.getMsg(guild.getId(), "purr.info.guild.embed.levels.title"), - getLevelName(guild) - ); - } - - private String getBoostLevel(Guild guild){ - return String.format( - "**%s**: %s", - bot.getMsg(guild.getId(), "purr.info.guild.embed.boost.title"), - getBoostMessage(guild) - ); - } - - private String getMembers(Guild guild, List members){ - String title = bot.getMsg(guild.getId(), "purr.info.guild.embed.members_title"); - if(members == null){ - return String.format( - "**%s**\n" + - "`?`", - title - ); - } - - int total = members.size(); - long humans = members.stream().filter(member -> !member.getUser().isBot()).count(); - long bots = members.stream().filter(member -> member.getUser().isBot()).count(); - - return String.format( - "**%s**\n" + - "%s", - title, - bot.getMsg(guild.getId(), "purr.info.guild.embed.members_value") - .replace("{members_total}", bot.getMessageUtil().formatNumber(total)) - .replace("{members_human}", bot.getMessageUtil().formatNumber(humans)) - .replace("{members_bot}", bot.getMessageUtil().formatNumber(bots)) - ); - } - - private String getChannels(Guild guild){ - long total = guild.getChannels().stream().filter(chan -> !chan.getType().equals(ChannelType.CATEGORY)).count(); - long text = guild.getChannels().stream().filter(chan -> chan.getType().equals(ChannelType.TEXT)).count(); - long voice = guild.getChannels().stream().filter(chan -> chan.getType().equals(ChannelType.VOICE)).count(); - - return String.format( - "**%s**\n" + - "%s", - bot.getMsg(guild.getId(), "purr.info.guild.embed.channels_title"), - bot.getMsg(guild.getId(), "purr.info.guild.embed.channels_value") - .replace("{channels_total}", bot.getMessageUtil().formatNumber(total)) - .replace("{channels_text}", bot.getMessageUtil().formatNumber(text)) - .replace("{channels_voice}", bot.getMessageUtil().formatNumber(voice)) - ); - } - - private void setGuildFeatures(Guild guild, EmbedBuilder builder){ - builder.addField( - EmbedBuilder.ZERO_WIDTH_SPACE, - String.join( - "\n", - "**" + bot.getMsg(guild.getId(), "purr.info.guild.embed.features.title") + "**", - Feature.ANIMATED_ICON.getString(bot, guild), - Feature.COMMERCE.getString(bot, guild), - Feature.DISCOVERABLE.getString(bot, guild), - Feature.MEMBER_VERIFICATION.getString(bot, guild), - Feature.PARTNERED.getString(bot, guild), - Feature.VANITY_URL.getString(bot, guild), - Feature.VIP_REGIONS.getString(bot, guild) - ), - true - ).addField( - EmbedBuilder.ZERO_WIDTH_SPACE, - String.join( - "\n", - EmbedBuilder.ZERO_WIDTH_SPACE, - Feature.BANNER.getString(bot, guild), - Feature.COMMUNITY.getString(bot, guild), - Feature.INVITE_SPLASH.getString(bot, guild), - Feature.NEWS.getString(bot, guild), - Feature.PREVIEW.getString(bot, guild), - Feature.VERIFIED.getString(bot, guild), - Feature.WELCOME_SCREEN.getString(bot, guild) - ), - true - ); - } - - private String getLevelName(Guild guild){ - Guild.VerificationLevel level = guild.getVerificationLevel(); - - switch(level){ - case VERY_HIGH: - return bot.getMsg(guild.getId(), "purr.info.guild.embed.levels.very_high"); - - case HIGH: - return bot.getMsg(guild.getId(), "purr.info.guild.embed.levels.high"); - - case MEDIUM: - return bot.getMsg(guild.getId(), "purr.info.guild.embed.levels.medium"); - - case LOW: - return bot.getMsg(guild.getId(), "purr.info.guild.embed.levels.low"); - - case NONE: - return bot.getMsg(guild.getId(), "purr.info.guild.embed.levels.none"); - - default: - case UNKNOWN: - return bot.getMsg(guild.getId(), "purr.info.guild.embed.levels.unknown"); - } - } - - private String getBoostMessage(Guild guild){ - int count = guild.getBoostCount(); - String boostMsg; - if(count == 1){ - boostMsg = bot.getMsg(guild.getId(), "purr.info.guild.embed.boost.single"); - }else{ - boostMsg = bot.getMsg(guild.getId(), "purr.info.guild.embed.boost.multiple") - .replace("{boost}", String.valueOf(count)); - } - - return bot.getMsg(guild.getId(), "purr.info.guild.embed.boost.value") - .replace("{boosts}", boostMsg) - .replace("{level}", String.valueOf(guild.getBoostTier().getKey())) - .replace("{BOOST_TIER}", getBoostEmote(guild)); - } - - private String getBoostEmote(Guild guild){ - switch(guild.getBoostTier()){ - default: - case NONE: - case UNKNOWN: - return ""; - - case TIER_1: - return " " + Emotes.BOOST_LEVEL_1.getEmote(); - - case TIER_2: - return " " + Emotes.BOOST_LEVEL_2.getEmote(); - - case TIER_3: - return " " + Emotes.BOOST_LEVEL_3.getEmote(); - } - } - - private enum Feature{ - ANIMATED_ICON ("ANIMATED_ICON", "animated_icon", Emotes.GIF), - BANNER ("BANNER", "banner", Emotes.IMAGES), - COMMERCE ("COMMERCE", "store_channel", Emotes.STORE), - COMMUNITY ("COMMUNITY", "community", Emotes.MEMBERS), - DISCOVERABLE ("DISCOVERABLE", "discoverable", Emotes.DISCOVER), - INVITE_SPLASH ("INVITE_SPLASH", "invite_screen", Emotes.IMAGES), - MEMBER_VERIFICATION("MEMBER_VERIFICATION_GATE_ENABLED", "member_verification", Emotes.RICH_RPESENCE), - NEWS ("NEWS", "news_channel", Emotes.NEWS), - PARTNERED ("PARTNERED", "partnered", Emotes.PARTNER), - PREVIEW ("PREVIEW_ENABLED", "guild_preview", Emotes.RICH_RPESENCE), - VANITY_URL ("VANITY_URL", "vanity_url", Emotes.INVITE), - VERIFIED ("VERIFIED", "verified", Emotes.VERIFIED), - VIP_REGIONS ("VIP_REGIONS", "vip_voice", Emotes.VOICE), - WELCOME_SCREEN ("WELCOME_SCREEN_ENABLED", "welcome_screen", Emotes.RICH_RPESENCE); - - private final String feature; - private final String name; - private final Emotes emote; - - Feature(String feature, String name, Emotes emote){ - this.feature = feature; - this.name = name; - this.emote = emote; - } - - public String getString(PurrBot bot, Guild guild){ - String msg = bot.getMsg(guild.getId(), "purr.info.guild.embed.features." + name); - - if(this == Feature.VANITY_URL){ - if(guild.getVanityUrl() != null){ - return String.format( - "%s [`%s`](%s)", - emote.getEmote(), - msg, - guild.getVanityUrl() - ); - } - } - - return String.format( - "%s %s", - emote.getEmote(), - guild.getFeatures().contains(feature) ? "`" + msg + "`" : "~~`" + msg + "`~~" - ); - } - } -} diff --git a/src/main/java/site/purrbot/bot/commands/info/CmdHelp.java b/src/main/java/site/purrbot/bot/commands/info/CmdHelp.java deleted file mode 100644 index 7dc9e7c6e..000000000 --- a/src/main/java/site/purrbot/bot/commands/info/CmdHelp.java +++ /dev/null @@ -1,342 +0,0 @@ -/* - * Copyright 2018 - 2021 Andre601 - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated - * documentation files (the "Software"), to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, - * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or substantial - * portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package site.purrbot.bot.commands.info; - -import ch.qos.logback.classic.Logger; -import com.github.rainestormee.jdacommand.CommandAttribute; -import com.github.rainestormee.jdacommand.CommandDescription; -import com.jagrosh.jdautilities.menu.EmbedPaginator; -import net.dv8tion.jda.api.EmbedBuilder; -import net.dv8tion.jda.api.Permission; -import net.dv8tion.jda.api.entities.*; -import net.dv8tion.jda.api.interactions.components.buttons.Button; -import org.slf4j.LoggerFactory; -import site.purrbot.bot.PurrBot; -import site.purrbot.bot.commands.Command; - -import java.util.*; -import java.util.concurrent.TimeUnit; -import java.util.stream.Collectors; - -@CommandDescription( - name = "Help", - description = "purr.info.help.description", - triggers = {"help", "command", "commands"}, - attributes = { - @CommandAttribute(key = "category", value = "info"), - @CommandAttribute(key = "usage", value = "{p}help [command]"), - @CommandAttribute(key = "help", value = "{p}help [command]") - } -) -public class CmdHelp implements Command{ - - private final PurrBot bot; - private final HashMap categories = new LinkedHashMap<>(); - - private final Logger logger = (Logger)LoggerFactory.getLogger("Command - Help"); - - public CmdHelp(PurrBot bot){ - this.bot = bot; - - categories.put("fun", "\uD83C\uDFB2"); - categories.put("guild", "\uD83C\uDFAE"); - categories.put("info", "\u2139"); - categories.put("nsfw", "\uD83D\uDC8B"); - categories.put("owner", "<:andre_601:730944556119359588>"); - } - - @Override - public void run(Guild guild, TextChannel tc, Message msg, Member member, String... args) { - String prefix = bot.getPrefix(msg.getGuild().getId()); - - if(args.length > 0){ - Command command = (Command)bot.getCmdHandler().findCommand(args[0]); - - if(command == null || !isCommand(command)){ - showHelpMenu(member, tc, args[0]); - return; - } - - if(!tc.isNSFW() && command.getAttribute("category").equals("nsfw")){ - bot.getEmbedUtil().sendError(tc, member, "purr.info.help.command_info.command_nsfw"); - return; - } - - tc.sendMessageEmbeds(commandHelp(member, command, prefix)) - .setActionRow(Button.link( - "https://docs.purrbot.site/bot/commands#" + command.getDescription().name().toLowerCase(Locale.ROOT), - bot.getMsg(guild.getId(), "purr.info.help.command_info.docs") - )) - .queue(); - }else{ - showHelpMenu(member, tc, null); - } - } - - private void showHelpMenu(Member member, TextChannel tc, String category){ - Guild guild = tc.getGuild(); - String prefix = bot.getPrefix(guild.getId()); - - if(category == null){ - EmbedPaginator.Builder builder = getPaginator(member, tc); - - builder.addItems( - commandList( - member, - "title", - String.join( - "\n", - bot.getMsg(guild.getId(), "purr.info.help.command_menu.categories.fun"), - bot.getMsg(guild.getId(), "purr.info.help.command_menu.categories.guild"), - bot.getMsg(guild.getId(), "purr.info.help.command_menu.categories.info"), - bot.getMsg(guild.getId(), "purr.info.help.command_menu.categories.nsfw") - ) - ) - ); - - builder.addItems(getHelpPages( - "fun", - member, - prefix - )).addItems(getHelpPages( - "guild", - member, - prefix - )).addItems(getHelpPages( - "info", - member, - prefix - )).addItems(getHelpPages( - "nsfw", - member, - prefix, - tc.isNSFW() - )); - - if(bot.getCheckUtil().isDeveloper(member)){ - builder.addItems(getHelpPages( - "owner", - member, - prefix - )); - } - - builder.build().display(tc); - }else{ - String cat = getCategory(guild.getId(), category); - - if(cat == null){ - MessageEmbed embed = bot.getEmbedUtil().getEmbed(member) - .setColor(0xFF0000) - .setDescription( - bot.getMsg(guild.getId(), "purr.info.help.command_info.no_command") - .replace("{command}", category) - ) - .build(); - - tc.sendMessageEmbeds(embed).queue(); - return; - } - - List pages = getHelpPages(cat, member, prefix, tc.isNSFW()); - - if(pages.size() == 1){ - tc.sendMessageEmbeds(pages.get(0)).queue(); - return; - } - - EmbedPaginator.Builder builder = getPaginator(member, tc); - - builder.addItems(pages).build().display(tc); - } - - } - - private List getHelpPages(String category, Member member, String prefix){ - return getHelpPages(category, member, prefix, false); - } - - private List getHelpPages(String category, Member member, String prefix, boolean isNsfw){ - List embeds = new LinkedList<>(); - - if(category.equals("nsfw") && !isNsfw){ - embeds.add(commandList( - member, - category, - bot.getMsg(member.getGuild().getId(), "purr.info.help.command_menu.nsfw_info") - )); - return embeds; - } - - StringBuilder builder = new StringBuilder(); - List commands = getCommands(category); - - - for(Command command : commands){ - if(builder.length() + command.getAttribute("help").length() + 10 > MessageEmbed.VALUE_MAX_LENGTH){ - embeds.add(commandList( - member, - category, - builder.toString() - )); - - builder.setLength(0); - } - - builder.append(command.getAttribute("help").replace("{p}", prefix)) - .append("\n"); - } - - embeds.add(commandList( - member, - category, - builder.toString() - )); - - return embeds; - } - - private List getCommands(String category){ - return bot.getCmdHandler().getCommands().stream() - .map(cmd -> (Command)cmd) - .sorted(Comparator.comparing(cmd -> cmd.getDescription().name().toLowerCase(Locale.ROOT))) - .filter(cmd -> cmd.getAttribute("category").equals(category)) - .collect(Collectors.toList()); - } - - private EmbedPaginator.Builder getPaginator(Member member, TextChannel tc){ - EmbedPaginator.Builder builder = new EmbedPaginator.Builder() - .setEventWaiter(bot.getWaiter()) - .setTimeout(1, TimeUnit.MINUTES) - .waitOnSinglePage(true) - .setText(EmbedBuilder.ZERO_WIDTH_SPACE) - .wrapPageEnds(true) - .addUsers(member.getUser()) - .setFinalAction(message -> { - if(tc.getGuild().getSelfMember().hasPermission(tc, Permission.MESSAGE_MANAGE)) - message.clearReactions().queue( - null, - e -> logger.warn("Couldn't clear reactions from message.") - ); - }); - - if(tc.getGuild().getOwner() != null) - builder.addUsers(tc.getGuild().getOwner().getUser()); - - return builder; - } - - private MessageEmbed commandHelp(Member member, Command cmd, String prefix){ - CommandDescription desc = cmd.getDescription(); - String[] triggers = desc.triggers(); - Guild guild = member.getGuild(); - - EmbedBuilder commandInfo = bot.getEmbedUtil().getEmbed(member) - .setTitle( - bot.getMsg(guild.getId(), "purr.info.help.command_info.title") - .replace("{command}", desc.name()) - ) - .setDescription( - bot.getMsg(guild.getId(), desc.description()) - ) - .addField( - bot.getMsg(guild.getId(), "purr.info.help.command_info.usage_title"), - bot.getMsg(guild.getId(), "purr.info.help.command_info.usage_value") - .replace("{commands}", cmd.getAttribute("usage").replace("{p}", prefix)), - false - ) - .addField( - bot.getMsg(guild.getId(), "purr.info.help.command_info.aliases"), - String.format( - "`%s`", - String.join(", ", triggers) - ), - false - ); - - return commandInfo.build(); - } - - private boolean isCommand(Command cmd){ - return cmd.getDescription() != null || cmd.hasAttribute("description"); - } - - private MessageEmbed commandList(Member member, String title, String commands){ - String id = member.getGuild().getId(); - return bot.getEmbedUtil().getEmbed(member) - .addField( - bot.getMsg(id, "purr.info.help.command_menu.description.nav_title"), - bot.getMsg(id, "purr.info.help.command_menu.description.nav_value"), - false - ) - .addField( - EmbedBuilder.ZERO_WIDTH_SPACE, - bot.getMsg(id, "purr.info.help.command_menu.description.command_value"), - false - ) - .addField( - EmbedBuilder.ZERO_WIDTH_SPACE, - bot.getMsg(id, "purr.info.help.command_menu.description.support"), - false - ) - .addField( - String.format( - "%s%s", - title.equals("title") ? "" : categories.get(title) + " ", - bot.getMsg(id, "purr.info.help.command_menu.categories." + title) - ), - String.format( - "```\n" + - "%s\n" + - "```", - commands - ), - false - ) - .addField( - bot.getMsg(id, "purr.info.help.command_menu.support_title"), - bot.getMsg(id, "purr.info.help.command_menu.support_value"), - false - ) - .build(); - } - - // Method to check, if text equals either a translated category name or the english one. - private String getCategory(String id, String text){ - String fun = "cat:" + bot.getMsg(id, "purr.info.help.command_menu.categories.fun"); - String guild = "cat:" + bot.getMsg(id, "purr.info.help.command_menu.categories.guild"); - String info = "cat:" + bot.getMsg(id, "purr.info.help.command_menu.categories.info"); - String nsfw = "cat:" + bot.getMsg(id, "purr.info.help.command_menu.categories.nsfw"); - - if(text.equalsIgnoreCase(fun) || text.equalsIgnoreCase("cat:fun")){ - return "fun"; - }else - if(text.equalsIgnoreCase(guild) || text.equalsIgnoreCase("cat:guild")){ - return "guild"; - }else - if(text.equalsIgnoreCase(info) || text.equalsIgnoreCase("cat:info")){ - return "info"; - }else - if(text.equalsIgnoreCase(nsfw) || text.equalsIgnoreCase("cat:nsfw")){ - return "nsfw"; - }else{ - return null; - } - } -} diff --git a/src/main/java/site/purrbot/bot/commands/info/CmdInfo.java b/src/main/java/site/purrbot/bot/commands/info/CmdInfo.java deleted file mode 100644 index 9c8a636ef..000000000 --- a/src/main/java/site/purrbot/bot/commands/info/CmdInfo.java +++ /dev/null @@ -1,157 +0,0 @@ -/* - * Copyright 2018 - 2021 Andre601 - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated - * documentation files (the "Software"), to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, - * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or substantial - * portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package site.purrbot.bot.commands.info; - -import com.github.rainestormee.jdacommand.CommandAttribute; -import com.github.rainestormee.jdacommand.CommandDescription; -import net.dv8tion.jda.api.EmbedBuilder; -import net.dv8tion.jda.api.JDAInfo; -import net.dv8tion.jda.api.entities.*; -import net.dv8tion.jda.api.utils.MarkdownUtil; -import site.purrbot.bot.PurrBot; -import site.purrbot.bot.commands.Command; -import site.purrbot.bot.constants.IDs; -import site.purrbot.bot.constants.Links; - -@CommandDescription( - name = "Info", - description = "purr.info.info.description", - triggers = {"info", "infos", "information"}, - attributes = { - @CommandAttribute(key = "category", value = "info"), - @CommandAttribute(key = "usage", value = "{p}info [--dm]"), - @CommandAttribute(key = "help", value = "{p}info [--dm]") - } -) -public class CmdInfo implements Command{ - - private final PurrBot bot; - - public CmdInfo(PurrBot bot){ - this.bot = bot; - } - - @Override - public void run(Guild guild, TextChannel tc, Message msg, Member member, String... args){ - MessageEmbed embed = getEmbed(member); - if(bot.getMessageUtil().hasArg("dm", args)){ - String mention = member.getAsMention(); - String prefix = bot.isBeta() ? "snuggle" : "purr"; - member.getUser().openPrivateChannel() - .flatMap(channel -> channel.sendMessageEmbeds(embed)) - .queue( - message -> tc.sendMessage( - bot.getMsg(guild.getId(), prefix + ".info.info.dm_success", mention) - ).queue(), - error -> tc.sendMessage( - bot.getMsg(guild.getId(), prefix + ".info.info.dm_failure", mention) - ).queue() - ); - return; - } - - tc.sendMessageEmbeds(embed).queue(); - } - - private MessageEmbed getEmbed(Member member){ - Guild guild = member.getGuild(); - EmbedBuilder builder = bot.getEmbedUtil().getEmbed(member); - if(bot.isBeta()){ - builder.setAuthor(guild.getJDA().getSelfUser().getName(), - Links.WEBSITE, - guild.getJDA().getSelfUser().getEffectiveAvatarUrl() - ) - .setThumbnail(guild.getJDA().getSelfUser().getEffectiveAvatarUrl()) - .addField( - bot.getMsg(guild.getId(), "snuggle.info.info.embed.about_title"), - bot.getMsg(guild.getId(), "snuggle.info.info.embed.about_value") - .replace("{name}", guild.getSelfMember().getAsMention()), - false - ); - }else{ - builder.setAuthor(guild.getJDA().getSelfUser().getName(), - Links.WEBSITE, - guild.getJDA().getSelfUser().getEffectiveAvatarUrl() - ) - .setThumbnail(guild.getJDA().getSelfUser().getEffectiveAvatarUrl()) - .addField( - bot.getMsg(guild.getId(), "purr.info.info.embed.about_title"), - bot.getMsg(guild.getId(), "purr.info.info.embed.about_value") - .replace("{name}", guild.getSelfMember().getAsMention()) - .replace("{id}", IDs.ANDRE_601), - false - ); - } - - builder.addField( - bot.getMsg(guild.getId(), "purr.info.info.embed.commands_title"), - bot.getMsg(guild.getId(), "purr.info.info.embed.commands_value"), - false - ) - .addField( - bot.getMsg(guild.getId(), "purr.info.info.embed.bot_info.title"), - String.join( - "\n", - getLink(guild.getId(), "bot_info.version", Links.GITHUB) - .replace("{bot_version}", "BOT_VERSION"), - getLink(guild.getId(), "bot_info.library", JDAInfo.GITHUB) - .replace("{jda_version}", JDAInfo.VERSION) - ), - false - ) - .addField( - bot.getMsg(guild.getId(), "purr.info.info.embed.bot_lists_title"), - String.format( - "[`Discord.bots.gg`](%s)\n" + - "[`Discordextremelist.xyz`](%s)\n" + - "[`Discordservices.net`](%s)", - Links.DISCORD_BOTS_GG, - Links.DISCORDEXTREMELIST_XYZ, - Links.DISCORDSERVICES_NET - ), - false - ) - .addField( - bot.getMsg(guild.getId(), "purr.info.info.embed.links.title"), - String.join( - "\n", - bot.getMsg(guild.getId(), "purr.info.info.embed.links.discord"), - bot.getMsg(guild.getId(), "purr.info.info.embed.links.github"), - bot.getMsg(guild.getId(), "purr.info.info.embed.links.policy"), - bot.getMsg(guild.getId(), "purr.info.info.embed.links.twitter"), - bot.getMsg(guild.getId(), "purr.info.info.embed.links.website"), - bot.getMsg(guild.getId(), "purr.info.info.embed.links.wiki") - ), - false - ) - .addField( - bot.getMsg(guild.getId(), "purr.info.info.embed.support_title"), - bot.getMsg(guild.getId(), "purr.info.info.embed.support_value"), - false - ); - - return builder.build(); - } - - private String getLink(String id, String path, String link){ - String text = bot.getMsg(id, "purr.info.info.embed." + path); - - return MarkdownUtil.maskedLink(text, link); - } -} diff --git a/src/main/java/site/purrbot/bot/commands/info/CmdInvite.java b/src/main/java/site/purrbot/bot/commands/info/CmdInvite.java deleted file mode 100644 index 739e3365f..000000000 --- a/src/main/java/site/purrbot/bot/commands/info/CmdInvite.java +++ /dev/null @@ -1,129 +0,0 @@ -/* - * Copyright 2018 - 2021 Andre601 - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated - * documentation files (the "Software"), to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, - * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or substantial - * portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package site.purrbot.bot.commands.info; - -import com.github.rainestormee.jdacommand.CommandAttribute; -import com.github.rainestormee.jdacommand.CommandDescription; -import net.dv8tion.jda.api.EmbedBuilder; -import net.dv8tion.jda.api.Permission; -import net.dv8tion.jda.api.entities.Guild; -import net.dv8tion.jda.api.entities.Member; -import net.dv8tion.jda.api.entities.Message; -import net.dv8tion.jda.api.entities.TextChannel; -import net.dv8tion.jda.api.utils.MarkdownUtil; -import site.purrbot.bot.PurrBot; -import site.purrbot.bot.commands.Command; -import site.purrbot.bot.constants.IDs; -import site.purrbot.bot.constants.Links; - -@CommandDescription( - name = "Invite", - description = "purr.info.invite.description", - triggers = {"invite", "links"}, - attributes = { - @CommandAttribute(key = "category", value = "info"), - @CommandAttribute(key = "usage", value = "{p}invite [--dm]"), - @CommandAttribute(key = "help", value = "{p}invite [--dm]") - } -) -public class CmdInvite implements Command{ - - private final PurrBot bot; - - public CmdInvite(PurrBot bot){ - this.bot = bot; - } - - @Override - public void run(Guild guild, TextChannel tc, Message msg, Member member, String... args){ - if(bot.isBeta()){ - bot.getEmbedUtil().sendError(tc, member, "snuggle.info.invite.message"); - return; - } - - String id = guild.getId(); - - EmbedBuilder invite = bot.getEmbedUtil().getEmbed(member) - .setAuthor( - msg.getJDA().getSelfUser().getName(), - Links.WEBSITE, - msg.getJDA().getSelfUser().getEffectiveAvatarUrl() - ) - .addField( - bot.getMsg(id, "purr.info.invite.embed.info_title"), - bot.getMsg(id, "purr.info.invite.embed.info_value"), - false - ) - .addField( - bot.getMsg(id, "purr.info.invite.embed.about_title"), - bot.getMsg(id, "purr.info.invite.embed.about_value"), - false - ) - .addField( - EmbedBuilder.ZERO_WIDTH_SPACE, - String.join( - "\n", - getLink( - id, - "discord", - Links.DISCORD - ), - getInvite( - guild, - Permission.MESSAGE_SEND, - Permission.MESSAGE_EMBED_LINKS, - Permission.MESSAGE_HISTORY, - Permission.MESSAGE_ADD_REACTION, - Permission.MESSAGE_EXT_EMOJI, - Permission.MESSAGE_MANAGE, - Permission.MESSAGE_ATTACH_FILES - ) - ), - false - ); - - if(bot.getMessageUtil().hasArg("dm", args)){ - member.getUser().openPrivateChannel() - .flatMap((channel) -> channel.sendMessageEmbeds(invite.build())) - .queue( - message -> tc.sendMessage( - bot.getMsg(guild.getId(), "purr.info.invite.dm_success", member.getAsMention()) - ).queue(), - (error) -> tc.sendMessage( - bot.getMsg(guild.getId(), "purr.info.invite.dm_failure", member.getAsMention()) - ).queue() - ); - return; - } - - tc.sendMessageEmbeds(invite.build()).queue(); - } - - private String getInvite(Guild guild, Permission... permissions){ - String invite = "https://add.botl.ink?id=" + IDs.PURR + "&perms=" + Permission.getRaw(permissions); - - return getLink(guild.getId(), "invite", invite); - } - - private String getLink(String id, String path, String link){ - String text = bot.getMsg(id, "purr.info.invite.embed.links." + path); - - return MarkdownUtil.maskedLink(text, link); - } -} diff --git a/src/main/java/site/purrbot/bot/commands/info/CmdPing.java b/src/main/java/site/purrbot/bot/commands/info/CmdPing.java deleted file mode 100644 index 1a462c04d..000000000 --- a/src/main/java/site/purrbot/bot/commands/info/CmdPing.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright 2018 - 2021 Andre601 - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated - * documentation files (the "Software"), to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, - * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or substantial - * portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package site.purrbot.bot.commands.info; - -import com.github.rainestormee.jdacommand.CommandAttribute; -import com.github.rainestormee.jdacommand.CommandDescription; -import net.dv8tion.jda.api.entities.Guild; -import net.dv8tion.jda.api.entities.Member; -import net.dv8tion.jda.api.entities.Message; -import net.dv8tion.jda.api.entities.TextChannel; -import site.purrbot.bot.PurrBot; -import site.purrbot.bot.commands.Command; - -import java.time.temporal.ChronoUnit; - -@CommandDescription( - name = "Ping", - description = "purr.info.ping.description", - triggers = {"ping"}, - attributes = { - @CommandAttribute(key = "category", value = "info"), - @CommandAttribute(key = "usage", value = "{p}ping"), - @CommandAttribute(key = "help", value = "{p}ping") - } -) -public class CmdPing implements Command{ - - private final PurrBot bot; - public CmdPing(PurrBot bot){ - this.bot = bot; - } - - @Override - public void run(Guild guild, TextChannel tc, Message msg, Member member, String... args){ - tc.sendMessage( - bot.getRandomMsg(guild.getId(), "purr.info.ping.loading") - ).queue(message -> msg.getJDA().getRestPing().queue(time -> message.editMessage( - bot.getMsg(guild.getId(), "purr.info.ping.info_full") - .replace("{edit_message}", String.valueOf( - msg.getTimeCreated().until(message.getTimeCreated(), ChronoUnit.MILLIS) - )) - .replace("{discord}", String.valueOf(msg.getJDA().getGatewayPing())) - .replace("{rest_action}", String.valueOf(time)) - ).queue(), throwable -> message.editMessage( - bot.getMsg(guild.getId(), "purr.info.ping.info") - .replace("{edit_message}", String.valueOf( - msg.getTimeCreated().until(message.getTimeCreated(), ChronoUnit.MILLIS) - )) - .replace("{discord}", String.valueOf(msg.getJDA().getGatewayPing())) - ).queue())); - } -} diff --git a/src/main/java/site/purrbot/bot/commands/info/CmdQuote.java b/src/main/java/site/purrbot/bot/commands/info/CmdQuote.java deleted file mode 100644 index 451767815..000000000 --- a/src/main/java/site/purrbot/bot/commands/info/CmdQuote.java +++ /dev/null @@ -1,127 +0,0 @@ -/* - * Copyright 2018 - 2021 Andre601 - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated - * documentation files (the "Software"), to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, - * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or substantial - * portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package site.purrbot.bot.commands.info; - -import com.github.rainestormee.jdacommand.CommandAttribute; -import com.github.rainestormee.jdacommand.CommandDescription; -import net.dv8tion.jda.api.EmbedBuilder; -import net.dv8tion.jda.api.Permission; -import net.dv8tion.jda.api.entities.*; -import net.dv8tion.jda.api.interactions.components.buttons.Button; -import site.purrbot.bot.PurrBot; -import site.purrbot.bot.commands.Command; - -@CommandDescription( - name = "Quote", - description = "purr.info.quote.description", - triggers = {"quote"}, - attributes = { - @CommandAttribute(key = "category", value = "info"), - @CommandAttribute(key = "usage", value = "{p}quote [#channel]"), - @CommandAttribute(key = "help", value = "{p}quote [#channel]") - } -) -public class CmdQuote implements Command{ - - private final PurrBot bot; - - public CmdQuote(PurrBot bot){ - this.bot = bot; - } - - @Override - public void run(Guild guild, TextChannel tc, Message msg, Member member, String... args){ - if(args.length == 0){ - bot.getEmbedUtil().sendError(tc, member, "purr.info.quote.few_args"); - return; - } - - TextChannel targetChannel = msg.getMentions().getChannels(TextChannel.class).isEmpty() ? tc : msg.getMentions().getChannels(TextChannel.class).get(0); - - if(targetChannel.isNSFW() && !tc.isNSFW()){ - MessageEmbed embed = bot.getEmbedUtil().getEmbed(member) - .setColor(0xFF0000) - .setDescription( - bot.getMsg(guild.getId(), "purr.info.quote.nsfw_channel") - .replace("{channel}", targetChannel.getAsMention()) - ).build(); - - tc.sendMessageEmbeds(embed).queue(); - return; - } - - if(!guild.getSelfMember().hasPermission(targetChannel, Permission.VIEW_CHANNEL, Permission.MESSAGE_HISTORY)){ - bot.getEmbedUtil().sendPermError(tc, member, targetChannel, Permission.MESSAGE_HISTORY, true); - return; - } - - targetChannel.retrieveMessageById(args[0]).queue( - message -> { - if(message.getAttachments().isEmpty() && message.getContentRaw().isEmpty()){ - bot.getEmbedUtil().sendError(tc, member, "purr.info.quote.no_value"); - return; - } - - String memberName = getMemberName(guild.getId(), message.getMember()); - EmbedBuilder quote = bot.getEmbedUtil().getEmbed() - .setAuthor( - bot.getMsg(guild.getId(), "purr.info.quote.embed_basic.info", memberName, false), - null, - message.getAuthor().getEffectiveAvatarUrl() - ) - .setDescription(message.getContentRaw()) - .setFooter( - bot.getMsg(guild.getId(), "purr.info.quote.embed_basic.channel").replace("{channel}", targetChannel.getName()) - ) - .setTimestamp(message.getTimeCreated()); - - if(!message.getAttachments().isEmpty()){ - for(Message.Attachment attachment : message.getAttachments()){ - if(!attachment.isImage()) - continue; - - quote.setImage(attachment.getUrl()); - break; - } - } - - tc.sendMessageEmbeds(quote.build()) - .setActionRow(Button.link(message.getJumpUrl(), bot.getMsg(guild.getId(), "purr.info.quote.button"))) - .queue(); - }, - e -> { - MessageEmbed embed = bot.getEmbedUtil().getEmbed(member) - .setColor(0xFF0000) - .setDescription( - bot.getMsg(guild.getId(), "purr.info.quote.no_msg") - .replace("{channel}", targetChannel.getAsMention()) - ).build(); - - tc.sendMessageEmbeds(embed).queue(); - } - ); - } - - private String getMemberName(String guildId, Member member){ - if(member == null) - return bot.getMsg(guildId, "misc.unknown_user"); - - return member.getEffectiveName(); - } -} diff --git a/src/main/java/site/purrbot/bot/commands/info/CmdShards.java b/src/main/java/site/purrbot/bot/commands/info/CmdShards.java deleted file mode 100644 index 5ba6c6636..000000000 --- a/src/main/java/site/purrbot/bot/commands/info/CmdShards.java +++ /dev/null @@ -1,170 +0,0 @@ -/* - * Copyright 2018 - 2021 Andre601 - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated - * documentation files (the "Software"), to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, - * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or substantial - * portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package site.purrbot.bot.commands.info; - -import com.github.rainestormee.jdacommand.CommandAttribute; -import com.github.rainestormee.jdacommand.CommandDescription; -import com.jagrosh.jdautilities.menu.EmbedPaginator; -import net.dv8tion.jda.api.EmbedBuilder; -import net.dv8tion.jda.api.JDA; -import net.dv8tion.jda.api.Permission; -import net.dv8tion.jda.api.entities.*; -import net.dv8tion.jda.api.requests.ErrorResponse; -import site.purrbot.bot.PurrBot; -import site.purrbot.bot.commands.Command; -import site.purrbot.bot.constants.Emotes; - -import java.text.DecimalFormat; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.List; -import java.util.concurrent.TimeUnit; -import java.util.stream.Collectors; - -import static net.dv8tion.jda.api.exceptions.ErrorResponseException.ignore; - -@CommandDescription( - name = "Shards", - description = "purr.info.shards.description", - triggers = {"shard", "shards", "shardinfo"}, - attributes = { - @CommandAttribute(key = "category", value = "info"), - @CommandAttribute(key = "usage", value = "{p}shards"), - @CommandAttribute(key = "help", value = "{p}shards") - } -) -public class CmdShards implements Command{ - - private final PurrBot bot; - - public CmdShards(PurrBot bot){ - this.bot = bot; - } - - @Override - public void run(Guild guild, TextChannel tc, Message msg, Member member, String... args){ - EmbedPaginator.Builder builder = new EmbedPaginator.Builder() - .setEventWaiter(bot.getWaiter()) - .addUsers(member.getUser()) - .waitOnSinglePage(true) - .wrapPageEnds(true) - .setText(EmbedBuilder.ZERO_WIDTH_SPACE) - .setTimeout(1, TimeUnit.MINUTES) - .setFinalAction(message -> { - if(guild.getSelfMember().hasPermission(tc, Permission.MESSAGE_MANAGE)) - message.clearReactions().queue(null, ignore(ErrorResponse.UNKNOWN_MESSAGE)); - }); - - if(guild.getOwner() != null) - builder.addUsers(guild.getOwner().getUser()); - - int id = msg.getJDA().getShardInfo().getShardId(); - final List shards = bot.getShardManager().getShardCache().stream() - .sorted(Comparator.comparing(jda -> jda.getShardInfo().getShardId())) - .collect(Collectors.toList()); - List embeds = new ArrayList<>(); - - double ping = 0; - double guilds = 0; - - for(final JDA jda : shards){ - int currId = jda.getShardInfo().getShardId(); - - ping += jda.getGatewayPing(); - guilds += jda.getGuildCache().size(); - MessageEmbed embed = bot.getEmbedUtil().getEmbed(member) - .setTitle( - bot.getMsg(guild.getId(), "purr.info.shards.embed.title") - .replace("{shard_id}", String.valueOf(currId)) - .replace("{shard_total}", String.valueOf(shards.size())) - ) - .addField( - bot.getMsg(guild.getId(), "purr.info.shards.embed.current_title"), - currId == id ? Emotes.ACCEPT.getEmote() : Emotes.DENY.getEmote(), - true - ) - .addField( - bot.getMsg(guild.getId(), "purr.info.shards.embed.guilds_title"), - String.format("`%d`", jda.getGuildCache().size()), - true - ) - .addField( - bot.getMsg(guild.getId(), "purr.info.shards.embed.status_title"), - getStatus(jda, guild.getId()), - true - ) - .addField( - bot.getMsg(guild.getId(), "purr.info.shards.embed.ping_title"), - String.format("`%d`", jda.getGatewayPing()), - true - ) - .build(); - - embeds.add(embed); - } - - double avgPing = (ping / bot.getShardManager().getShardCache().size()); - double avgGuilds = (guilds / bot.getShardManager().getShardCache().size()); - - DecimalFormat format = new DecimalFormat("#,###.##"); - - MessageEmbed average = bot.getEmbedUtil().getEmbed(member) - .setTitle(bot.getMsg(guild.getId(), "purr.info.shards.average.title")) - .setDescription(bot.getMsg(guild.getId(), "purr.info.shards.average.description")) - .addField( - bot.getMsg(guild.getId(), "purr.info.shards.average.guilds"), - String.format("`%s`", format.format(avgGuilds)), - false - ) - .addField( - bot.getMsg(guild.getId(), "purr.info.shards.average.ping"), - String.format("`%s`", format.format(avgPing)), - false - ) - .build(); - - builder.addItems(average); - for(MessageEmbed embed : embeds) - builder.addItems(embed); - - builder.build() - .display(tc); - } - - private String getStatus(JDA jda, String id){ - String status; - switch(jda.getStatus()){ - case CONNECTED: - status = bot.getMsg(id, "purr.info.shards.status.connected"); - break; - - case ATTEMPTING_TO_RECONNECT: - case RECONNECT_QUEUED: - status = bot.getMsg(id, "purr.info.shards.status.reconnect"); - break; - - case DISCONNECTED: - default: - status = bot.getMsg(id, "purr.info.shards.status.disconnected"); - break; - } - - return "`" + status + "`"; - } -} diff --git a/src/main/java/site/purrbot/bot/commands/info/CmdStats.java b/src/main/java/site/purrbot/bot/commands/info/CmdStats.java deleted file mode 100644 index 7fc29253d..000000000 --- a/src/main/java/site/purrbot/bot/commands/info/CmdStats.java +++ /dev/null @@ -1,167 +0,0 @@ -/* - * Copyright 2018 - 2021 Andre601 - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated - * documentation files (the "Software"), to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, - * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or substantial - * portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package site.purrbot.bot.commands.info; - -import com.github.rainestormee.jdacommand.CommandAttribute; -import com.github.rainestormee.jdacommand.CommandDescription; -import net.dv8tion.jda.api.EmbedBuilder; -import net.dv8tion.jda.api.JDA; -import net.dv8tion.jda.api.entities.Guild; -import net.dv8tion.jda.api.entities.Member; -import net.dv8tion.jda.api.entities.Message; -import net.dv8tion.jda.api.entities.TextChannel; -import net.dv8tion.jda.api.sharding.ShardManager; -import site.purrbot.bot.PurrBot; -import site.purrbot.bot.commands.Command; - -import java.lang.management.ManagementFactory; -import java.text.DecimalFormat; -import java.util.concurrent.TimeUnit; - -@CommandDescription( - name = "Stats", - description = "purr.info.stats.description", - triggers = {"stats", "stat", "statistic", "statistics"}, - attributes = { - @CommandAttribute(key = "category", value = "info"), - @CommandAttribute(key = "usage", value = "{p}stats"), - @CommandAttribute(key = "help", value = "{p}stats") - } -) -public class CmdStats implements Command{ - - private final PurrBot bot; - - public CmdStats(PurrBot bot){ - this.bot = bot; - } - - - @Override - public void run(Guild guild, TextChannel tc, Message msg, Member member, String... args){ - JDA jda = msg.getJDA(); - ShardManager shardManager = bot.getShardManager(); - - long uptime = ManagementFactory.getRuntimeMXBean().getUptime(); - - EmbedBuilder stats = bot.getEmbedUtil().getEmbed(member) - .setAuthor( - bot.getMsg(guild.getId(), "purr.info.stats.embed.title") - ) - .addField( - bot.getMsg(guild.getId(), "purr.info.stats.embed.shard_total_title"), - bot.getMsg(guild.getId(), "purr.info.stats.embed.shard_total_value") - .replace("{shards}", formatNumber(shardManager.getShardCache().size())) - .replace("{guilds}", formatNumber(shardManager.getGuildCache().size())), - false - ) - .addField( - bot.getMsg(guild.getId(), "purr.info.stats.embed.shard_this_title"), - bot.getMsg(guild.getId(), "purr.info.stats.embed.shard_this_value") - .replace("{id}", String.valueOf(jda.getShardInfo().getShardId())) - .replace("{guilds}", formatNumber(jda.getGuildCache().size())), - false - ) - .addField( - bot.getMsg(guild.getId(), "purr.info.stats.embed.other_title"), - bot.getMsg(guild.getId(), "purr.info.stats.embed.other_value") - .replace("{ram}", getRAM()) - .replace("{days}", getDaysString(uptime, guild.getId())) - .replace("{hours}", getHoursString(uptime, guild.getId())) - .replace("{minutes}", getMinutesString(uptime, guild.getId())) - .replace("{seconds}", getSecondsString(uptime, guild.getId())), - false - ); - - tc.sendMessageEmbeds(stats.build()).queue(); - - } - - private long getDays(long uptime){ - return TimeUnit.MILLISECONDS.toDays(uptime); - } - - private long getHours(long uptime){ - return TimeUnit.MILLISECONDS.toHours(uptime) - getDays(uptime) * 24; - } - - private long getMinutes(long uptime){ - return TimeUnit.MILLISECONDS.toMinutes(uptime) - getHours(uptime) * 60 - getDays(uptime) * 1440; - } - - private long getSeconds(long uptime){ - return TimeUnit.MILLISECONDS.toSeconds(uptime) - getMinutes(uptime) * 60 - getHours(uptime) * 3600 - - getDays(uptime) * 86400; - } - - private String getDaysString(long uptime, String id){ - long time = getDays(uptime); - - return String.format( - "%d %s", - time, - time == 1 ? bot.getMsg(id, "purr.info.stats.uptime.day") : bot.getMsg(id, "purr.info.stats.uptime.days") - ); - } - - private String getHoursString(long uptime, String id){ - long time = getHours(uptime); - - return String.format( - "%d %s", - time, - time == 1 ? bot.getMsg(id, "purr.info.stats.uptime.hour") : bot.getMsg(id, "purr.info.stats.uptime.hours") - ); - } - - private String getMinutesString(long uptime, String id){ - long time = getMinutes(uptime); - - return String.format( - "%d %s", - time, - time == 1 ? bot.getMsg(id, "purr.info.stats.uptime.minute") : bot.getMsg(id, "purr.info.stats.uptime.minutes") - ); - } - - private String getSecondsString(long uptime, String id){ - long time = getSeconds(uptime); - - return String.format( - "%d %s", - time, - time == 1 ? bot.getMsg(id, "purr.info.stats.uptime.second") : bot.getMsg(id, "purr.info.stats.uptime.seconds") - ); - } - - private String getRAM(){ - long usedMem = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed() >> 20; - long totalMem = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getMax() >> 20; - - return String.format( - "%d/%dMB", - usedMem, - totalMem - ); - } - - private String formatNumber(long number){ - return new DecimalFormat("#,###,###").format(number); - } -} diff --git a/src/main/java/site/purrbot/bot/commands/info/CmdUser.java b/src/main/java/site/purrbot/bot/commands/info/CmdUser.java deleted file mode 100644 index 1086792be..000000000 --- a/src/main/java/site/purrbot/bot/commands/info/CmdUser.java +++ /dev/null @@ -1,250 +0,0 @@ -/* - * Copyright 2018 - 2021 Andre601 - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated - * documentation files (the "Software"), to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, - * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or substantial - * portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package site.purrbot.bot.commands.info; - -import com.github.rainestormee.jdacommand.CommandAttribute; -import com.github.rainestormee.jdacommand.CommandDescription; -import net.dv8tion.jda.api.EmbedBuilder; -import net.dv8tion.jda.api.entities.*; -import net.dv8tion.jda.api.utils.MarkdownSanitizer; -import net.dv8tion.jda.api.utils.MarkdownUtil; -import site.purrbot.bot.PurrBot; -import site.purrbot.bot.commands.Command; -import site.purrbot.bot.constants.Emotes; - -import java.util.List; - -@CommandDescription( - name = "User", - description = "purr.info.user.description", - triggers = {"user", "member", "userinfo", "memberinfo"}, - attributes = { - @CommandAttribute(key = "category", value = "info"), - @CommandAttribute(key = "usage", value = "{p}user [@user]"), - @CommandAttribute(key = "help", value = "{p}user [@user]") - } -) -public class CmdUser implements Command{ - - private final PurrBot bot; - - public CmdUser(PurrBot bot){ - this.bot = bot; - } - - @Override - public void run(Guild guild, TextChannel tc, Message msg, Member member, String... args) { - Member target = msg.getMentions().getMembers().isEmpty() ? member : msg.getMentions().getMembers().get(0); - - EmbedBuilder embed = bot.getEmbedUtil().getEmbed(member) - .setThumbnail(target.getUser().getEffectiveAvatarUrl()) - .addField( - getName(target), - String.format( - "```yaml\n" + - "%s" + - "```", - getUserInfo(target) - ), - false - ) - .addField( - bot.getMsg(guild.getId(), "purr.info.user.embed.badges"), - getBadges(target), - true - ) - .addField( - bot.getMsg(guild.getId(), "purr.info.user.embed.avatar"), - MarkdownUtil.maskedLink( - bot.getMsg(guild.getId(), "purr.info.user.embed.avatar_url"), - target.getUser().getEffectiveAvatarUrl() - ), - true - ) - .addField( - bot.getMsg(guild.getId(), "purr.info.user.embed.role_highest"), - target.getRoles().isEmpty() ? bot.getMsg(guild.getId(), "purr.info.user.no_roles") : - target.getRoles().get(0).getAsMention(), - true - ) - .addField( - EmbedBuilder.ZERO_WIDTH_SPACE, - String.format( - "**%s**\n" + - "%s", - bot.getMsg(guild.getId(), "purr.info.user.embed.role_total"), - getRoles(target) - ), - false - ) - .addField( - EmbedBuilder.ZERO_WIDTH_SPACE, - getTimes(target), - false - ); - - tc.sendMessageEmbeds(embed.build()).queue(); - } - - private String getRoles(Member member){ - List roles = member.getRoles(); - - if(roles.size() <= 1) - return bot.getMsg(member.getGuild().getId(), "purr.info.user.no_roles_others"); - - StringBuilder sb = new StringBuilder("```\n"); - for(int i = 1; i < roles.size(); i++){ - Role role = roles.get(i); - String name = role.getName(); - - if(sb.length() + name.length() + 20 > MessageEmbed.VALUE_MAX_LENGTH){ - int rolesLeft = roles.size() - i; - - sb.append( - bot.getMsg(member.getGuild().getId(), "purr.info.user.more_roles") - .replace("{remaining}", String.valueOf(rolesLeft)) - ); - break; - } - - sb.append(name).append("\n"); - } - - sb.append("```"); - - return sb.toString(); - } - - private String getName(Member member){ - StringBuilder sb = new StringBuilder(MarkdownSanitizer.escape(member.getUser().getName())); - - if(member.isOwner()) - sb.append(" ").append(Emotes.OWNER.getEmote()); - - User user = member.getUser(); - if(user.isBot()) - if(user.getFlags().contains(User.UserFlag.VERIFIED_BOT)) - sb.append(" ").append(Emotes.VERIFIED_BOT_TAG_1.getEmote()).append(Emotes.VERIFIED_BOT_TAG_2.getEmote()); - else - sb.append(" ").append(Emotes.BOT_TAG_1.getEmote()).append(Emotes.BOT_TAG_2.getEmote()); - - return sb.toString(); - } - - private String getUserInfo(Member member){ - StringBuilder sb = new StringBuilder( - bot.getMsg(member.getGuild().getId(), "purr.info.user.embed.id") - .replace("{id}", member.getId()) - ); - - if(member.getNickname() != null){ - String nick = member.getNickname(); - sb.append("\n") - .append( - bot.getMsg(member.getGuild().getId(), "purr.info.user.embed.nickname") - .replace("{nickname}", nick.length() > 20 ? nick.substring(0, 19) + "..." : nick) - ); - } - - return sb.toString(); - } - - private String getTimes(Member member){ - StringBuilder sb = new StringBuilder(); - - sb.append(bot.getMsg(member.getGuild().getId(), "purr.info.user.embed.created")) - .append("\n") - .append(Emotes.BLANK.getEmote()) - .append(" ") - .append(bot.getMessageUtil().formatTime(member.getTimeCreated())) - .append("\n\n") - .append(bot.getMsg(member.getGuild().getId(), "purr.info.user.embed.joined")) - .append("\n") - .append(Emotes.BLANK.getEmote()) - .append(" ") - .append(bot.getMessageUtil().formatTime(member.getTimeJoined())); - - if(member.getTimeBoosted() != null) - sb.append("\n\n") - .append(bot.getMsg(member.getGuild().getId(), "purr.info.user.embed.booster")) - .append("\n") - .append(Emotes.BLANK.getEmote()) - .append(" ") - .append(bot.getMessageUtil().formatTime(member.getTimeBoosted())); - - return sb.toString(); - } - - private String getBadges(Member member){ - StringBuilder sb = new StringBuilder(); - - for(User.UserFlag flag : member.getUser().getFlags()){ - if(sb.length() > 0) - sb.append(" "); - - switch(flag){ - case STAFF: - sb.append(Emotes.STAFF.getEmote()); - break; - - case PARTNER: - sb.append(Emotes.PARTNER.getEmote()); - break; - - case HYPESQUAD: - sb.append(Emotes.HYPESQUAD_EVENTS.getEmote()); - break; - - case BUG_HUNTER_LEVEL_1: - sb.append(Emotes.BUGHUNTER.getEmote()); - break; - - case HYPESQUAD_BRAVERY: - sb.append(Emotes.HYPESQUAD_BRAVERY.getEmote()); - break; - - case HYPESQUAD_BRILLIANCE: - sb.append(Emotes.HYPESQUAD_BRILLIANCE.getEmote()); - break; - - case HYPESQUAD_BALANCE: - sb.append(Emotes.HYPESQUAD_BALANCE.getEmote()); - break; - - case EARLY_SUPPORTER: - sb.append(Emotes.EARLY_SUPPORTER.getEmote()); - break; - - case BUG_HUNTER_LEVEL_2: - sb.append(Emotes.BUGHUNTER_GOLD.getEmote()); - break; - - case VERIFIED_DEVELOPER: - sb.append(Emotes.EARLY_VERIFIED_BOT_DEV.getEmote()); - break; - - case CERTIFIED_MODERATOR: - sb.append(Emotes.CERTIFIED_MOD.getEmote()); - break; - } - } - - return sb.length() == 0 ? bot.getMsg(member.getGuild().getId(), "purr.info.user.embed.no_badges") : sb.toString(); - } -} diff --git a/src/main/java/site/purrbot/bot/commands/nsfw/CmdBlowjob.java b/src/main/java/site/purrbot/bot/commands/nsfw/CmdBlowjob.java deleted file mode 100644 index e0e641a87..000000000 --- a/src/main/java/site/purrbot/bot/commands/nsfw/CmdBlowjob.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Copyright 2018 - 2021 Andre601 - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated - * documentation files (the "Software"), to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, - * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or substantial - * portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package site.purrbot.bot.commands.nsfw; - -import com.github.rainestormee.jdacommand.CommandAttribute; -import com.github.rainestormee.jdacommand.CommandDescription; -import net.dv8tion.jda.api.entities.Guild; -import net.dv8tion.jda.api.entities.Member; -import net.dv8tion.jda.api.entities.Message; -import net.dv8tion.jda.api.entities.TextChannel; -import site.purrbot.bot.PurrBot; -import site.purrbot.bot.commands.Command; -import site.purrbot.bot.util.HttpUtil; - -@CommandDescription( - name = "Blowjob", - description = "purr.nsfw.blowjob.description", - triggers = {"blowjob", "bj", "bjob", "succ"}, - attributes = { - @CommandAttribute(key = "category", value = "nsfw"), - @CommandAttribute(key = "usage", value = "{p}blowjob <@user>"), - @CommandAttribute(key = "help", value = "{p}blowjob <@user>") - } -) -public class CmdBlowjob implements Command{ - - private final PurrBot bot; - - public CmdBlowjob(PurrBot bot){ - this.bot = bot; - } - - @Override - public void run(Guild guild, TextChannel tc, Message msg, Member member, String... args){ - if(msg.getMentions().getMembers().isEmpty()){ - bot.getEmbedUtil().sendError(tc, member, "purr.nsfw.blowjob.no_mention"); - return; - } - - Member target = msg.getMentions().getMembers().get(0); - - if(target.equals(guild.getSelfMember())){ - if(bot.isBeta()){ - if(bot.isSpecial(member.getId())){ - tc.sendMessage( - bot.getMsg(guild.getId(), "snuggle.nsfw.blowjob.special_user", member.getAsMention()) - ).queue(); - return; - } - tc.sendMessage( - bot.getMsg(guild.getId(), "snuggle.nsfw.blowjob.mention_snuggle", member.getAsMention()) - ).queue(); - }else{ - if(bot.isSpecial(member.getId())){ - tc.sendMessage( - bot.getMsg(guild.getId(), "purr.nsfw.blowjob.special_user", member.getAsMention()) - ).queue(); - return; - } - tc.sendMessage( - bot.getMsg(guild.getId(), "purr.nsfw.blowjob.mention_purr", member.getAsMention()) - ).queue(); - } - return; - } - - if(target.equals(member)){ - if(bot.isBeta()){ - tc.sendMessage( - bot.getMsg(guild.getId(), "snuggle.nsfw.blowjob.mention_self", member.getAsMention()) - ).queue(); - }else{ - tc.sendMessage( - bot.getMsg(guild.getId(), "purr.nsfw.blowjob.mention_self", member.getAsMention()) - ).queue(); - } - return; - } - - if(target.getUser().isBot()){ - bot.getEmbedUtil().sendError(tc, member, "purr.nsfw.blowjob.mention_bot"); - return; - } - - bot.getRequestUtil().handleButtonEvent(tc, member, target, HttpUtil.ImageAPI.NSFW_BLOWJOB); - } -} diff --git a/src/main/java/site/purrbot/bot/commands/nsfw/CmdCum.java b/src/main/java/site/purrbot/bot/commands/nsfw/CmdCum.java deleted file mode 100644 index 94965f086..000000000 --- a/src/main/java/site/purrbot/bot/commands/nsfw/CmdCum.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright 2018 - 2021 Andre601 - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated - * documentation files (the "Software"), to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, - * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or substantial - * portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package site.purrbot.bot.commands.nsfw; - -import com.github.rainestormee.jdacommand.CommandAttribute; -import com.github.rainestormee.jdacommand.CommandDescription; -import net.dv8tion.jda.api.entities.Guild; -import net.dv8tion.jda.api.entities.Member; -import net.dv8tion.jda.api.entities.Message; -import net.dv8tion.jda.api.entities.TextChannel; -import site.purrbot.bot.PurrBot; -import site.purrbot.bot.commands.Command; -import site.purrbot.bot.util.HttpUtil; - -@CommandDescription( - name = "Cum", - description = "purr.nsfw.cum.description", - triggers = {"cum", "cumming"}, - attributes = { - @CommandAttribute(key = "category", value = "nsfw"), - @CommandAttribute(key = "usage", value = - "{p}cum" - ), - @CommandAttribute(key = "help", value = "{p}cum") - } -) -public class CmdCum implements Command{ - - private final PurrBot bot; - - public CmdCum(PurrBot bot){ - this.bot = bot; - } - - @Override - public void run(Guild guild, TextChannel tc, Message msg, Member member, String... args){ - tc.sendMessage(bot.getMsg(guild.getId(), "purr.nsfw.cum.loading")).queue(message -> - bot.getRequestUtil().handleEdit(tc, message, HttpUtil.ImageAPI.NSFW_CUM, member) - ); - } -} diff --git a/src/main/java/site/purrbot/bot/commands/nsfw/CmdFuck.java b/src/main/java/site/purrbot/bot/commands/nsfw/CmdFuck.java deleted file mode 100644 index 6ab44a4de..000000000 --- a/src/main/java/site/purrbot/bot/commands/nsfw/CmdFuck.java +++ /dev/null @@ -1,354 +0,0 @@ -/* - * Copyright 2018 - 2021 Andre601 - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated - * documentation files (the "Software"), to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, - * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or substantial - * portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package site.purrbot.bot.commands.nsfw; - -import ch.qos.logback.classic.Logger; -import com.github.benmanes.caffeine.cache.Cache; -import com.github.benmanes.caffeine.cache.Caffeine; -import com.github.rainestormee.jdacommand.CommandAttribute; -import com.github.rainestormee.jdacommand.CommandDescription; -import com.jagrosh.jdautilities.commons.waiter.EventWaiter; -import net.dv8tion.jda.api.entities.*; -import net.dv8tion.jda.api.entities.emoji.Emoji; -import net.dv8tion.jda.api.events.interaction.component.ButtonInteractionEvent; -import net.dv8tion.jda.api.events.interaction.component.SelectMenuInteractionEvent; -import net.dv8tion.jda.api.interactions.components.selections.SelectMenu; -import net.dv8tion.jda.api.requests.restaction.MessageAction; -import org.slf4j.LoggerFactory; -import site.purrbot.bot.PurrBot; -import site.purrbot.bot.commands.Command; -import site.purrbot.bot.constants.Emotes; -import site.purrbot.bot.constants.IDs; -import site.purrbot.bot.util.HttpUtil; - -import java.util.Collections; -import java.util.Locale; -import java.util.concurrent.TimeUnit; - -@CommandDescription( - name = "Fuck", - description = "purr.nsfw.fuck.description", - triggers = {"fuck", "sex"}, - attributes = { - @CommandAttribute(key = "category", value = "nsfw"), - @CommandAttribute(key = "usage", value = - "{p}fuck <@user>\n" + - "{p}fuck <@user> --anal\n" + - "{p}fuck <@user> --normal\n" + - "{p}fuck <@user> --yaoi\n" + - "{p}fuck <@user> --yuri" - ), - @CommandAttribute(key = "help", value = "{p}fuck <@user> [--anal|--normal|--yaoi|--yuri]") - } -) -public class CmdFuck implements Command{ - - private final Logger logger = (Logger)LoggerFactory.getLogger(CmdFuck.class); - private final PurrBot bot; - - public CmdFuck(PurrBot bot){ - this.bot = bot; - } - - private final Cache queue = Caffeine.newBuilder() - .expireAfterWrite(2, TimeUnit.MINUTES) - .build(); - - @Override - public void run(Guild guild, TextChannel tc, Message msg, Member member, String... args){ - if(msg.getMentions().getUsers().isEmpty()){ - bot.getEmbedUtil().sendError(tc, member, "purr.nsfw.fuck.no_mention"); - return; - } - - Member target = msg.getMentions().getMembers().get(0); - - if(target.getId().equals(IDs.PURR)){ - if(bot.isBeta()){ - tc.sendMessage( - bot.getMsg(guild.getId(), "snuggle.nsfw.fuck.mention_purr", member.getAsMention()) - ).queue(); - }else{ - if(bot.isSpecial(member.getId())){ - int random = bot.getRandom().nextInt(10); - - if(random >= 1 && random <= 3){ - tc.sendMessage( - bot.getRandomMsg(guild.getId(), "purr.nsfw.fuck.special_user.accept", member.getAsMention()) - ).queue(); - }else{ - tc.sendMessage( - bot.getRandomMsg(guild.getId(), "purr.nsfw.fuck.special_user.deny", member.getAsMention()) - ).queue(); - } - }else{ - tc.sendMessage( - bot.getMsg(guild.getId(), "purr.nsfw.fuck.mention_purr", member.getAsMention()) - ).queue(); - } - } - return; - }else - if(target.getId().equals(IDs.SNUGGLE)){ - if(bot.isBeta()){ - tc.sendMessage( - bot.getMsg(guild.getId(), "snuggle.nsfw.fuck.mention_snuggle", member.getAsMention()) - ).queue(); - }else{ - tc.sendMessage( - bot.getMsg(guild.getId(), "purr.nsfw.fuck.mention_snuggle", member.getAsMention()) - ).queue(); - } - return; - } - - if(target.equals(member)){ - tc.sendMessage( - bot.getMsg(guild.getId(), "purr.nsfw.fuck.mention_self", member.getAsMention()) - ).queue(); - return; - } - - if(target.getUser().isBot()){ - bot.getEmbedUtil().sendError(tc, member, "purr.nsfw.fuck.mention_bot"); - return; - } - - if(queue.getIfPresent(bot.getRequestUtil().getQueueString("fuck", guild.getId(), member.getId())) != null){ - tc.sendMessage( - bot.getMsg(guild.getId(), "purr.nsfw.fuck.request.open", member.getAsMention()) - ).queue(); - return; - } - - String path = hasArgs(args) ? "purr.nsfw.fuck.request.message" : "purr.nsfw.fuck.request.message_choose"; - MessageAction messageAction = tc.sendMessage( - bot.getMsg(guild.getId(), path, member.getEffectiveName(), target.getAsMention()) - ); - - String guildId = guild.getId(); - if(hasArgs(args)){ - messageAction.setActionRow( - bot.getRequestUtil().getButton(guildId, "fuck", true), - bot.getRequestUtil().getButton(guildId, "fuck", false) - ).queue( - message -> handleButton(message, member, target, args), - e -> bot.getEmbedUtil().sendError(tc, member, "errors.request_error") - ); - }else{ - messageAction.setActionRow( - getSelectionMenu(guildId) - ).queue( - message -> handleSelection(message, member, target), - e -> bot.getEmbedUtil().sendError(tc, member, "errors.request_error") - ); - } - } - - private SelectMenu getSelectionMenu(String guildId){ - return SelectMenu.create("purr:fuck") - .addOption(bot.getMsg(guildId, "request.buttons.fuck_anal"), "anal", Emoji.fromFormatted(Emotes.SEX_ANAL.getEmote())) - .addOption(bot.getMsg(guildId, "request.buttons.fuck_normal"), "normal", Emoji.fromFormatted(Emotes.SEX.getEmote())) - .addOption(bot.getMsg(guildId, "request.buttons.fuck_yaoi"), "yaoi", Emoji.fromFormatted(Emotes.SEX_YAOI.getEmote())) - .addOption(bot.getMsg(guildId, "request.buttons.fuck_yuri"), "yuri", Emoji.fromFormatted(Emotes.SEX_YURI.getEmote())) - .addOption(bot.getMsg(guildId, "request.buttons.deny"), "deny", Emoji.fromFormatted(Emotes.DENY.getEmote())) - .build(); - } - - private boolean hasArgs(String... args){ - if(bot.getMessageUtil().hasArg("anal", args)){ - return true; - }else - if(bot.getMessageUtil().hasArg("normal", args) || bot.getMessageUtil().hasArg("hetero", args)){ - return true; - }else - if(bot.getMessageUtil().hasArg("yaoi", args)){ - return true; - }else{ - return bot.getMessageUtil().hasArg("yuri", args); - } - } - - private void handleSelection(Message botMsg, Member author, Member target){ - Guild guild = botMsg.getGuild(); - String channelId = botMsg.getChannel().getId(); - queue.put( - bot.getRequestUtil().getQueueString("fuck", guild.getId(), author.getId()), - target.getId() - ); - - bot.getWaiter().waitForEvent( - SelectMenuInteractionEvent.class, - event -> { - if(event.getUser().isBot()) - return false; - - if(event.getMember() == null) - return false; - - if(!event.getComponentId().equals("purr:fuck")) - return false; - - if(!event.isAcknowledged()) - event.deferEdit().queue(); - - if(event.getValues().size() > 1) - return false; - - if(!event.getMember().equals(target)) - return false; - - return event.getMessageId().equals(botMsg.getId()); - }, - event -> { - TextChannel channel = event.getChannel().asTextChannel(); - queue.invalidate(bot.getRequestUtil().getQueueString("fuck", guild.getId(), author.getId())); - - String value = event.getValues().get(0); - - if(value.equals("deny")){ - botMsg.delete().queue( - null, - e -> logger.warn("Could not delete own message for CmdFuck. Was it already deleted?") - ); - - channel.sendMessage( - bot.getMsg(guild.getId(), "purr.nsfw.fuck.request.denied", author.getAsMention(), target.getEffectiveName()) - ).queue(); - return; - } - - HttpUtil.ImageAPI api; - switch(value.toLowerCase(Locale.ROOT)){ - case "anal": - api = HttpUtil.ImageAPI.NSFW_ANAL; - break; - - default: - case "normal": - api = HttpUtil.ImageAPI.NSFW_FUCK; - break; - - case "yaoi": - api = HttpUtil.ImageAPI.NSFW_YAOI; - break; - - case "yuri": - api = HttpUtil.ImageAPI.NSFW_YURI; - break; - } - - bot.getRequestUtil().handleEdit(channel, botMsg, api, author, Collections.singletonList(target.getEffectiveName())); - }, 1, TimeUnit.MINUTES, - () -> { - TextChannel channel = guild.getTextChannelById(channelId); - if(channel == null) - return; - - botMsg.delete().queue( - null, - e -> logger.warn("Unable to delete own Message for fuck! Was it already deleted?") - ); - queue.invalidate(bot.getRequestUtil().getQueueString("fuck", guild.getId(), author.getId())); - - channel.sendMessage( - bot.getMsg(guild.getId(), "request.timed_out", author.getAsMention(), target.getEffectiveName()) - ).queue(); - } - ); - } - - private void handleButton(Message botMsg, Member author, Member target, String... args){ - Guild guild = botMsg.getGuild(); - String channelId = botMsg.getChannel().getId(); - queue.put( - bot.getRequestUtil().getQueueString("fuck", guild.getId(), author.getId()), - target.getId() - ); - - EventWaiter waiter = bot.getWaiter(); - waiter.waitForEvent( - ButtonInteractionEvent.class, - event -> { - if(event.getUser().isBot()) - return false; - - if(event.getMember() == null) - return false; - - if(!event.getComponentId().equals("purr:fuck:accept") && !event.getComponentId().equals("purr:fuck:deny")) - return false; - - if(!event.isAcknowledged()) - event.deferEdit().queue(); - - if(!event.getMember().equals(target)) - return false; - - return event.getMessageId().equals(botMsg.getId()); - }, - event -> { - TextChannel channel = event.getChannel().asTextChannel(); - queue.invalidate(bot.getRequestUtil().getQueueString("fuck", guild.getId(), author.getId())); - - String buttonId = event.getComponentId().split(":")[2]; - if(buttonId.equals("deny")){ - botMsg.delete().queue( - null, - e -> logger.warn("Could not delete own message for CmdFuck. Was it already deleted?") - ); - channel.sendMessage( - bot.getMsg(guild.getId(), "purr.nsfw.fuck.request.denied", author.getAsMention(), target.getEffectiveName()) - ).queue(); - return; - } - - HttpUtil.ImageAPI api; - if(bot.getMessageUtil().hasArg("anal", args)){ - api = HttpUtil.ImageAPI.NSFW_ANAL; - }else - if(bot.getMessageUtil().hasArg("yaoi", args)){ - api = HttpUtil.ImageAPI.NSFW_YAOI; - }else - if(bot.getMessageUtil().hasArg("yuri", args)){ - api = HttpUtil.ImageAPI.NSFW_YURI; - }else{ - api = HttpUtil.ImageAPI.NSFW_FUCK; - } - - bot.getRequestUtil().handleEdit(channel, botMsg, api, author, Collections.singletonList(target.getEffectiveName())); - }, 1, TimeUnit.MINUTES, - () -> { - TextChannel channel = guild.getTextChannelById(channelId); - if(channel == null) - return; - - botMsg.delete().queue( - null, - e -> logger.warn("Unable to delete own Message for fuck! Was it already deleted?") - ); - queue.invalidate(bot.getRequestUtil().getQueueString("fuck", guild.getId(), author.getId())); - - channel.sendMessage( - bot.getMsg(guild.getId(), "request.timed_out", author.getAsMention(), target.getEffectiveName()) - ).queue(); - } - ); - } -} diff --git a/src/main/java/site/purrbot/bot/commands/nsfw/CmdLewd.java b/src/main/java/site/purrbot/bot/commands/nsfw/CmdLewd.java deleted file mode 100644 index ef8a7eff9..000000000 --- a/src/main/java/site/purrbot/bot/commands/nsfw/CmdLewd.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright 2018 - 2021 Andre601 - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated - * documentation files (the "Software"), to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, - * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or substantial - * portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package site.purrbot.bot.commands.nsfw; - -import com.github.rainestormee.jdacommand.CommandAttribute; -import com.github.rainestormee.jdacommand.CommandDescription; -import net.dv8tion.jda.api.entities.Guild; -import net.dv8tion.jda.api.entities.Member; -import net.dv8tion.jda.api.entities.Message; -import net.dv8tion.jda.api.entities.TextChannel; -import site.purrbot.bot.PurrBot; -import site.purrbot.bot.commands.Command; -import site.purrbot.bot.util.HttpUtil; - -@CommandDescription( - name = "Lewd", - description = "purr.nsfw.lewd.description", - triggers = {"lewd", "lneko"}, - attributes = { - @CommandAttribute(key = "category", value = "nsfw"), - @CommandAttribute(key = "usage", value = "{p}lewd [--gif]"), - @CommandAttribute(key = "help", value = "{p}lewd [--gif]") - } -) -public class CmdLewd implements Command{ - - private final PurrBot bot; - - public CmdLewd(PurrBot bot){ - this.bot = bot; - } - - @Override - public void run(Guild guild, TextChannel tc, Message msg, Member member, String... args){ - tc.sendMessage(bot.getMsg(guild.getId(), "purr.nsfw.lewd.loading")).queue(message -> { - if(bot.getMessageUtil().hasArg("gif", args)){ - bot.getRequestUtil().handleEdit(tc, message, HttpUtil.ImageAPI.NSFW_NEKO_GIF, member); - }else{ - bot.getRequestUtil().handleEdit(tc, message, HttpUtil.ImageAPI.NSFW_NEKO_IMG, member); - } - }); - } -} diff --git a/src/main/java/site/purrbot/bot/commands/nsfw/CmdPussylick.java b/src/main/java/site/purrbot/bot/commands/nsfw/CmdPussylick.java deleted file mode 100644 index 01ba96855..000000000 --- a/src/main/java/site/purrbot/bot/commands/nsfw/CmdPussylick.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright 2018 - 2021 Andre601 - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated - * documentation files (the "Software"), to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, - * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or substantial - * portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package site.purrbot.bot.commands.nsfw; - -import com.github.rainestormee.jdacommand.CommandAttribute; -import com.github.rainestormee.jdacommand.CommandDescription; -import net.dv8tion.jda.api.entities.Guild; -import net.dv8tion.jda.api.entities.Member; -import net.dv8tion.jda.api.entities.Message; -import net.dv8tion.jda.api.entities.TextChannel; -import site.purrbot.bot.PurrBot; -import site.purrbot.bot.commands.Command; -import site.purrbot.bot.util.HttpUtil; - -@CommandDescription( - name = "PussyLick", - description = "purr.nsfw.pussylick.description", - triggers = {"pussylick", "plick", "cunni"}, - attributes = { - @CommandAttribute(key = "category", value = "nsfw"), - @CommandAttribute(key = "usage", value = "{p}plick <@user>"), - @CommandAttribute(key = "help", value = "{p}plick <@user>") - } -) -public class CmdPussylick implements Command{ - - private final PurrBot bot; - - public CmdPussylick(PurrBot bot){ - this.bot = bot; - } - - @Override - public void run(Guild guild, TextChannel tc, Message msg, Member member, String... args){ - if(msg.getMentions().getUsers().isEmpty()){ - bot.getEmbedUtil().sendError(tc, member, "purr.nsfw.pussylick.no_mention"); - return; - } - - Member target = msg.getMentions().getMembers().get(0); - - if(target.equals(guild.getSelfMember())){ - if(bot.isBeta()){ - tc.sendMessage( - bot.getMsg(guild.getId(), "snuggle.nsfw.pussylick.mention_snuggle", member.getAsMention()) - ).queue(); - return; - }else{ - if(bot.isSpecial(member.getId())){ - tc.sendMessage( - bot.getMsg(guild.getId(), "purr.nsfw.pussylick.special_user", member.getAsMention()) - ).queue(); - return; - } - } - tc.sendMessage( - bot.getMsg(guild.getId(), "purr.nsfw.pussylick.mention_purr", member.getAsMention()) - ).queue(); - return; - } - - if(target.equals(member)){ - tc.sendMessage( - bot.getMsg(guild.getId(), "purr.nsfw.pussylick.mention_self", member.getAsMention()) - ).queue(); - return; - } - - if(target.getUser().isBot()){ - bot.getEmbedUtil().sendError(tc, member, "purr.nsfw.pussylick.mention_bot"); - return; - } - - bot.getRequestUtil().handleButtonEvent(tc, member, target, HttpUtil.ImageAPI.NSFW_PUSSYLICK); - } -} diff --git a/src/main/java/site/purrbot/bot/commands/nsfw/CmdSolo.java b/src/main/java/site/purrbot/bot/commands/nsfw/CmdSolo.java deleted file mode 100644 index fe3646e78..000000000 --- a/src/main/java/site/purrbot/bot/commands/nsfw/CmdSolo.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright 2018 - 2021 Andre601 - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated - * documentation files (the "Software"), to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, - * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or substantial - * portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package site.purrbot.bot.commands.nsfw; - -import com.github.rainestormee.jdacommand.CommandAttribute; -import com.github.rainestormee.jdacommand.CommandDescription; -import net.dv8tion.jda.api.entities.Guild; -import net.dv8tion.jda.api.entities.Member; -import net.dv8tion.jda.api.entities.Message; -import net.dv8tion.jda.api.entities.TextChannel; -import site.purrbot.bot.PurrBot; -import site.purrbot.bot.commands.Command; -import site.purrbot.bot.util.HttpUtil; - -@CommandDescription( - name = "Solo", - description = "purr.nsfw.solo.description", - triggers = {"solo", "girl"}, - attributes = { - @CommandAttribute(key = "category", value = "nsfw"), - @CommandAttribute(key = "usage", value = "{p}solo"), - @CommandAttribute(key = "help", value = "{p}solo") - } -) -public class CmdSolo implements Command{ - - private final PurrBot bot; - - public CmdSolo(PurrBot bot){ - this.bot = bot; - } - - @Override - public void run(Guild guild, TextChannel tc, Message msg, Member member, String... args){ - tc.sendMessage(bot.getMsg(guild.getId(), "purr.nsfw.solo.loading")).queue(message -> - bot.getRequestUtil().handleEdit(tc, message, HttpUtil.ImageAPI.NSFW_SOLO, member) - ); - } -} diff --git a/src/main/java/site/purrbot/bot/commands/nsfw/CmdSpank.java b/src/main/java/site/purrbot/bot/commands/nsfw/CmdSpank.java deleted file mode 100644 index 588327fc9..000000000 --- a/src/main/java/site/purrbot/bot/commands/nsfw/CmdSpank.java +++ /dev/null @@ -1,120 +0,0 @@ -/* - * Copyright 2018 - 2021 Andre601 - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated - * documentation files (the "Software"), to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, - * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or substantial - * portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package site.purrbot.bot.commands.nsfw; - -import com.github.rainestormee.jdacommand.CommandAttribute; -import com.github.rainestormee.jdacommand.CommandDescription; -import net.dv8tion.jda.api.entities.Guild; -import net.dv8tion.jda.api.entities.Member; -import net.dv8tion.jda.api.entities.Message; -import net.dv8tion.jda.api.entities.TextChannel; -import site.purrbot.bot.PurrBot; -import site.purrbot.bot.commands.Command; -import site.purrbot.bot.constants.IDs; -import site.purrbot.bot.util.HttpUtil; - -@CommandDescription( - name = "Spank", - description = "purr.nsfw.spank.description", - triggers = {"spank", "spanking"}, - attributes = { - @CommandAttribute(key = "category", value = "nsfw"), - @CommandAttribute(key = "usage", value = "{p}spank <@user>"), - @CommandAttribute(key = "help", value = "{p}spank <@user>") - } -) -public class CmdSpank implements Command{ - - private final PurrBot bot; - - public CmdSpank(PurrBot bot){ - this.bot = bot; - } - - @Override - public void run(Guild guild, TextChannel tc, Message msg, Member member, String... args){ - if(msg.getMentions().getMembers().isEmpty()){ - bot.getEmbedUtil().sendError(tc, member, "purr.nsfw.spank.no_mention"); - return; - } - - Member target = msg.getMentions().getMembers().get(0); - if(isPurrOrSnuggle(target.getId(), member, tc)) - return; - - if(target.equals(member)){ - tc.sendMessage( - bot.getMsg(guild.getId(), "purr.nsfw.spank.mention_self", member.getAsMention()) - ).queue(); - return; - } - - if(target.getUser().isBot()){ - tc.sendMessage( - bot.getMsg(guild.getId(), "purr.nsfw.spank.mention_bot", member.getAsMention()) - ).queue(); - return; - } - - bot.getRequestUtil().handleButtonEvent(tc, member, target, HttpUtil.ImageAPI.NSFW_SPANK); - } - - private boolean isPurrOrSnuggle(String memberId, Member member, TextChannel tc){ - Guild guild = tc.getGuild(); - if(memberId.equals(IDs.PURR)){ - if(bot.isBeta()){ - if(bot.isSpecial(member.getId())){ - tc.sendMessage( - bot.getMsg(guild.getId(), "snuggle.nsfw.spank.special_user", member.getAsMention()) - ).queue(); - return true; - } - tc.sendMessage( - bot.getMsg(guild.getId(), "snuggle.nsfw.spank.mention_purr", member.getAsMention()) - ).queue(); - }else{ - if(bot.isSpecial(member.getId())){ - tc.sendMessage( - bot.getMsg(guild.getId(), "purr.nsfw.spank.special_user", member.getAsMention()) - ).queue(); - return true; - } - tc.sendMessage( - bot.getMsg(guild.getId(), "purr.nsfw.spank.mention_purr", member.getAsMention()) - ).queue(); - } - return true; - } - - if(memberId.equals(IDs.SNUGGLE)){ - if(bot.isBeta()){ - tc.sendMessage( - bot.getMsg(guild.getId(), "snuggle.nsfw.spank.mention_snuggle", member.getAsMention()) - ).queue(); - }else{ - tc.sendMessage( - bot.getMsg(guild.getId(), "purr.nsfw.spank.mention_snuggle", member.getAsMention()) - ).queue(); - } - return true; - } - - return false; - } -} diff --git a/src/main/java/site/purrbot/bot/commands/nsfw/CmdThreesome.java b/src/main/java/site/purrbot/bot/commands/nsfw/CmdThreesome.java deleted file mode 100644 index d80f90e01..000000000 --- a/src/main/java/site/purrbot/bot/commands/nsfw/CmdThreesome.java +++ /dev/null @@ -1,227 +0,0 @@ -/* - * Copyright 2018 - 2021 Andre601 - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated - * documentation files (the "Software"), to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, - * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or substantial - * portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package site.purrbot.bot.commands.nsfw; - -import ch.qos.logback.classic.Logger; -import com.github.benmanes.caffeine.cache.Cache; -import com.github.benmanes.caffeine.cache.Caffeine; -import com.github.rainestormee.jdacommand.CommandAttribute; -import com.github.rainestormee.jdacommand.CommandDescription; -import com.jagrosh.jdautilities.commons.waiter.EventWaiter; -import net.dv8tion.jda.api.entities.*; -import net.dv8tion.jda.api.events.interaction.component.ButtonInteractionEvent; -import org.slf4j.LoggerFactory; -import site.purrbot.bot.PurrBot; -import site.purrbot.bot.commands.Command; -import site.purrbot.bot.util.HttpUtil; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.concurrent.TimeUnit; - -@CommandDescription( - name = "Threesome", - description = "purr.nsfw.threesome.description", - triggers = {"threesome", "3some"}, - attributes = { - @CommandAttribute(key = "category", value = "nsfw"), - @CommandAttribute(key = "usage", value = - "{p}threesome <@user1> <@user2>\n" + - "{p}threesome <@user1> <@user2> --fff\n" + - "{p}threesome <@user1> <@user2> --mmf" - ), - @CommandAttribute(key = "help", value = "{p}threesome <@user1> <@user2> [--fff|--mmf]") - } -) -public class CmdThreesome implements Command{ - - private final Logger logger = (Logger)LoggerFactory.getLogger(CmdThreesome.class); - private final PurrBot bot; - - public CmdThreesome(PurrBot bot){ - this.bot = bot; - } - - private final Cache queue = Caffeine.newBuilder() - .expireAfterWrite(2, TimeUnit.MINUTES) - .build(); - - @Override - public void run(Guild guild, TextChannel tc, Message msg, Member member, String... args){ - if(msg.getMentions().getMembers().isEmpty() || msg.getMentions().getMembers().size() < 2){ - bot.getEmbedUtil().sendError(tc, member, "purr.nsfw.threesome.no_mention"); - return; - } - - Member target1 = msg.getMentions().getMembers().get(0); - Member target2 = msg.getMentions().getMembers().get(1); - - if(target1.equals(guild.getSelfMember()) || target2.equals(guild.getSelfMember())){ - if(bot.isBeta()){ - tc.sendMessage( - bot.getMsg(guild.getId(), "snuggle.nsfw.threesome.mention_snuggle", member.getAsMention()) - ).queue(); - return; - }else{ - if(bot.isSpecial(member.getId())){ - tc.sendMessage( - bot.getMsg(guild.getId(), "purr.nsfw.threesome.special_user", member.getAsMention()) - ).queue(); - return; - } - } - tc.sendMessage( - bot.getMsg(guild.getId(), "purr.nsfw.threesome.mention_purr", member.getAsMention()) - ).queue(); - return; - } - - if(target1.equals(member) || target2.equals(member)){ - tc.sendMessage( - bot.getMsg(guild.getId(), "purr.nsfw.threesome.mention_self", member.getAsMention()) - ).queue(); - return; - } - - if(target1.getUser().isBot() || target2.getUser().isBot()){ - tc.sendMessage( - bot.getMsg(guild.getId(), "purr.nsfw.threesome.mention_bot", member.getAsMention()) - ).queue(); - return; - } - - if(queue.getIfPresent(bot.getRequestUtil().getQueueString("threesome", guild.getId(), member.getId())) != null){ - tc.sendMessage( - bot.getMsg(guild.getId(), "purr.nsfw.threesome.request.open", member.getAsMention()) - ).queue(); - return; - } - - tc.sendMessage( - bot.getMsg(guild.getId(), "purr.nsfw.threesome.request.message", member.getEffectiveName()) - .replace("{target1}", target1.getAsMention()) - .replace("{target2}", target2.getAsMention()) - ).setActionRow( - bot.getRequestUtil().getButton(guild.getId(), "threesome", true), - bot.getRequestUtil().getButton(guild.getId(), "threesome", false) - ).queue( - message -> handleEvent(message, member, target1, target2, args), - e -> bot.getEmbedUtil().sendError(tc, member, "errors.request_error") - ); - } - - private boolean allUser(List list, String id, String buttonId){ - if(buttonId.equals("purr:threesome:deny")) - return true; - - if(!buttonId.equals("purr:threesome:accept")) - return false; - - list.remove(id); - - return list.isEmpty(); - } - - public void handleEvent(Message botMsg, Member author, Member target1, Member target2, String... args){ - Guild guild = botMsg.getGuild(); - List list = new ArrayList<>(); - list.add(target1.getId()); - list.add(target2.getId()); - - queue.put( - bot.getRequestUtil().getQueueString("threesome", guild.getId(), author.getId()), - String.format("%s:%s", target1.getId(), target2.getId()) - ); - - EventWaiter waiter = bot.getWaiter(); - waiter.waitForEvent( - ButtonInteractionEvent.class, - event -> { - if(event.getUser().isBot()) - return false; - - if(event.getMember() == null) - return false; - - if(!event.getMember().equals(target1) && !event.getMember().equals(target2)) - return false; - - if(!event.getMessageId().equals(botMsg.getId())) - return false; - - if(!event.isAcknowledged()) - event.deferEdit().queue(); - - return allUser(list, event.getUser().getId(), event.getComponentId()); - }, - event -> { - TextChannel channel = event.getGuildChannel().asTextChannel(); - queue.invalidate(bot.getRequestUtil().getQueueString("threesome", guild.getId(), author.getId())); - - if(event.getComponentId().equals("purr:threesome:deny")){ - list.remove(target1.getId()); - list.remove(target2.getId()); - - botMsg.delete().queue( - null, - e -> logger.warn("Unable to delete own Message for threesome! Was it already deleted?") - ); - - channel.sendMessage( - bot.getMsg(guild.getId(), "purr.nsfw.threesome.request.denied", author.getAsMention()) - .replace("{target1}", target1.getEffectiveName()) - .replace("{target2}", target2.getEffectiveName()) - ).queue(); - }else{ - List targets = Arrays.asList(target1.getEffectiveName(), target2.getEffectiveName()); - - HttpUtil.ImageAPI api; - if(bot.getMessageUtil().hasArg("mmf", args)){ - api = HttpUtil.ImageAPI.NSFW_THREESOME_MMF; - }else - if(bot.getMessageUtil().hasArg("fff", args)){ - api = HttpUtil.ImageAPI.NSFW_THREESOME_FFF; - }else{ - api = HttpUtil.ImageAPI.NSFW_THREESOME_FFM; - } - - bot.getRequestUtil().handleEdit(channel, botMsg, api, author, targets); - } - }, 1, TimeUnit.MINUTES, - () -> { - TextChannel channel = botMsg.getChannel().asTextChannel(); - botMsg.delete().queue( - null, - e -> logger.warn("Unable to delete own Message for Threesome! Was it already deleted?") - ); - queue.invalidate(bot.getRequestUtil().getQueueString("threesome", guild.getId(), author.getId())); - - list.remove(target1.getId()); - list.remove(target2.getId()); - - List targets = Arrays.asList(target1.getEffectiveName(), target2.getEffectiveName()); - - channel.sendMessage( - bot.getMsg(guild.getId(), "request.timed_out", author.getAsMention(), targets) - ).queue(); - } - ); - } -} diff --git a/src/main/java/site/purrbot/bot/commands/owner/CmdCheck.java b/src/main/java/site/purrbot/bot/commands/owner/CmdCheck.java deleted file mode 100644 index da8bcd972..000000000 --- a/src/main/java/site/purrbot/bot/commands/owner/CmdCheck.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright 2018 - 2021 Andre601 - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated - * documentation files (the "Software"), to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, - * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or substantial - * portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package site.purrbot.bot.commands.owner; - -import com.github.rainestormee.jdacommand.CommandAttribute; -import com.github.rainestormee.jdacommand.CommandDescription; -import net.dv8tion.jda.api.JDA; -import net.dv8tion.jda.api.entities.Guild; -import net.dv8tion.jda.api.entities.Member; -import net.dv8tion.jda.api.entities.Message; -import net.dv8tion.jda.api.entities.TextChannel; -import site.purrbot.bot.PurrBot; -import site.purrbot.bot.commands.Command; -import site.purrbot.bot.constants.Emotes; - -import java.util.ArrayList; -import java.util.Comparator; -import java.util.List; - -@CommandDescription( - name = "Check", - description = - "Checks the Shards and prints their status.", - triggers = {"check"}, - attributes = { - @CommandAttribute(key = "category", value = "owner"), - @CommandAttribute(key = "usage", value = "{p}check"), - @CommandAttribute(key = "help", value = "{p}check") - } -) -public class CmdCheck implements Command{ - - private final PurrBot bot; - - public CmdCheck(PurrBot bot){ - this.bot = bot; - } - - @Override - public void run(Guild guild, TextChannel tc, Message msg, Member member, String... args){ - tc.sendMessage(String.format( - "%s Performing Status checks on Shards. Please wait...", - Emotes.TYPING.getEmote() - )).queue(this::checkShards); - } - - private void checkShards(Message msg){ - List shards = new ArrayList<>(bot.getShardManager().getShards()); - StringBuilder builder = new StringBuilder("```"); - int checkedShards = 0; - - shards.sort(Comparator.comparing(jda -> jda.getShardInfo().getShardId())); - - for(JDA shard : shards){ - if(builder.length() + getShardStatus(shard).length() > Message.MAX_CONTENT_LENGTH){ - builder.append("\n```"); - msg.getChannel().asTextChannel().sendMessage(builder.toString()).queue(); - builder = new StringBuilder("```"); - } - - builder.append(getShardStatus(shard)); - checkedShards++; - - if(checkedShards == shards.size()) - msg.editMessage(String.format("%s Status Check complete!", Emotes.ACCEPT.getEmote())).queue(); - - } - - if(builder.length() > 0){ - String text = builder.toString(); - if(!text.endsWith("```")) - text += "\n```"; - - msg.getChannel().asTextChannel().sendMessage(text).queue(); - } - } - - private String getShardStatus(JDA jda){ - return String.format("\nShard %2d [Status: %s]", jda.getShardInfo().getShardId(), jda.getStatus().name()); - } -} diff --git a/src/main/java/site/purrbot/bot/commands/owner/CmdEval.java b/src/main/java/site/purrbot/bot/commands/owner/CmdEval.java deleted file mode 100644 index 28dca3c89..000000000 --- a/src/main/java/site/purrbot/bot/commands/owner/CmdEval.java +++ /dev/null @@ -1,122 +0,0 @@ -/* - * Copyright 2018 - 2021 Andre601 - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated - * documentation files (the "Software"), to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, - * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or substantial - * portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package site.purrbot.bot.commands.owner; - -import com.github.rainestormee.jdacommand.CommandAttribute; -import com.github.rainestormee.jdacommand.CommandDescription; -import net.dv8tion.jda.api.EmbedBuilder; -import net.dv8tion.jda.api.Permission; -import net.dv8tion.jda.api.entities.Guild; -import net.dv8tion.jda.api.entities.Member; -import net.dv8tion.jda.api.entities.Message; -import net.dv8tion.jda.api.entities.TextChannel; -import site.purrbot.bot.PurrBot; -import site.purrbot.bot.commands.Command; - -import javax.script.ScriptEngine; -import javax.script.ScriptEngineManager; -import javax.script.ScriptException; - -@CommandDescription( - name = "Eval", - description = "Evaluates code... I guess.", - triggers = {"eval"}, - attributes = { - @CommandAttribute(key = "category", value = "owner"), - @CommandAttribute(key = "usage", value = "{p}eval "), - @CommandAttribute(key = "help", value = "{p}eval ") - } -) -public class CmdEval implements Command{ - - private final PurrBot bot; - - public CmdEval(PurrBot bot){ - this.bot = bot; - } - - @Override - public void run(Guild guild, TextChannel tc, Message msg, Member member, String... args) { - if(msg.getGuild().getSelfMember().hasPermission(tc, Permission.MESSAGE_MANAGE)) - msg.delete().queue(); - - if(args.length == 0){ - bot.getEmbedUtil().sendError(tc, member, "I need at least one argument!"); - return; - } - - ScriptEngine se = new ScriptEngineManager().getEngineByName("Nashorn"); - - se.put("jda", msg.getJDA()); - se.put("shardManager", bot.getShardManager()); - se.put("guild", guild); - se.put("channel", tc); - se.put("msg", msg); - se.put("embed", bot.getEmbedUtil().getEmbed().setTimestamp(null)); - - String statement = String.join(" ", args); - - long startTime = System.currentTimeMillis(); - - try{ - String result = se.eval(statement).toString(); - - sendEvalEmbed(tc, statement, result, String.format( - "Evaluated in %dms", - System.currentTimeMillis() - startTime - ), true); - }catch(ScriptException ex){ - sendEvalEmbed(tc, statement, ex.getMessage(), String.format( - "Evaluated in %dms", - System.currentTimeMillis() - startTime - ), false); - } - } - - private void sendEvalEmbed(TextChannel tc, String input, String output, String footer, boolean success){ - String newMsg = input; - - String overflow = null; - - if(newMsg.length() > 2000){ - overflow = newMsg.substring(1999); - newMsg = newMsg.substring(0, 1999); - } - - EmbedBuilder embed = bot.getEmbedUtil().getEmbed() - .setColor(success ? 0x00FF00 : 0xFF0000) - .addField("Input", String.format( - "```java\n" + - "%s\n" + - "```", - newMsg - ), false) - .addField("Output", String.format( - "```java\n" + - "%s\n" + - "```", - output - ), false) - .setFooter(footer, null); - - tc.sendMessageEmbeds(embed.build()).queue(); - if(overflow != null) - sendEvalEmbed(tc, overflow, output, footer, success); - } -} diff --git a/src/main/java/site/purrbot/bot/commands/owner/CmdLeave.java b/src/main/java/site/purrbot/bot/commands/owner/CmdLeave.java deleted file mode 100644 index 94869c636..000000000 --- a/src/main/java/site/purrbot/bot/commands/owner/CmdLeave.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright 2018 - 2021 Andre601 - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated - * documentation files (the "Software"), to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, - * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or substantial - * portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package site.purrbot.bot.commands.owner; - -import com.github.rainestormee.jdacommand.CommandAttribute; -import com.github.rainestormee.jdacommand.CommandDescription; -import net.dv8tion.jda.api.entities.Guild; -import net.dv8tion.jda.api.entities.Member; -import net.dv8tion.jda.api.entities.Message; -import net.dv8tion.jda.api.entities.TextChannel; -import site.purrbot.bot.PurrBot; -import site.purrbot.bot.commands.Command; - -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -@CommandDescription( - name = "Leave", - description = - "Let the bot leave a Guild.\n" + - "Use `--pm` to send an optional PM to Guild Owner", - triggers = {"leave", "bye"}, - attributes = { - @CommandAttribute(key = "category", value = "owner"), - @CommandAttribute(key = "usage", value = "{p}leave [--pm ]"), - @CommandAttribute(key = "help", value = "{p}leave [--pm ]") - } -) -public class CmdLeave implements Command{ - - Pattern pattern = Pattern.compile("--pm (?.+)", Pattern.DOTALL); - - private final PurrBot bot; - - public CmdLeave(PurrBot bot){ - this.bot = bot; - } - - @Override - public void run(Guild guild, TextChannel tc, Message msg, Member member, String... args) { - String pm = null; - - String s = msg.getContentRaw(); - Matcher matcher = pattern.matcher(s); - if(matcher.find()) - pm = matcher.group("message"); - - String id = args[0]; - - final String finalPm = pm; - Guild targetGuild = bot.getShardManager().getGuildById(id); - - if(targetGuild == null) - return; - - Member owner = targetGuild.getOwner(); - if(owner == null){ - targetGuild.leave().queue(); - return; - } - - owner.getUser().openPrivateChannel() - .flatMap( - channel -> channel.sendMessage(String.format( - "I left your Discord `%s` for the following reason:\n" + - "```\n" + - "%s\n" + - "```", - targetGuild.getName(), - finalPm == null ? "No reason given" : finalPm - )) - ) - .queue( - message -> targetGuild.leave().queue(), - throwable -> targetGuild.leave().queue() - ); - } -} diff --git a/src/main/java/site/purrbot/bot/commands/owner/CmdListEmotes.java b/src/main/java/site/purrbot/bot/commands/owner/CmdListEmotes.java deleted file mode 100644 index 26d7c61e5..000000000 --- a/src/main/java/site/purrbot/bot/commands/owner/CmdListEmotes.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Copyright 2018 - 2021 Andre601 - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated - * documentation files (the "Software"), to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, - * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or substantial - * portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package site.purrbot.bot.commands.owner; - -import com.github.rainestormee.jdacommand.CommandAttribute; -import com.github.rainestormee.jdacommand.CommandDescription; -import net.dv8tion.jda.api.entities.*; -import net.dv8tion.jda.api.entities.emoji.CustomEmoji; -import net.dv8tion.jda.api.entities.emoji.Emoji; -import net.dv8tion.jda.api.entities.emoji.RichCustomEmoji; -import site.purrbot.bot.PurrBot; -import site.purrbot.bot.commands.Command; -import site.purrbot.bot.constants.Emotes; - -import java.util.ArrayList; -import java.util.Comparator; -import java.util.List; - -@CommandDescription( - name = "Listemotes", - description = "Lists all emotes the bot uses", - triggers = {"listemotes", "le"}, - attributes = { - @CommandAttribute(key = "category", value = "owner"), - @CommandAttribute(key = "usage", value = "{p}listemotes"), - @CommandAttribute(key = "help", value = "{p}listemotes") - } -) -public class CmdListEmotes implements Command{ - - private final PurrBot bot; - - public CmdListEmotes(PurrBot bot){ - this.bot = bot; - } - - @Override - public void run(Guild guild, TextChannel tc, Message msg, Member member, String... args){ - if(args.length == 0){ - msg.addReaction(Emoji.fromFormatted(Emotes.DENY.getEmote())).queue(); - return; - } - - Guild targetGuild = bot.getShardManager().getGuildById(args[0]); - if(targetGuild == null){ - msg.addReaction(Emoji.fromFormatted(Emotes.DENY.getEmote())).queue(); - return; - } - - List emotes = new ArrayList<>(targetGuild.getEmojis()); - emotes.sort(Comparator.comparing(RichCustomEmoji::getName)); - - StringBuilder builder = new StringBuilder(String.format( - "Emotes for Guild %s (%d emotes)\n" + - "\n", - targetGuild.getName(), - emotes.size() - )); - int i = 0; - for(RichCustomEmoji emote : emotes){ - if(emote.isAnimated()) - continue; - - i++; - if(builder.length() + getEmoteString(emote).length() + 100 > Message.MAX_CONTENT_LENGTH){ - tc.sendMessageFormat( - "```\n" + - "%s\n" + - "```", - builder.toString() - ).queue(); - - builder.setLength(0); - } - - if(builder.length() > 0) - builder.append("\n"); - - builder.append(getEmoteString(emote)); - - if(i % 10 == 0) - builder.append("\n"); - } - - tc.sendMessageFormat( - "```\n" + - "%s\n" + - "```", - builder.toString() - ).queue(); - } - - private String getEmoteString(RichCustomEmoji emote){ - return String.format( - "%s `:%s: - %s`", - emote.getAsMention(), - emote.getName(), - emote.getAsMention() - ); - } -} diff --git a/src/main/java/site/purrbot/bot/commands/owner/CmdMsg.java b/src/main/java/site/purrbot/bot/commands/owner/CmdMsg.java deleted file mode 100644 index c3dc21d44..000000000 --- a/src/main/java/site/purrbot/bot/commands/owner/CmdMsg.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright 2018 - 2021 Andre601 - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated - * documentation files (the "Software"), to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, - * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or substantial - * portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package site.purrbot.bot.commands.owner; - -import com.github.rainestormee.jdacommand.CommandAttribute; -import com.github.rainestormee.jdacommand.CommandDescription; -import net.dv8tion.jda.api.entities.*; -import net.dv8tion.jda.api.entities.emoji.Emoji; -import site.purrbot.bot.PurrBot; -import site.purrbot.bot.commands.Command; -import site.purrbot.bot.constants.Emotes; - -@CommandDescription( - name = "Message", - description = "Sends a message as the bot to the specified channel", - triggers = {"msg", "message", "send"}, - attributes = { - @CommandAttribute(key = "category", value = "owner"), - @CommandAttribute(key = "usage", value = "{p}msg "), - @CommandAttribute(key = "help", value = "{p}msg ") - } -) -public class CmdMsg implements Command{ - - private final PurrBot bot; - - public CmdMsg(PurrBot bot){ - this.bot = bot; - } - - @Override - public void run(Guild guild, TextChannel tc, Message msg, Member member, String... args) { - if(args.length <= 1){ - msg.addReaction(Emoji.fromFormatted(Emotes.DENY.getEmote())).queue(); - return; - } - - TextChannel channel = bot.getShardManager().getTextChannelById(args[0]); - if(channel == null){ - msg.addReaction(Emoji.fromFormatted(Emotes.DENY.getEmote())).queue(); - return; - } - - if(args[1].equalsIgnoreCase("msg")){ - String content = args[2].replaceAll("\\{#(\\d+)}", "<#$1>"); - - channel.sendMessage(content).queue( - message -> msg.addReaction(Emoji.fromFormatted(Emotes.ACCEPT.getEmote())).queue(), - failure -> msg.addReaction(Emoji.fromFormatted(Emotes.DENY.getEmote())).queue() - ); - }else - if(args[1].equalsIgnoreCase("edit")){ - String msgId = args[2].split("\\s+")[0]; - - Message message = channel.retrieveMessageById(msgId).complete(); - if(message == null || !message.getAuthor().equals(guild.getSelfMember().getUser())){ - tc.sendMessage("Invalid message! It was either null or I'm not the author of it.").queue( - m -> msg.addReaction(Emoji.fromFormatted(Emotes.DENY.getEmote())).queue() - ); - return; - } - - String content = args[2].substring(msgId.length() + 1).replaceAll("\\{#(\\d+)}", "<#$1>"); - message.editMessage(content).queue( - m -> msg.addReaction(Emoji.fromFormatted(Emotes.ACCEPT.getEmote())).queue(), - failure -> msg.addReaction(Emoji.fromFormatted(Emotes.DENY.getEmote())).queue()); - }else - if(args[1].equalsIgnoreCase("embed")){ - String content = args[2].replaceAll("\\{#(\\d+)}", "<#$1>"); - - MessageEmbed embed = bot.getEmbedUtil().getEmbed() - .setTimestamp(null) - .setDescription(content) - .build(); - - channel.sendMessageEmbeds(embed).queue(); - }else{ - tc.sendMessage("Invalid message type! Allowed are `msg`, `edit` and `embed`").queue(); - } - } -} diff --git a/src/main/java/site/purrbot/bot/commands/owner/CmdShutdown.java b/src/main/java/site/purrbot/bot/commands/owner/CmdShutdown.java deleted file mode 100644 index a95c9d3c9..000000000 --- a/src/main/java/site/purrbot/bot/commands/owner/CmdShutdown.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright 2018 - 2021 Andre601 - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated - * documentation files (the "Software"), to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, - * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or substantial - * portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package site.purrbot.bot.commands.owner; - -import ch.qos.logback.classic.Logger; -import com.github.rainestormee.jdacommand.CommandAttribute; -import com.github.rainestormee.jdacommand.CommandDescription; -import net.dv8tion.jda.api.Permission; -import net.dv8tion.jda.api.entities.*; -import org.slf4j.LoggerFactory; -import site.purrbot.bot.PurrBot; -import site.purrbot.bot.commands.Command; - -@CommandDescription( - name = "Shutdown", - description = "Disables the bot", - triggers = {"shutdown", "sleep"}, - attributes = { - @CommandAttribute(key = "category", value = "owner"), - @CommandAttribute(key = "usage", value = "{p}shutdown"), - @CommandAttribute(key = "help", value = "{p}shutdown") - } -) -public class CmdShutdown implements Command{ - - private final PurrBot bot; - private final Logger logger = (Logger)LoggerFactory.getLogger(CmdShutdown.class); - - public CmdShutdown(PurrBot bot){ - this.bot = bot; - } - - @Override - public void run(Guild guild, TextChannel tc, Message msg, Member member, String... args){ - if(msg.getGuild().getSelfMember().hasPermission(tc, Permission.MESSAGE_MANAGE)) - msg.delete().queue(); - - MessageEmbed embed = bot.getEmbedUtil().getEmbed() - .setDescription(bot.getMessageUtil().getRandomShutdownMsg()) - .setImage(bot.getMessageUtil().getRandomShutdownImg()) - .build(); - - tc.sendMessageEmbeds(embed).queue(message -> { - logger.info("Disabling bot! Good bye..."); - bot.disable(); - }); - } -} diff --git a/src/main/java/site/purrbot/bot/constants/Emotes.java b/src/main/java/site/purrbot/bot/constants/Emotes.java deleted file mode 100644 index 6b7d12e4e..000000000 --- a/src/main/java/site/purrbot/bot/constants/Emotes.java +++ /dev/null @@ -1,153 +0,0 @@ -/* - * Copyright 2018 - 2021 Andre601 - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated - * documentation files (the "Software"), to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, - * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or substantial - * portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package site.purrbot.bot.constants; - -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -public enum Emotes{ - // Animated emotes, - LOADING ("loading", "858052734859345930", true), - SENKO_TAIL_WAG("senkoTailWag", "858053594081918996", true), - SHIRO_TAIL_WAG("shiroTailWag", "858053594162135070", true), - TYPING ("typing", "858052735063818260", true), - - // Static/normal emotes - ACCEPT ("accept", "858052657204559872", false), - AWOO ("awoo", "858074817822195727", false), - BLANK ("blank", "669291169951252560", false), - BLOB_HOLO ("blobHolo", "858052852680622125", false), - BLUSH ("vanillaBlush", "858052852562526208", false), - BOOST_LEVEL_1 ("boost_level_1", "857291736133009489", false), - BOOST_LEVEL_2 ("boost_level_2", "857291736118984715", false), - BOOST_LEVEL_3 ("boost_level_3", "857291735906517003", false), - BOT ("bot", "855436906119299082", false), - BOT_TAG_1 ("botTag_1", "855439119005646908", false), - BOT_TAG_2 ("botTag_2", "855439119152054302", false), - BUGHUNTER ("bughunter", "857290795169611777", false), - BUGHUNTER_GOLD ("bughunterGold", "857290795530321960", false), - CATEGORY ("category", "855418148798857226", false), - CERTIFIED_MOD ("certifiedMod", "857290795438571520", false), - CLYDE ("clyde", "855436906100031489", false), - DENY ("deny", "858052657151475722", false), - DISCOVER ("discover", "855418148558471199", false), - DOWNLOAD ("download", "855439118997258270", false), - EARLY_SUPPORTER ("earlySupporter", "857290795640291370", false), - EARLY_VERIFIED_BOT_DEV("earlyVerifiedBotDev", "857290795194515516", false), - GIF ("gif", "855418148903714841", false), - HYPESQUAD_BALANCE ("hypesquadBalance", "857290795002363905", false), - HYPESQUAD_BRAVERY ("hypesquadBravery", "857290795505680434", false), - HYPESQUAD_BRILLIANCE ("hypesquadBrilliance", "857290795534516275", false), - HYPESQUAD_EVENTS ("hypesquadEvents", "857290795639504926", false), - IMAGES ("images", "855443695007301643", false), - INVITE ("invite", "855418148458332162", false), - KOFI ("kofi", "858075879837401098", false), - MEMBERS ("members", "855418149028495410", false), - MINUS ("minus", "592043203042213925", false), - NEKOWO ("nekOwO", "858052852717715475", false), - NEWS ("news", "855418148811440128", false), - OWNER ("owner", "855436906287988756", false), - PARTNER ("partner", "855418148962435082", false), - PARTNER_BADGE ("partner", "857290795581046864", false), - PATREON ("patreon", "858052657339957278", false), - PAYPAL ("paypal", "858052657163272212", false), - PENCIL ("pencil", "855442436515037225", false), - PLUS ("plus", "592043203629416459", false), - PURR ("purr", "858052891704295434", false), - RICH_RPESENCE ("rich_presence", "855418148949196830", false), - SEX ("sex", "858052656706355211", false), - SEX_ANAL ("sex_anal", "858052657277304842", false), - SEX_YAOI ("sex_yaoi", "858052657301159946", false), - SEX_YURI ("sex_yuri", "858052657239162900", false), - SLOWMODE ("slowmode", "855418148760977419", false), - SMILEY ("smiley", "855436906254434324", false), - SNUGGLE ("snuggle", "858052852639334430", false), - STAFF ("staff", "857290795090575391", false), - STATUS_DISCONNECT ("statusDisconnect", "592043203440410624", false), - STATUS_READY ("statusReady", "592043203646193692", false), - STORE ("store", "855418148895064075", false), - TEXT ("text", "855436906259021844", false), - VERIFIED_BOT_TAG_1 ("verifiedBotTag_1", "855439119006040067", false), - VERIFIED_BOT_TAG_2 ("verifiedBotTag_2", "855439119009447977", false), - VERIFIED ("verified", "855418151587807232", false), - VOICE ("voice", "855418149054578688", false); - - private static final Pattern emote_pattern = Pattern.compile("\\{EMOTE_(?[A-Z0-9_]+)}"); - private static final Emotes[] ALL = values(); - - private final String emoteName; - private final String id; - private final boolean animated; - - Emotes(String emoteName, String id, boolean animated){ - this.emoteName = emoteName; - this.id = id; - this.animated = animated; - } - - public String getEmote() { - return String.format( - "<%s:%s:%s>", - this.animated ? "a" : "", - this.emoteName, - this.id - ); - } - - public String getNameAndId(){ - return String.format( - "%s:%s", - this.emoteName, - this.id - ); - } - - public String getId(){ - return this.id; - } - - public static String getWithEmotes(String input){ - Matcher matcher = emote_pattern.matcher(input); - if(matcher.find()){ - StringBuilder builder = new StringBuilder(); - - do{ - String name = getEmote(matcher.group("name")); - if(name == null) - continue; - - matcher.appendReplacement(builder, name); - }while(matcher.find()); - - matcher.appendTail(builder); - input = builder.toString(); - } - - return input; - } - - private static String getEmote(String name){ - for(Emotes emote : ALL){ - if(emote.name().equalsIgnoreCase(name)) - return emote.getEmote(); - } - - return null; - } -} diff --git a/src/main/java/site/purrbot/bot/constants/IDs.java b/src/main/java/site/purrbot/bot/constants/IDs.java deleted file mode 100644 index c41661441..000000000 --- a/src/main/java/site/purrbot/bot/constants/IDs.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright 2018 - 2021 Andre601 - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated - * documentation files (the "Software"), to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, - * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or substantial - * portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package site.purrbot.bot.constants; - -public class IDs { - - // Developer of the bot - public static final String ANDRE_601 = "204232208049766400"; - - // IDs of the Bot and the beta version - public static final String PURR = "425382319449309197"; - public static final String SNUGGLE = "439829950686822410"; - - // Main Guild of the bot - public static final String GUILD = "423771795523371019"; - - // Suggestions channel on the server - public static final String SUGGESTIONS = "735986543293890613"; - - // Donator roles - public static final String DONATOR = "615201548892635166"; - public static final String PATREON_TIER_2 = "870674727289651201"; - public static final String PATREON_TIER_3 = "870674833216774155"; -} diff --git a/src/main/java/site/purrbot/bot/constants/Links.java b/src/main/java/site/purrbot/bot/constants/Links.java deleted file mode 100644 index cd39347c5..000000000 --- a/src/main/java/site/purrbot/bot/constants/Links.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright 2018 - 2021 Andre601 - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated - * documentation files (the "Software"), to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, - * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or substantial - * portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package site.purrbot.bot.constants; - -public class Links { - - // Discord invite - public static final String DISCORD = "https://purrbot.site/discord"; - - // GitHub links - public static final String GITHUB = "https://purrbot.site/github"; - - // Bot lists - public static final String DISCORD_BOTS_GG = "https://discord.bots.gg/bots/425382319449309197"; - public static final String DISCORDEXTREMELIST_XYZ = "https://discordextremelist.xyz/bots/purr"; - public static final String DISCORDSERVICES_NET = "https://dbot.page/purr"; - - // Other links - public static final String KOFI = "https://ko-fi.com/andre_601"; - public static final String PATREON = "https://patreon.com/andre_601"; - public static final String PAYPAL = "https://purrbot.site/donate"; - public static final String POLICY = "https://docs.purrbot.site/legal/bot"; - public static final String TRANSLATORS = "https://lang.purrbot.site"; - public static final String TWITTER = "https://purrbot.site/twitter"; - public static final String WEBSITE = "https://purrbot.site"; - public static final String WIKI = "https://docs.purrbot.site/bot"; -} diff --git a/src/main/java/site/purrbot/bot/listener/ConnectionListener.java b/src/main/java/site/purrbot/bot/listener/ConnectionListener.java deleted file mode 100644 index c7a809e8a..000000000 --- a/src/main/java/site/purrbot/bot/listener/ConnectionListener.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * Copyright 2018 - 2021 Andre601 - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated - * documentation files (the "Software"), to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, - * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or substantial - * portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package site.purrbot.bot.listener; - -import ch.qos.logback.classic.Logger; -import club.minnced.discord.webhook.send.WebhookEmbed; -import club.minnced.discord.webhook.send.WebhookEmbedBuilder; -import net.dv8tion.jda.api.JDA; -import net.dv8tion.jda.api.events.DisconnectEvent; -import net.dv8tion.jda.api.events.ResumedEvent; -import net.dv8tion.jda.api.hooks.ListenerAdapter; -import org.jetbrains.annotations.NotNull; -import org.slf4j.LoggerFactory; -import site.purrbot.bot.PurrBot; -import site.purrbot.bot.constants.Emotes; -import site.purrbot.bot.util.message.WebhookUtil; - -import java.time.ZonedDateTime; - -public class ConnectionListener extends ListenerAdapter{ - - private final Logger logger = (Logger)LoggerFactory.getLogger(ConnectionListener.class); - private final WebhookUtil webhookUtil; - - public ConnectionListener(PurrBot bot){ - this.webhookUtil = new WebhookUtil(bot.getFileManager().getString("config", "webhooks.log")); - } - - @Override - public void onDisconnect(@NotNull DisconnectEvent event){ - JDA jda = event.getJDA(); - - WebhookEmbedBuilder embed = new WebhookEmbedBuilder() - .setColor(0xFF0000) - .setTitle(new WebhookEmbed.EmbedTitle(Emotes.STATUS_DISCONNECT.getEmote(), null)) - .addField(new WebhookEmbed.EmbedField( - true, - "Shard:", - String.valueOf(jda.getShardInfo().getShardId()) - )) - .addField(new WebhookEmbed.EmbedField( - true, - "Affected Guilds:", - String.valueOf(jda.getGuilds().size()) - )) - .setFooter(new WebhookEmbed.EmbedFooter("Disconnected at", null)) - .setTimestamp(event.getTimeDisconnected()); - - if((event.getCloseCode() != null) && (event.getCloseCode().getCode() != 4900)) - embed.addField(new WebhookEmbed.EmbedField( - false, - "Reason:", - String.format( - "```yaml\n" + - "Code: %d\n" + - "Message: %s\n" + - "```", - event.getCloseCode().getCode(), - event.getCloseCode().getMeaning() - ) - )); - - webhookUtil.sendMsg( - jda.getSelfUser().getEffectiveAvatarUrl(), - "Disconnected", - embed.build() - ); - logger.info("Got disconnected on shard {}. Resume connection...", jda.getShardInfo().getShardId()); - } - - @Override - public void onResumed(@NotNull ResumedEvent event){ - JDA jda = event.getJDA(); - - WebhookEmbed embed = new WebhookEmbedBuilder() - .setColor(0x00FF00) - .setTitle(new WebhookEmbed.EmbedTitle(Emotes.STATUS_READY.getEmote(), null)) - .addField(new WebhookEmbed.EmbedField( - true, - "Shard:", - String.valueOf(jda.getShardInfo().getShardId()) - )) - .addField(new WebhookEmbed.EmbedField( - true, - "Affected Guilds:", - String.valueOf(jda.getGuilds().size()) - )) - .setFooter(new WebhookEmbed.EmbedFooter("Resumed at", null)) - .setTimestamp(ZonedDateTime.now()) - .build(); - - webhookUtil.sendMsg( - jda.getSelfUser().getEffectiveAvatarUrl(), - "Resumed session", - embed - ); - logger.info("Connection successfully resumed for shard {}!", jda.getShardInfo().getShardId()); - } - -} diff --git a/src/main/java/site/purrbot/bot/listener/GuildListener.java b/src/main/java/site/purrbot/bot/listener/GuildListener.java deleted file mode 100644 index ceaafa5b5..000000000 --- a/src/main/java/site/purrbot/bot/listener/GuildListener.java +++ /dev/null @@ -1,218 +0,0 @@ -/* - * Copyright 2018 - 2021 Andre601 - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated - * documentation files (the "Software"), to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, - * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or substantial - * portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package site.purrbot.bot.listener; - -import ch.qos.logback.classic.Logger; -import club.minnced.discord.webhook.send.WebhookEmbed; -import club.minnced.discord.webhook.send.WebhookEmbedBuilder; -import net.dv8tion.jda.api.entities.ChannelType; -import net.dv8tion.jda.api.entities.Guild; -import net.dv8tion.jda.api.entities.Member; -import net.dv8tion.jda.api.entities.TextChannel; -import net.dv8tion.jda.api.events.channel.ChannelDeleteEvent; -import net.dv8tion.jda.api.events.guild.GuildJoinEvent; -import net.dv8tion.jda.api.events.guild.GuildLeaveEvent; -import net.dv8tion.jda.api.hooks.ListenerAdapter; -import net.dv8tion.jda.api.utils.MarkdownSanitizer; -import org.slf4j.LoggerFactory; -import site.purrbot.bot.PurrBot; -import site.purrbot.bot.constants.Emotes; -import site.purrbot.bot.constants.Links; -import site.purrbot.bot.util.message.WebhookUtil; - -import javax.annotation.Nonnull; -import java.time.ZonedDateTime; - -public class GuildListener extends ListenerAdapter{ - - private final Logger logger = (Logger)LoggerFactory.getLogger(GuildListener.class); - - private final PurrBot bot; - private final WebhookUtil webhookUtil; - - public GuildListener(PurrBot bot){ - this.bot = bot; - this.webhookUtil = new WebhookUtil(bot.getFileManager().getString("config", "webhooks.guild")); - } - - @Override - public void onGuildJoin(@Nonnull GuildJoinEvent event){ - Guild guild = event.getGuild(); - - if(bot.getBlacklist().contains(guild.getId())){ - if(guild.getOwner() == null){ - guild.leave().queue(); - return; - } - guild.getOwner().getUser().openPrivateChannel() - .flatMap(channel -> channel.sendMessageFormat( - "I left your Discord `%s` for the following reason:\n" + - "```\n" + - "[Auto Leave] Your Discord is blacklisted! To find out why, join the\n" + - " Support Discord: %s\n" + - "```", - guild.getName(), - Links.DISCORD - )) - .queue(message -> { - logger.info("[Guild Leave] {} (id: {}, members: {})", guild.getName(), guild.getId(), guild.getMemberCount()); - guild.leave().queue(); - }, throwable -> { - logger.info("[Guild Leave] {} (id: {}, members: {})", guild.getName(), guild.getId(), guild.getMemberCount()); - guild.leave().queue(); - }); - - guild.retrieveOwner().queue( - owner -> sendWebhook(owner, guild, Action.AUTO_LEAVE), - e -> sendWebhook(null, guild, Action.AUTO_LEAVE) - ); - return; - } - - bot.getDbUtil().addGuild(guild.getId()); - - logger.info("[Guild Join] {} (id: {}, members: {})", guild.getName(), guild.getId(), guild.getMemberCount()); - - guild.retrieveOwner().queue( - owner -> sendWebhook(owner, guild, Action.JOIN), - e -> sendWebhook(null, guild, Action.JOIN) - ); - } - - @Override - public void onGuildLeave(@Nonnull GuildLeaveEvent event){ - Guild guild = event.getGuild(); - - if(bot.getBlacklist().contains(guild.getId())) - return; - - bot.getDbUtil().delGuild(guild.getId()); - - bot.invalidateCache(guild.getId()); - - logger.info("[Guild Leave] {} (id: {}, members: {})", guild.getName(), guild.getId(), guild.getMemberCount()); - - guild.retrieveOwner().queue( - owner -> sendWebhook(owner, guild, Action.LEAVE), - e -> sendWebhook(null, guild, Action.LEAVE) - ); - } - - @Override - public void onChannelDelete(@Nonnull ChannelDeleteEvent event){ - if(!event.isFromGuild() || (event.getChannel().getType() != ChannelType.TEXT)) - return; - - Guild guild = event.getGuild(); - String id = bot.getWelcomeChannel(guild.getId()); - - if(id.equals("none")) - return; - - TextChannel tc = guild.getTextChannelById(id); - if(tc == null) { - bot.setWelcomeChannel(guild.getId(), "none"); - return; - } - - if(event.getChannel().getId().equals(id)) - bot.setWelcomeChannel(guild.getId(), "none"); - } - - private void sendWebhook(Member owner, Guild guild, Action action) { - String mention = owner == null ? "Unknown" : owner.getAsMention(); - String name = owner == null ? "Unknown" : owner.getUser().getName(); - String id = owner == null ? "?" : owner.getId(); - - String title = null; - WebhookEmbedBuilder embed = new WebhookEmbedBuilder() - .setThumbnailUrl(guild.getIconUrl()) - .addField(new WebhookEmbed.EmbedField( - true, - "Name", - guild.getName() - )) - .addField(new WebhookEmbed.EmbedField( - true, - "Shard [Current / Total]", - guild.getJDA().getShardInfo().getShardString() - )) - .addField(new WebhookEmbed.EmbedField( - false, - "Owner", - String.format( - "%s | %s (`%s`)", - mention, - MarkdownSanitizer.escape(name), - id - ) - )) - .addField(new WebhookEmbed.EmbedField( - false, - "Members", - String.format( - "```yaml\n" + - "Total: %d\n" + - "```", - guild.getMemberCount() - ) - )) - .setFooter(new WebhookEmbed.EmbedFooter( - String.format( - "Guild #%s", - bot.getMessageUtil().formatNumber(bot.getShardManager().getGuildCache().size()) - ), - null - )) - .setTimestamp(ZonedDateTime.now()); - - switch(action){ - case JOIN: - title = "Join"; - embed.setColor(0x00FF00) - .setTitle(new WebhookEmbed.EmbedTitle(Emotes.PLUS.getEmote(), null)); - break; - - case LEAVE: - title = "Leave"; - embed.setColor(0xFF0000) - .setTitle(new WebhookEmbed.EmbedTitle(Emotes.MINUS.getEmote(), null)); - break; - - case AUTO_LEAVE: - title = "Leave [Auto]"; - embed.setColor(0xFF0000) - .setTitle(new WebhookEmbed.EmbedTitle(Emotes.MINUS.getEmote(), null)); - break; - } - - webhookUtil.sendMsg( - guild.getSelfMember().getUser().getEffectiveAvatarUrl(), - title, - action == Action.JOIN ? ".leave " + guild.getId() : null, - embed.build() - ); - } - - enum Action{ - JOIN, - LEAVE, - AUTO_LEAVE - } -} diff --git a/src/main/java/site/purrbot/bot/listener/MemberListener.java b/src/main/java/site/purrbot/bot/listener/MemberListener.java deleted file mode 100644 index 51c427b78..000000000 --- a/src/main/java/site/purrbot/bot/listener/MemberListener.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright 2018 - 2021 Andre601 - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated - * documentation files (the "Software"), to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, - * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or substantial - * portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package site.purrbot.bot.listener; - -import net.dv8tion.jda.api.Permission; -import net.dv8tion.jda.api.entities.Guild; -import net.dv8tion.jda.api.entities.Member; -import net.dv8tion.jda.api.entities.TextChannel; -import net.dv8tion.jda.api.events.guild.member.GuildMemberJoinEvent; -import net.dv8tion.jda.api.events.guild.member.update.GuildMemberUpdatePendingEvent; -import net.dv8tion.jda.api.hooks.ListenerAdapter; -import org.jetbrains.annotations.NotNull; -import site.purrbot.bot.PurrBot; - -import javax.annotation.Nonnull; -import java.io.InputStream; - -public class MemberListener extends ListenerAdapter{ - - private final PurrBot bot; - - public MemberListener(PurrBot bot){ - this.bot = bot; - } - - @Override - public void onGuildMemberJoin(@Nonnull GuildMemberJoinEvent event){ - Guild guild = event.getGuild(); - - // Don't handle joins when the Guild has the Member screening active - if(guild.getFeatures().contains("MEMBER_VERIFICATION_GATE_ENABLED")) - return; - - if(event.getUser().isBot()) - return; - - sendWelcomeMessage(guild, event.getMember()); - } - - @Override - public void onGuildMemberUpdatePending(@NotNull GuildMemberUpdatePendingEvent event){ - if(event.getNewPending()) - return; - - if(event.getUser().isBot()) - return; - - sendWelcomeMessage(event.getGuild(), event.getMember()); - } - - private void sendWelcomeMessage(Guild guild, Member member){ - String guildId = guild.getId(); - if(bot.getWelcomeChannel(guildId).equals("none")) - return; - - TextChannel tc = guild.getTextChannelById(bot.getWelcomeChannel(guildId)); - if(tc == null) - return; - - if(!guild.getSelfMember().hasPermission(tc, Permission.MESSAGE_SEND)) - return; - - String message = bot.getWelcomeMsg(guildId); - if(message == null) - message = "Welcome {mention}!"; - - InputStream image = bot.getImageUtil().getWelcomeImg( - member, - bot.getWelcomeIcon(guildId), - bot.getWelcomeBg(guildId), - bot.getWelcomeColor(guildId) - ); - - bot.getMessageUtil().sendWelcomeMsg(tc, message, member, image); - } -} diff --git a/src/main/java/site/purrbot/bot/listener/ReadyListener.java b/src/main/java/site/purrbot/bot/listener/ReadyListener.java deleted file mode 100644 index 121b6c311..000000000 --- a/src/main/java/site/purrbot/bot/listener/ReadyListener.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Copyright 2018 - 2021 Andre601 - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated - * documentation files (the "Software"), to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, - * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or substantial - * portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package site.purrbot.bot.listener; - -import ch.qos.logback.classic.Logger; -import club.minnced.discord.webhook.send.WebhookEmbed; -import club.minnced.discord.webhook.send.WebhookEmbedBuilder; -import net.dv8tion.jda.api.JDA; -import net.dv8tion.jda.api.OnlineStatus; -import net.dv8tion.jda.api.entities.Activity; -import net.dv8tion.jda.api.events.ReadyEvent; -import net.dv8tion.jda.api.hooks.ListenerAdapter; -import net.dv8tion.jda.api.sharding.ShardManager; -import org.jetbrains.annotations.NotNull; -import org.slf4j.LoggerFactory; -import site.purrbot.bot.PurrBot; -import site.purrbot.bot.constants.Emotes; -import site.purrbot.bot.util.message.WebhookUtil; - -import java.time.ZonedDateTime; - -public class ReadyListener extends ListenerAdapter{ - - private final Logger logger = (Logger)LoggerFactory.getLogger(ReadyListener.class); - - private final PurrBot bot; - private final WebhookUtil webhookUtil; - - private int shards = 0; - - public ReadyListener(PurrBot bot){ - this.bot = bot; - this.webhookUtil = new WebhookUtil(bot.getFileManager().getString("config", "webhooks.log")); - } - - @Override - public void onReady(@NotNull ReadyEvent event){ - ShardManager shardManager = bot.getShardManager(); - JDA jda = event.getJDA(); - - shards++; - logger.info("Shard {} ({} Guilds) ready!", jda.getShardInfo().getShardId(), jda.getGuildCache().size()); - - WebhookEmbed embed = new WebhookEmbedBuilder() - .setColor(0x00FF00) - .setTitle(new WebhookEmbed.EmbedTitle(Emotes.STATUS_READY.getEmote(), null)) - .addField(new WebhookEmbed.EmbedField( - true, - "Guilds:", - String.valueOf(jda.getGuilds().size()) - )) - .addField(new WebhookEmbed.EmbedField( - true, - "Shard:", - String.valueOf(jda.getShardInfo().getShardId()) - )) - .setFooter(new WebhookEmbed.EmbedFooter("Ready at", null)) - .setTimestamp(ZonedDateTime.now()) - .build(); - - webhookUtil.sendMsg( - jda.getSelfUser().getEffectiveAvatarUrl(), - "Shard ready!", - embed - ); - - if(shards == jda.getShardInfo().getShardTotal()){ - shardManager.setPresence(OnlineStatus.ONLINE, Activity.of( - Activity.ActivityType.WATCHING, - bot.getMessageUtil().getBotGame(shardManager.getGuildCache().size()) - )); - - bot.startUpdater(); - - WebhookEmbed finished = new WebhookEmbedBuilder() - .setColor(0x00FF00) - .setTitle(new WebhookEmbed.EmbedTitle(String.format( - "\\%s ready!", - jda.getSelfUser().getName() - ), null)) - .setDescription(String.format( - "\\%s is online and ready to bring you fun and nekos. <:catUwU:703924268022497340>", - jda.getSelfUser().getName() - )) - .build(); - - webhookUtil.sendMsg( - jda.getSelfUser().getEffectiveAvatarUrl(), - "Ready!", - finished - ); - - logger.info( - "Loaded Bot {} vBOT_VERSION with {} shard(s) and {} guilds!", - jda.getSelfUser().getAsTag(), - shardManager.getShardCache().size(), - bot.getMessageUtil().formatNumber(shardManager.getGuildCache().size()) - ); - } - } -} diff --git a/src/main/java/site/purrbot/bot/util/CheckUtil.java b/src/main/java/site/purrbot/bot/util/CheckUtil.java deleted file mode 100644 index 3281fca0f..000000000 --- a/src/main/java/site/purrbot/bot/util/CheckUtil.java +++ /dev/null @@ -1,188 +0,0 @@ -/* - * Copyright 2018 - 2021 Andre601 - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated - * documentation files (the "Software"), to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, - * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or substantial - * portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package site.purrbot.bot.util; - -import net.dv8tion.jda.api.EmbedBuilder; -import net.dv8tion.jda.api.Permission; -import net.dv8tion.jda.api.entities.*; -import site.purrbot.bot.PurrBot; -import site.purrbot.bot.constants.IDs; - -import java.util.stream.Collectors; - -public class CheckUtil{ - - private final PurrBot bot; - - public CheckUtil(PurrBot bot){ - this.bot = bot; - } - - public boolean isDeveloper(Member member){ - return member.getId().equals(IDs.ANDRE_601); - } - - public boolean lacksPermission(TextChannel tc, Member member, Permission permission){ - return lacksPermission(tc, member, false, null, permission); - } - - public boolean lacksPermission(TextChannel tc, Member member, boolean isSelf, TextChannel channel, Permission permission){ - Guild guild = tc.getGuild(); - if(isSelf){ - Member self = guild.getSelfMember(); - if(channel == null){ - if(self.hasPermission(permission)){ - return false; - }else{ - bot.getEmbedUtil().sendPermError(tc, member, permission, true); - return true; - } - }else{ - if(self.hasPermission(channel, permission)){ - return false; - }else{ - bot.getEmbedUtil().sendPermError(tc, member, channel, permission, true); - return true; - } - } - }else{ - if(member.hasPermission(permission)){ - return false; - }else{ - bot.getEmbedUtil().sendPermError(tc, member, permission, false); - return true; - } - } - } - - public boolean hasAdmin(Member executor, TextChannel tc){ - Guild guild = tc.getGuild(); - Member self = guild.getSelfMember(); - if(!self.hasPermission(Permission.ADMINISTRATOR)) - return false; - - String roles = self.getRoles().stream() - .filter(role -> role.getPermissions().contains(Permission.ADMINISTRATOR)) - .map(role -> "- " + role.getAsMention()) - .collect(Collectors.joining("\n")); - - if(guild.getPublicRole().getPermissions().contains(Permission.ADMINISTRATOR)) - roles += (roles.isEmpty() ? "" : "\n") + "- @everyone"; - - MessageEmbed embed = bot.getEmbedUtil().getErrorEmbed(executor) - .setDescription( - bot.getMsg(guild.getId(), "errors.administrator") - .replace("{roles}", roles) - ).build(); - - tc.sendMessageEmbeds(embed).queue(); - - return true; - } - - public boolean isPatreon(String id){ - Guild guild = bot.getShardManager().getGuildById(IDs.GUILD); - if(guild == null) - return false; - - Member member = guild.getMemberById(id); - if(member == null) - return false; - - Role tier2 = guild.getRoleById(IDs.PATREON_TIER_2); - Role tier3 = guild.getRoleById(IDs.PATREON_TIER_3); - if(tier2 == null || tier3 == null) - return false; - - return member.getRoles().contains(tier2) || member.getRoles().contains(tier3); - } - - public boolean isPatreon(TextChannel tc, String id){ - Guild guild = bot.getShardManager().getGuildById(IDs.GUILD); - if(guild == null){ - EmbedBuilder builder = bot.getEmbedUtil().getErrorEmbed(null) - .setDescription(bot.getMsg(tc.getGuild().getId(), "errors.fetch.guild")); - tc.sendMessageEmbeds(builder.build()).queue(); - return false; - } - - Member member = guild.getMemberById(id); - if(member == null){ - EmbedBuilder builder = bot.getEmbedUtil().getErrorEmbed(null) - .setDescription(bot.getMsg(tc.getGuild().getId(), "errors.fetch.member")); - tc.sendMessageEmbeds(builder.build()).queue(); - return false; - } - - Role tier2 = guild.getRoleById(IDs.PATREON_TIER_2); - Role tier3 = guild.getRoleById(IDs.PATREON_TIER_3); - if(tier2 == null || tier3 == null){ - EmbedBuilder builder = bot.getEmbedUtil().getErrorEmbed(null) - .setDescription(bot.getMsg(tc.getGuild().getId(), "errors.fetch.patreon_roles")); - tc.sendMessageEmbeds(builder.build()).queue(); - return false; - } - - return member.getRoles().contains(tier2) || member.getRoles().contains(tier3); - } - - public boolean isBooster(String id){ - Guild guild = bot.getShardManager().getGuildById(IDs.GUILD); - if(guild == null) - return false; - - Member member = guild.getMemberById(id); - if(member == null) - return false; - - Role booster = guild.getBoostRole(); - if(booster == null) - return false; - - return member.getRoles().contains(booster); - } - - public boolean isBooster(TextChannel tc, String id){ - Guild guild = bot.getShardManager().getGuildById(IDs.GUILD); - if(guild == null){ - EmbedBuilder builder = bot.getEmbedUtil().getErrorEmbed(null) - .setDescription(bot.getMsg(tc.getGuild().getId(), "errors.fetch.guild")); - tc.sendMessageEmbeds(builder.build()).queue(); - return false; - } - - Member member = guild.getMemberById(id); - if(member == null){ - EmbedBuilder builder = bot.getEmbedUtil().getErrorEmbed(null) - .setDescription(bot.getMsg(tc.getGuild().getId(), "errors.fetch.member")); - tc.sendMessageEmbeds(builder.build()).queue(); - return false; - } - - Role booster = guild.getBoostRole(); - if(booster == null){ - EmbedBuilder builder = bot.getEmbedUtil().getErrorEmbed(null) - .setDescription(bot.getMsg(tc.getGuild().getId(), "errors.fetch.booster_role")); - tc.sendMessageEmbeds(builder.build()).queue(); - return false; - } - - return member.getRoles().contains(booster); - } -} diff --git a/src/main/java/site/purrbot/bot/util/DBUtil.java b/src/main/java/site/purrbot/bot/util/DBUtil.java deleted file mode 100644 index b94bc3ad0..000000000 --- a/src/main/java/site/purrbot/bot/util/DBUtil.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Copyright 2018 - 2021 Andre601 - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated - * documentation files (the "Software"), to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, - * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or substantial - * portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package site.purrbot.bot.util; - -import com.rethinkdb.RethinkDB; -import com.rethinkdb.net.Connection; -import com.rethinkdb.utils.Types; -import site.purrbot.bot.PurrBot; - -import java.util.Map; -import java.util.Objects; - -public class DBUtil { - - private final PurrBot bot; - - private final RethinkDB r; - private final Connection connection; - - private final String guildTable; - - public DBUtil(PurrBot bot){ - r = RethinkDB.r; - connection = r.connection() - .hostname(bot.getFileManager().getString("config", "database.ip")) - .port(28015) - .db(bot.getFileManager().getString("config", "database.name")) - .connect(); - - guildTable = bot.getFileManager().getString("config", "database.guildTable"); - this.bot = bot; - } - - /* - * Guild Stuff - */ - public void addGuild(String id){ - r.table(guildTable).insert( - r.array( - r.hashMap("id", id) - .with("language", "en") - .with("prefix", bot.isBeta() ? "p.." : "p.") - .with("welcome_background", "color_white") - .with("welcome_channel", "none") - .with("welcome_color", "hex:000000") - .with("welcome_icon", "purr") - .with("welcome_message", "Welcome {mention}!") - ) - ).optArg("conflict", "update").run(connection); - } - - public void delGuild(String id){ - Map guild = getGuild(id); - - if(guild == null) - return; - - r.table(guildTable).get(id).delete().run(connection); - } - - public Map getGuild(String id){ - return r.table(guildTable) - .get(id) - .run(connection, Types.mapOf(String.class, String.class)) - .stream() - .filter(Objects::nonNull) - .findFirst() - .orElse(null); - } - - public void updateSettings(String id, String key, String value){ - Map guild = getGuild(id); - if(guild == null) - addGuild(id); - - r.table(guildTable).get(id) - .update(r.hashMap(key, value)) - .run(connection); - } -} diff --git a/src/main/java/site/purrbot/bot/util/GuildSettings.java b/src/main/java/site/purrbot/bot/util/GuildSettings.java deleted file mode 100644 index 3cd1c8a6d..000000000 --- a/src/main/java/site/purrbot/bot/util/GuildSettings.java +++ /dev/null @@ -1,126 +0,0 @@ -/* - * Copyright 2018 - 2021 Andre601 - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated - * documentation files (the "Software"), to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, - * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or substantial - * portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package site.purrbot.bot.util; - -public class GuildSettings{ - - // Name keys for the settings - public static final String LANGUAGE = "language"; - public static final String PREFIX = "prefix"; - - public static final String WELCOME_BACKGROUND = "welcome_background"; - public static final String WELCOME_CHANNEL = "welcome_channel"; - public static final String WELCOME_COLOR = "welcome_color"; - public static final String WELCOME_ICON = "welcome_icon"; - public static final String WELCOME_MESSAGE = "welcome_message"; - - // Default values - public static final String DEF_LANGUAGE = "en"; - public static final String DEF_PREFIX = "p."; - public static final String DEF_PREFIX_BETA = "p.."; - - public static final String DEF_BACKGROUND = "color_white"; - public static final String DEF_CHANNEL = "none"; - public static final String DEF_COLOR = "hex:000000"; - public static final String DEF_ICON = "purr"; - public static final String DEF_MESSAGE = "Welcome {mention}!"; - - private String language; - private String prefix; - - private String welcomeBackground; - private String welcomeChannel; - private String welcomeColor; - private String welcomeIcon; - private String welcomeMessage; - - public static GuildSettings createDefault(boolean beta){ - return new GuildSettings() - .setLanguage(DEF_LANGUAGE) - .setPrefix(beta ? DEF_PREFIX_BETA : DEF_PREFIX) - .setWelcomeBackground(DEF_BACKGROUND) - .setWelcomeChannel(DEF_CHANNEL) - .setWelcomeColor(DEF_COLOR) - .setWelcomeIcon(DEF_ICON) - .setWelcomeMessage(DEF_MESSAGE); - } - - public GuildSettings setLanguage(String language){ - this.language = language; - return this; - } - - public GuildSettings setPrefix(String prefix){ - this.prefix = prefix; - return this; - } - - public GuildSettings setWelcomeBackground(String welcomeBackground){ - this.welcomeBackground = welcomeBackground; - return this; - } - - public GuildSettings setWelcomeChannel(String welcomeChannel){ - this.welcomeChannel = welcomeChannel; - return this; - } - - public GuildSettings setWelcomeColor(String welcomeColor){ - this.welcomeColor = welcomeColor; - return this; - } - - public GuildSettings setWelcomeIcon(String welcomeIcon){ - this.welcomeIcon = welcomeIcon; - return this; - } - - public GuildSettings setWelcomeMessage(String welcomeMessage){ - this.welcomeMessage = welcomeMessage; - return this; - } - - public String getLanguage(){ - return language; - } - - public String getPrefix(){ - return prefix; - } - - public String getWelcomeBackground(){ - return welcomeBackground; - } - - public String getWelcomeChannel(){ - return welcomeChannel; - } - - public String getWelcomeColor(){ - return welcomeColor; - } - - public String getWelcomeIcon(){ - return welcomeIcon; - } - - public String getWelcomeMessage(){ - return welcomeMessage; - } -} diff --git a/src/main/java/site/purrbot/bot/util/HttpUtil.java b/src/main/java/site/purrbot/bot/util/HttpUtil.java deleted file mode 100644 index 97670e4fd..000000000 --- a/src/main/java/site/purrbot/bot/util/HttpUtil.java +++ /dev/null @@ -1,356 +0,0 @@ -/* - * Copyright 2018 - 2021 Andre601 - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated - * documentation files (the "Software"), to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, - * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or substantial - * portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package site.purrbot.bot.util; - -import ch.qos.logback.classic.Logger; -import okhttp3.*; -import org.json.JSONObject; -import org.slf4j.LoggerFactory; -import site.purrbot.bot.constants.IDs; - -import java.io.IOException; -import java.util.concurrent.CompletableFuture; - -public class HttpUtil { - - private final Logger logger = (Logger)LoggerFactory.getLogger(HttpUtil.class); - private final OkHttpClient client = new OkHttpClient(); - - private String image(String url) throws IOException{ - Request request = new Request.Builder() - .url(url) - .build(); - - try(Response response = client.newCall(request).execute()){ - if(!response.isSuccessful()) - throw new IOException(String.format( - "Unexpected code from url %s: %s", - url, - response - )); - - ResponseBody body = response.body(); - if(body == null) - throw new NullPointerException("Received empty body!"); - - String bodyString = body.string(); - if(bodyString.isEmpty()) - throw new NullPointerException("Received empty body!"); - - return new JSONObject(bodyString).getString("link"); - } - } - - public String getImage(String url){ - try{ - return image(url); - }catch(IOException ex){ - return null; - } - } - - public CompletableFuture getImage(ImageAPI imageAPI){ - return CompletableFuture.supplyAsync(() -> { - Request request = new Request.Builder() - .url(imageAPI.getUrl()) - .build(); - - try(Response response = client.newCall(request).execute()){ - if(!response.isSuccessful()){ - logger.warn("Non-Successfull HTTP-Response for {}", imageAPI.getUrl()); - logger.warn("Status-Code: {}; Message: {}", response.code(), response.message()); - - return new Result(null, imageAPI.getPath(), imageAPI.isRequest(), imageAPI.isRequired()); - } - - ResponseBody body = response.body(); - if(body == null){ - logger.warn("Received null Body for {}", imageAPI.getUrl()); - - return new Result(null, imageAPI.getPath(), imageAPI.isRequest(), imageAPI.isRequired()); - } - - String bodyString = body.string(); - if(bodyString.isEmpty()){ - logger.warn("Received empty body!"); - - return new Result(null, imageAPI.getPath(), imageAPI.isRequest(), imageAPI.isRequired()); - } - - String link = new JSONObject(bodyString).optString("link", null); - return new Result(link, imageAPI.getPath(), imageAPI.isRequest(), imageAPI.isRequired()); - }catch(IOException ex){ - return new Result(null, imageAPI.getPath(), imageAPI.isRequest(), imageAPI.isRequired()); - } - }); - } - - public CompletableFuture postServerStats(String name, String discrim, long guilds, long shards, BotList botList, String token){ - return CompletableFuture.supplyAsync(() -> performPost(name, discrim, guilds, shards, botList, token)); - } - - private BotListResult performPost(String name, String discrim, long guilds, long shards, BotList botList, String token){ - JSONObject json = new JSONObject() - .put(botList.getGuildCount(), guilds); - - if(botList.getShardCount() != null) - json.put(botList.getShardCount(), shards); - - RequestBody requestBody = RequestBody.create(json.toString(), null); - Request request = new Request.Builder() - .url(botList.getUrl().replace("{id}", IDs.PURR)) - .addHeader("Authorization", token) - .addHeader("Content-Type", "application/json") - .addHeader("User-Agent", String.format( - "%s-%s/%s (JDA) DBots/%s", - name, - discrim, - "BOT_VERSION", - IDs.PURR - )) - .post(requestBody) - .build(); - - try(Response response = client.newCall(request).execute()){ - return new BotListResult(botList.getName(), response.isSuccessful(), response.code(), response.message()); - }catch(IOException ex){ - ex.printStackTrace(); - return null; - } - } - - public static class BotListResult{ - private final String botList; - private final boolean success; - private final int responseCode; - private final String responseMessage; - - public BotListResult(String botList, boolean success, int responseCode, String responseMessage){ - this.botList = botList; - this.success = success; - this.responseCode = responseCode; - this.responseMessage = responseMessage; - } - - public String getBotList(){ - return botList; - } - - public boolean isSuccess(){ - return success; - } - - public int getResponseCode(){ - return responseCode; - } - - public String getResponseMessage(){ - return responseMessage; - } - } - - public static class Result{ - private final String url; - private final String path; - private final boolean request; - private final boolean required; - - public Result(String url, String path, boolean request, boolean required){ - this.url = url; - this.path = path; - this.request = request; - this.required = required; - } - - public String getUrl(){ - return url; - } - - public String getPath(){ - return path; - } - - public boolean isRequest(){ - return request; - } - - public boolean isRequired(){ - return required; - } - } - - public enum ImageAPI{ - // SFW Gifs - BITE ("bite", "bite", true, false, false, false), - BLUSH ("blush", "blush", true, false, false, false), - COMFY ("comfy", "comfy", true, false, false, false), - CRY ("cry", "cry", true, false, false, false), - CUDDLE ("cuddle", "cuddle", true, false, false, false), - DANCE ("dance", "dance", true, false, false, false), - EEVEE_GIF("eevee", "eevee", true, false, false, true), - FEED ("feed", "feed", true, false, true, false), - FLUFF ("fluff", "fluff", true, false, true, false), - HUG ("hug", "hug", true, false, false, false), - KISS ("kiss", "kiss", true, false, false, false), - LICK ("lick", "lick", true, false, false, false), - NEKO_GIF ("neko", "neko", true, false, false, true), - PAT ("pat", "pat", true, false, false, false), - POKE ("poke", "poke", true, false, false, false), - SLAP ("slap", "slap", true, false, false, false), - SMILE ("smile", "smile", true, false, false, false), - TAIL ("tail", "tail", true, false, false, false), - TICKLE ("tickle", "tickle", true, false, false, false), - - // NSFW Gifs - NSFW_ANAL ("anal", "fuck", true, true, true, false), - NSFW_BLOWJOB ("blowjob", "blowjob", true, true, true, false), - NSFW_CUM ("cum", "cum", true, true, false, false), - NSFW_FUCK ("fuck", "fuck", true, true, true, false), - NSFW_NEKO_GIF ("neko", "lewd", true, true, false, true), - NSFW_PUSSYLICK ("pussylick", "pussylick", true, true, true, false), - NSFW_SOLO ("solo", "solo", true, true, false, false), - NSFW_SPANK ("spank", "spank", true, true, true, false), - NSFW_THREESOME_FFF("threesome_fff", "threesome", true, true, true, false), - NSFW_THREESOME_FFM("threesome_ffm", "threesome", true, true, true, false), - NSFW_THREESOME_MMF("threesome_mmf", "threesome", true, true, true, false), - NSFW_YAOI ("yaoi", "fuck", true, true, true, false), - NSFW_YURI ("yuri", "fuck", true, true, true, false), - - // SFW Images - EEVEE_IMG("eevee", "eevee", false, false, false, true), - HOLO ("holo", "holo", false, false, false, true), - KITSUNE ("kitsune", "kitsune", false, false, false, true), - NEKO_IMG ("neko", "neko", false, false, false, true), - OKAMI ("okami", "okami", false, false, false, true), - SENKO ("senko", "senko", false, false, false, true), - - // NSFW Images - NSFW_NEKO_IMG("neko", "lewd", false, true, false, true); - - private final String name; - private final String pathName; - private final boolean gif; - private final boolean nsfw; - private final boolean request; - private final boolean required; - - ImageAPI(String name, String pathName, boolean gif, boolean nsfw, boolean request, boolean required){ - this.name = name; - this.pathName = pathName; - this.gif = gif; - this.nsfw = nsfw; - this.request = request; - this.required = required; - } - - public String getName(){ - return name; - } - - public boolean isRequest(){ - return request; - } - - public boolean isRequired(){ - return required; - } - - public String getUrl(){ - return String.format( - "https://purrbot.site/api/img/%s/%s/%s", - nsfw ? "nsfw" : "sfw", - name, - gif ? "gif" : "img" - ); - } - - public String getPath(){ - return String.format( - "purr.%s.%s.", - nsfw ? "nsfw" : "fun", - pathName - ); - } - } - - public enum BotList{ - DISCORD_BOTS_GG( - "tokens.discord-bots-gg", - "discord.bots.gg", - "https://discord.bots.gg/api/v1/bots/{id}/stats", - "guildCount", "shardCount" - ), - DISCORDEXTREMELIST_XYZ( - "tokens.discordextremelist-xyz", - "discordextremelist.xyz", - "https://api.discordextremelist.xyz/v2/bot/{id}/stats", - "guildCount", - "shardCount" - ), - DISCORDSERVICES_NET( - "tokens.discordservices-net", - "discordservices.net", - "https://api.discordservices.net/bot/{id}/stats", - "servers", - "shards" - ); - - private final String tokenPath; - private final String name; - private final String url; - private final String guildCount; - private final String shardCount; - - BotList(String tokenPath, String name, String url, String guildCount){ - this.tokenPath = tokenPath; - this.name = name; - this.url = url; - this.guildCount = guildCount; - this.shardCount = null; - } - - BotList(String tokenPath, String name, String url, String guildCount, String shardCount){ - this.tokenPath = tokenPath; - this.name = name; - this.url = url; - this.guildCount = guildCount; - this.shardCount = shardCount; - } - - public String getTokenPath(){ - return tokenPath; - } - - public String getName(){ - return name; - } - - public String getUrl(){ - return url; - } - - public String getGuildCount(){ - return guildCount; - } - - public String getShardCount(){ - return shardCount; - } - } -} diff --git a/src/main/java/site/purrbot/bot/util/ImageUtil.java b/src/main/java/site/purrbot/bot/util/ImageUtil.java deleted file mode 100644 index c11861e34..000000000 --- a/src/main/java/site/purrbot/bot/util/ImageUtil.java +++ /dev/null @@ -1,236 +0,0 @@ -/* - * Copyright 2018 - 2021 Andre601 - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated - * documentation files (the "Software"), to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, - * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or substantial - * portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package site.purrbot.bot.util; - -import net.dv8tion.jda.api.entities.Member; -import net.dv8tion.jda.api.entities.User; -import okhttp3.*; -import org.json.JSONObject; -import site.purrbot.bot.PurrBot; - -import javax.imageio.ImageIO; -import java.awt.*; -import java.awt.font.FontRenderContext; -import java.awt.font.TextLayout; -import java.awt.geom.AffineTransform; -import java.awt.image.BufferedImage; -import java.io.*; -import java.net.URL; -import java.net.URLConnection; - -public class ImageUtil { - - private final PurrBot bot; - - public ImageUtil(PurrBot bot){ - this.bot = bot; - } - - private final OkHttpClient CLIENT = new OkHttpClient(); - - private BufferedImage getAvatar(User user) throws IOException{ - URL url = new URL(user.getEffectiveAvatarUrl()); - URLConnection connection = url.openConnection(); - connection.setRequestProperty("User-Agent", "PurrBot BOT_VERSION"); - connection.connect(); - - return ImageIO.read(connection.getInputStream()); - } - - public byte[] getShipImg(Member member1, Member member2, int chance){ - try{ - BufferedImage template = ImageIO.read(new File("img/LoveTemplate.png")); - BufferedImage avatar1 = getAvatar(member1.getUser()); - BufferedImage avatar2 = getAvatar(member2.getUser()); - - BufferedImage background = new BufferedImage(template.getWidth(), template.getHeight(), template.getType()); - - Graphics2D img = background.createGraphics(); - - float r = (100 - (float)chance) / 100; - float g = (float)chance / 100; - - Color outlineColor = Color.BLACK; - Color fillColor = new Color(r, g, 0.0f); - - if(chance == 69) - fillColor = new Color(0xFF8989); // This number is "special" - - img.drawImage(avatar1, 0, 0, 320, 320, null); - img.drawImage(avatar2, 640, 0, 320, 320, null); - img.drawImage(template, 0, 0, null); - - Font font = new Font(Font.SANS_SERIF, Font.PLAIN, 80); - - img.setColor(fillColor); - img.setFont(font); - - String text = chance + "%"; - - img.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - img.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); - - FontRenderContext context = img.getFontRenderContext(); - - int textWidth = img.getFontMetrics(font).stringWidth(text); - - int textX = (template.getWidth() / 2) - (textWidth / 2); - int textY = (template.getHeight() / 2) + 40; - - img.drawString(text, textX, textY); - - TextLayout layout = new TextLayout(text, font, context); - AffineTransform transform = img.getTransform(); - - Shape outline = layout.getOutline(null); - - transform.translate(textX, textY); - - img.setStroke(new BasicStroke(2.0f)); - - img.transform(transform); - img.setColor(outlineColor); - img.draw(outline); - - img.setClip(outline); - - img.dispose(); - - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - ImageIO.setUseCache(false); - ImageIO.write(background, "png", baos); - - return baos.toByteArray(); - }catch(IOException ex){ - return null; - } - } - - public InputStream getWelcomeImg(Member member, String icon, String bg, String color){ - Color col = bot.getMessageUtil().getColor(color); - - if(col == null) - color = "#000000"; - else - color = String.format("%d,%d,%d", col.getRed(), col.getGreen(), col.getBlue()); - - JSONObject json = new JSONObject() - .put("username", member.getUser().getName()) - .put( - "members", - bot.getMsg(member.getGuild().getId(), "misc.welcome_member") - .replace("{count}", String.valueOf(member.getGuild().getMemberCount())) - ) - .put( - "icon", - getUrl("icon", icon, member.getGuild().getOwnerId()) - ) - .put( - "banner", - getUrl("background", bg, member.getGuild().getOwnerId()) - ) - .put( - "avatar", - member.getUser().getEffectiveAvatarUrl() - ) - .put( - "color_welcome", - color - ) - .put( - "color_username", - color - ) - .put( - "color_members", - color - ); - - RequestBody body = RequestBody.create(json.toString(), null); - - Request request = new Request.Builder() - .addHeader("User-Agent", "PurrBot BOT_VERSION") - .addHeader("Content-Type", "application/json") - .addHeader("Authorization", bot.getFileManager().getString("config", "tokens.fluxpoint-dev")) - .post(body) - .url("https://api.fluxpoint.dev/gen/welcome") - .build(); - - try(Response response = CLIENT.newCall(request).execute()){ - if(!response.isSuccessful()) - throw new IOException(String.format( - "Couldn't get welcome image. Server responded with %d (%s)", - response.code(), - response.message() - )); - - ResponseBody responseBody = response.body(); - if(responseBody == null) - return null; - - return new ByteArrayInputStream(responseBody.bytes()); - }catch(IOException ex){ - return null; - } - } - - public boolean isValidImage(String url, int width, int height){ - try{ - URL finalUrl = new URL(url); - URLConnection connection = finalUrl.openConnection(); - connection.setRequestProperty("User-Agent", "PurrBot BOT_VERSION"); - connection.connect(); - - BufferedImage image = ImageIO.read(connection.getInputStream()); - if(image == null) - return false; - - return image.getWidth() == width && image.getHeight() == height; - }catch(IOException ex){ - return false; - } - } - - private String getUrl(String type, String name, String ownerId){ - String baseUrl = "https://purrbot.site/img/sfw/%s/img/%s.png"; - String defaultUrl = String.format(baseUrl, type, type.equalsIgnoreCase("background") ? "color_white" : "purr"); - - int width = type.equalsIgnoreCase("background") ? 2000 : 320; - int height = type.equalsIgnoreCase("background") ? 350 : 320; - - String url = String.format(baseUrl, type, name); - if(name.equalsIgnoreCase("booster")){ - if(bot.getCheckUtil().isBooster(ownerId)) - url = String.format("https://purrbot.site/images/boost/booster_%s.png", type); - else - url = defaultUrl; - }else - if((name.startsWith("https://") || name.startsWith("http://"))){ - if(bot.getCheckUtil().isPatreon(ownerId) && isValidImage(name, width, height)) - url = name; - else - url = defaultUrl; - }else - if(name.equalsIgnoreCase("random")){ - url = bot.getHttpUtil().getImage(String.format("https://purrbot.site/api/img/sfw/%s/img", type)); - } - - return url; - } -} diff --git a/src/main/java/site/purrbot/bot/util/RequestUtil.java b/src/main/java/site/purrbot/bot/util/RequestUtil.java deleted file mode 100644 index 6f7452c53..000000000 --- a/src/main/java/site/purrbot/bot/util/RequestUtil.java +++ /dev/null @@ -1,252 +0,0 @@ -/* - * Copyright 2018 - 2021 Andre601 - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated - * documentation files (the "Software"), to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, - * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or substantial - * portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package site.purrbot.bot.util; - -import ch.qos.logback.classic.Logger; -import com.github.benmanes.caffeine.cache.Cache; -import com.github.benmanes.caffeine.cache.Caffeine; -import com.jagrosh.jdautilities.commons.waiter.EventWaiter; -import net.dv8tion.jda.api.EmbedBuilder; -import net.dv8tion.jda.api.Permission; -import net.dv8tion.jda.api.entities.*; -import net.dv8tion.jda.api.entities.emoji.Emoji; -import net.dv8tion.jda.api.events.interaction.component.ButtonInteractionEvent; -import net.dv8tion.jda.api.interactions.components.buttons.Button; -import net.dv8tion.jda.api.interactions.components.buttons.ButtonStyle; -import org.slf4j.LoggerFactory; -import site.purrbot.bot.PurrBot; -import site.purrbot.bot.constants.Emotes; - -import java.util.Collections; -import java.util.List; -import java.util.concurrent.TimeUnit; - -public class RequestUtil{ - - private final PurrBot bot; - private final Logger logger = (Logger)LoggerFactory.getLogger(RequestUtil.class); - - private final Cache queue = Caffeine.newBuilder() - .expireAfterWrite(2, TimeUnit.MINUTES) - .build(); - - public RequestUtil(PurrBot bot){ - this.bot = bot; - } - - public String getQueueString(String api, String guildId, String authorId){ - return api + ":" + guildId + ":" + authorId; - } - - public Button getButton(String guildId, String buttonId, boolean accept){ - return Button.of( - accept ? ButtonStyle.SUCCESS : ButtonStyle.DANGER, - "purr:" + buttonId + (accept ? ":accept" : ":deny"), - bot.getMsg(guildId, accept ? "request.buttons.accept" : "request.buttons.deny"), - Emoji.fromFormatted((accept ? Emotes.ACCEPT : Emotes.DENY).getEmote()) - ); - } - - public void handleButtonEvent(TextChannel tc, Member author, Member target, HttpUtil.ImageAPI api){ - Guild guild = tc.getGuild(); - - if(queue.getIfPresent(getQueueString(api.getName(), guild.getId(), author.getId())) != null){ - bot.getEmbedUtil().sendError(tc, author, api.getPath() + "request.open"); - return; - } - - String text = bot.getMsg(guild.getId(), api.getPath() + "request.message", author.getEffectiveName(), target.getAsMention()); - - tc.sendMessage( - bot.getMsg(guild.getId(), "request.message") - .replace("{text}", text) - ).setActionRow( - getButton(guild.getId(), api.getName(), true), - getButton(guild.getId(), api.getName(), false) - ).queue( - message -> handleButton(message, tc, author, target, api), - e -> bot.getEmbedUtil().sendError(tc, author, "errors.request_error") - ); - } - - public void handleEdit(TextChannel tc, Message msg, HttpUtil.ImageAPI api){ - handleEdit(tc, msg, api, null, null); - } - - public void handleEdit(TextChannel tc, Message msg, HttpUtil.ImageAPI api, Member author){ - handleEdit(tc, msg, api, author, null); - } - - public void handleEdit(TextChannel tc, Message msg, HttpUtil.ImageAPI api, Member author, List targets){ - bot.getHttpUtil().getImage(api).whenComplete((result, ex) -> { - Guild guild = tc.getGuild(); - String text; - - if(author == null){ - text = bot.getMsg(guild.getId(), result.getPath() + "message"); - }else - if(targets == null){ - text = bot.getMsg(guild.getId(), result.getPath() + "message", author.getEffectiveName()); - }else{ - text = bot.getMsg(guild.getId(), result.getPath() + "message", author.getEffectiveName(), targets); - } - - if(ex != null || result.getUrl() == null){ - if(result.isRequired()){ - bot.getEmbedUtil().sendError(tc, author, "errors.api_error"); - return; - } - - msg.editMessage(text) - .setActionRows(Collections.emptyList()) - .queue(message -> { - if(result.isRequest() && author != null) - sendConfirmation(tc, author, targets, message); - }, e -> tc.sendMessage(text).queue(message -> { - if(result.isRequest() && author != null) - sendConfirmation(tc, author, targets, message); - })); - return; - } - - sendResponse(msg, tc, result, author, targets, text); - }); - } - - private void handleButton(Message msg, TextChannel tc, Member author, Member target, HttpUtil.ImageAPI api){ - queue.put(getQueueString(api.getName(), tc.getGuild().getId(), author.getId()), target.getId()); - - Guild guild = tc.getGuild(); - String channelId = tc.getId(); - EventWaiter waiter = bot.getWaiter(); - - waiter.waitForEvent( - ButtonInteractionEvent.class, - event -> { - if(event.getUser().isBot()) - return false; - - if(event.getMember() == null) - return false; - - if(!event.isAcknowledged()) - event.deferEdit().queue(); - - if(!isValidButton(event.getComponentId(), api.getName())) - return false; - - if(!event.getMember().equals(target)) - return false; - - return event.getMessageId().equals(msg.getId()); - }, - event -> { - TextChannel channel = event.getGuildChannel().asTextChannel(); - queue.invalidate(getQueueString(api.getName(), guild.getId(), author.getId())); - - String result = event.getComponentId().split(":")[2]; - if(result.equals("deny")){ - channel.sendMessage( - bot.getMsg(guild.getId(), api.getPath() + "request.denied", author.getAsMention(), target.getEffectiveName()) - ).queue(); - - msg.delete().queue( - null, - e -> logger.warn("Unable to delete Message for {}. Was it already deleted?", api.getName()) - ); - }else{ - handleEdit(tc, msg, api, author, Collections.singletonList(target.getEffectiveName())); - } - }, - 1, TimeUnit.MINUTES, - () -> { - TextChannel channel = guild.getTextChannelById(channelId); - if(channel == null) - return; - - msg.delete().queue( - null, - e -> logger.warn("Unable to delete Message for {}. Was it already deleted?", api.getName()) - ); - queue.invalidate(getQueueString(api.getName(), guild.getId(), author.getId())); - - channel.sendMessage( - bot.getMsg(guild.getId(), "request.timed_out", author.getAsMention(), target.getEffectiveName()) - ).queue(); - } - ); - } - - private void sendResponse(Message msg, TextChannel tc, HttpUtil.Result result, Member author, List targets, String text){ - String id = tc.getGuild().getId(); - - if(result.getUrl().equalsIgnoreCase("https://purrbot.site/img/sfw/neko/img/neko_136.jpg")){ - if(bot.isBeta()){ - text = bot.getMsg(id, "snuggle.fun.neko.purr"); - }else{ - text = bot.getMsg(id, "purr.fun.neko.purr"); - } - }else - if(result.getUrl().equalsIgnoreCase("https://purrbot.site/img/sfw/neko/img/neko_076.jpg")){ - if(bot.isBeta()){ - text = bot.getMsg(id, "snuggle.fun.neko.snuggle"); - }else{ - text = bot.getMsg(id, "purr.fun.neko.snuggle"); - } - } - - EmbedBuilder embed; - if(result.isRequired() && author != null){ - embed = bot.getEmbedUtil().getEmbed(author); - }else{ - embed = bot.getEmbedUtil().getEmbed(); - } - - embed.setDescription(text) - .setImage(result.getUrl()); - - msg.editMessage(EmbedBuilder.ZERO_WIDTH_SPACE) - .setActionRows(Collections.emptyList()) - .setEmbeds(embed.build()) - .queue(message -> { - if(message.getGuild().getSelfMember().hasPermission(tc, Permission.MESSAGE_MANAGE)) - message.clearReactions().queue( - null, - e -> logger.warn("Unable to clear reactions from Message! Was the message deleted?") - ); - - if(result.isRequest() && author != null) - sendConfirmation(tc, author, targets, message); - }, e -> tc.sendMessageEmbeds(embed.build()).queue(message -> { - if(result.isRequest() && author != null) - sendConfirmation(tc, author, targets, message); - })); - } - - private void sendConfirmation(TextChannel tc, Member author, List targets, Message msg){ - msg.reply( - bot.getMsg(tc.getGuild().getId(), "request.accepted", author.getAsMention(), targets) - ).queue(); - } - - private boolean isValidButton(String buttonId, String apiName){ - return buttonId.equals(String.format("purr:%s:accept", apiName)) || - buttonId.equals(String.format("purr:%s:deny", apiName)); - } -} diff --git a/src/main/java/site/purrbot/bot/util/file/FileManager.java b/src/main/java/site/purrbot/bot/util/file/FileManager.java deleted file mode 100644 index a9d6ea051..000000000 --- a/src/main/java/site/purrbot/bot/util/file/FileManager.java +++ /dev/null @@ -1,199 +0,0 @@ -/* - * Copyright 2018 - 2021 Andre601 - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated - * documentation files (the "Software"), to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, - * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or substantial - * portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package site.purrbot.bot.util.file; - -import ch.qos.logback.classic.Logger; -import com.google.gson.Gson; -import com.google.gson.JsonElement; -import com.google.gson.JsonParser; -import com.google.gson.reflect.TypeToken; -import com.google.gson.stream.JsonReader; -import org.slf4j.LoggerFactory; -import site.purrbot.bot.PurrBot; - -import java.io.*; -import java.lang.reflect.Type; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.nio.file.StandardCopyOption; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class FileManager{ - - private final Logger logger = (Logger)LoggerFactory.getLogger(FileManager.class); - private Map files; - private List languages; - - public FileManager(){} - - public FileManager addFile(String name, String internal, String external){ - createOrLoad(name, internal, external); - - return this; - } - - // Convenience method do add new languages more easy. - public FileManager addLang(String file){ - if(languages == null) - languages = new ArrayList<>(); - - languages.add(file.toLowerCase()); - return addFile(file.toLowerCase(), "/lang/" + file + ".json", "./lang/" + file + ".json"); - } - - public Map getFiles(){ - return files; - } - - public List getLanguages(){ - return languages; - } - - public void createOrLoad(String name, String internal, String external){ - if(files == null) - files = new HashMap<>(); - - File file = new File(external); - String[] split = external.split("/"); - - try{ - if(!file.exists()){ - if((split.length == 2 && !split[0].equals(".")) || (split.length >= 3 && split[0].equals("."))){ - if(!file.getParentFile().mkdirs() && !file.getParentFile().exists()){ - logger.warn("Failed to create directory {}", split[1]); - return; - } - } - if(file.createNewFile()){ - if(export(PurrBot.class.getResourceAsStream(internal), external)){ - logger.info("Successfully created {}!", name); - files.put(name, file); - }else{ - logger.warn("Failed to create {}!", name); - } - } - }else{ - logger.info("Successfully loaded {}!", name); - - files.put(name, file); - } - }catch(IOException ex){ - logger.warn("Couldn't create nor load {}", name, ex); - } - } - - public String getString(String name, String path){ - File file = files.get(name); - - if(file == null) - return ""; - - try{ - JsonReader reader = new JsonReader(new FileReader(file)); - JsonElement json = JsonParser.parseReader(reader); - - for(String key : path.split("\\.")){ - if(!json.isJsonObject()) - break; - - json = json.getAsJsonObject().get(key); - } - - if(json == null || json.isJsonNull()) - return ""; - - return json.getAsString(); - }catch(FileNotFoundException ex){ - logger.warn("Couldn't find \"{}\" in file {}.json", path, name, ex); - return ""; - } - } - - public boolean getBoolean(String name, String path){ - File file = files.get(name); - - if(file == null) - return false; - - try{ - JsonReader reader = new JsonReader(new FileReader(file)); - JsonElement json = JsonParser.parseReader(reader); - - for(String key : path.split("\\.")){ - if(!json.isJsonObject()) - break; - - json = json.getAsJsonObject().get(key); - } - - if(json == null || json.isJsonNull()) - return false; - - return json.getAsBoolean(); - }catch(FileNotFoundException ex){ - logger.warn("Couldn't find \"{}\" in file {}.json", path, name, ex); - return false; - } - } - - public List getStringlist(String name, String path){ - File file = files.get(name); - - if(file == null) - return new ArrayList<>(); - - try{ - JsonReader reader = new JsonReader(new FileReader(file)); - JsonElement json = JsonParser.parseReader(reader); - - for(String key : path.split("\\.")){ - if(!json.isJsonObject()) - break; - - json = json.getAsJsonObject().get(key); - } - - if(json == null || json.isJsonNull()) - return new ArrayList<>(); - - Gson gson = new Gson(); - Type type = new TypeToken>(){}.getType(); - - return gson.fromJson(json.getAsJsonArray(), type); - - }catch(FileNotFoundException ex){ - logger.warn("Couldn't find \"{}\" in file {}.json", path, name, ex); - return new ArrayList<>(); - } - } - - private boolean export(InputStream inputStream, String destination){ - boolean success = true; - try{ - Files.copy(inputStream, Paths.get(destination), StandardCopyOption.REPLACE_EXISTING); - }catch(IOException ex){ - success = false; - } - - return success; - } -} diff --git a/src/main/java/site/purrbot/bot/util/file/lang/LangUtils.java b/src/main/java/site/purrbot/bot/util/file/lang/LangUtils.java deleted file mode 100644 index e33146e10..000000000 --- a/src/main/java/site/purrbot/bot/util/file/lang/LangUtils.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * Copyright 2018 - 2021 Andre601 - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated - * documentation files (the "Software"), to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, - * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or substantial - * portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package site.purrbot.bot.util.file.lang; - -import site.purrbot.bot.PurrBot; - -import java.util.List; - -public final class LangUtils{ - - private final PurrBot bot; - public LangUtils(PurrBot bot){ - this.bot = bot; - } - - public String getString(String language, String path){ - switch(language.toLowerCase()){ - case "de-ch": - case "de-de": - case "en-owo": - case "es-es": - case "fr-fr": - case "ko-kr": - case "pt-br": - case "ru-ru": - case "tr-tr": - return bot.getFileManager().getString(language.toLowerCase(), path); - - case "it-it": - case "et-ee": - default: - return bot.getFileManager().getString("en", path); - } - } - - public List getStringList(String language, String path){ - switch(language.toLowerCase()){ - case "de-ch": - case "de-de": - case "en-owo": - case "es-es": - case "fr-fr": - case "ko-kr": - case "pt-br": - case "ru-ru": - case "tr-tr": - return bot.getFileManager().getStringlist(language.toLowerCase(), path); - - case "it-it": - case "et-ee": - default: - return bot.getFileManager().getStringlist("en", path); - } - } - - public enum Language{ - DE_CH ("\uDDE8", "\uDDED"), - DE_DE ("\uDDE9", "\uDDEA"), - EN ("\uDDEC", "\uDDE7"), - EN_OWO("\uDDEC", "\uDDE7"), - ES_ES ("\uDDEA", "\uDDF8"), - //ET_EE ("\uDDEA", "\uDDEA"), - FR_FR ("\uDDEB", "\uDDF7"), - //IT_IT ("\uDDEE", "\uDDF9"), - KO_KR ("\uDDF0", "\uDDF7"), - PT_BR ("\uDDE7", "\uDDF7"), - RU_RU ("\uDDF7", "\uDDFA"), - TR_TR ("\uDDF9", "\uDDF7"), - - UNKNOWN("\uDDFA", "\uDDF3"); - - private final String emote; - - Language(String code1, String code2){ - this.emote = "\uD83C" + code1 + "\uD83C" + code2; - } - - public static String getEmote(String lang){ - for(Language language : values()){ - if(lang.equals(language.name().toLowerCase().replace("_", "-"))) - return language.emote; - } - - return UNKNOWN.emote; - } - - public static String getString(String lang){ - for(Language language : values()){ - if(lang.equals(language.name().toLowerCase().replace("_", "-"))) - return language.emote + " " + lang; - } - - return UNKNOWN.emote + " " + UNKNOWN.name().toLowerCase(); - } - } -} diff --git a/src/main/java/site/purrbot/bot/util/message/EmbedUtil.java b/src/main/java/site/purrbot/bot/util/message/EmbedUtil.java deleted file mode 100644 index ac20b9d77..000000000 --- a/src/main/java/site/purrbot/bot/util/message/EmbedUtil.java +++ /dev/null @@ -1,142 +0,0 @@ -/* - * Copyright 2018 - 2021 Andre601 - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated - * documentation files (the "Software"), to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, - * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or substantial - * portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package site.purrbot.bot.util.message; - -import net.dv8tion.jda.api.EmbedBuilder; -import net.dv8tion.jda.api.Permission; -import net.dv8tion.jda.api.entities.Guild; -import net.dv8tion.jda.api.entities.Member; -import net.dv8tion.jda.api.entities.MessageEmbed; -import net.dv8tion.jda.api.entities.TextChannel; -import site.purrbot.bot.PurrBot; - -import java.time.ZonedDateTime; - -public class EmbedUtil { - - private final PurrBot bot; - - public EmbedUtil(PurrBot bot){ - this.bot = bot; - } - - public EmbedBuilder getEmbed(){ - return new EmbedBuilder().setColor(0x802F3136).setTimestamp(ZonedDateTime.now()); - } - - public EmbedBuilder getEmbed(Member member){ - return getEmbed().setFooter( - bot.getMsg(member.getGuild().getId(), "embed.footer", member.getUser().getAsTag(), false), - member.getUser().getEffectiveAvatarUrl() - ); - } - - public EmbedBuilder getErrorEmbed(Member member){ - return (member == null ? getEmbed() : getEmbed(member)).setColor(0xFF0000); - } - - public MessageEmbed getPermErrorEmbed(Member member, Guild guild, TextChannel channel, Permission perm, boolean self){ - EmbedBuilder embed = getErrorEmbed(member); - String msg; - if(self){ - if(channel == null){ - msg = bot.getMsg(guild.getId(), "errors.missing_perms.self") - .replace("{permission}", perm.getName()); - }else{ - msg = bot.getMsg(guild.getId(), "errors.missing_perms.self_channel") - .replace("{permission}", perm.getName()) - .replace("{channel}", channel.getAsMention()); - } - }else{ - if(channel == null){ - msg = bot.getMsg(guild.getId(), "errors.missing_perms.other") - .replace("{permission}", perm.getName()); - }else{ - msg = bot.getMsg(guild.getId(), "errors.missing_perms.other_channel") - .replace("{permission}", perm.getName()) - .replace("{channel}", channel.getAsMention()); - } - } - - return embed.setDescription(msg).build(); - - } - - public void sendError(TextChannel tc, Member member, String path){ - sendError(tc, member, path, false); - } - - public void sendError(TextChannel tc, Member member, String path, boolean random){ - sendError(tc, member, path, null, random); - } - - public void sendError(TextChannel tc, Member member, String path, String reason, boolean random){ - Guild guild = tc.getGuild(); - - EmbedBuilder embed = getErrorEmbed(member); - String msg; - if(random){ - msg = member == null ? bot.getRandomMsg(guild.getId(), path) : bot.getRandomMsg(guild.getId(), path, member.getEffectiveName()); - }else{ - msg = member == null ? bot.getMsg(guild.getId(), path) : bot.getMsg(guild.getId(), path, member.getEffectiveName()); - } - - embed.setDescription(msg); - - if(reason != null) - embed.addField( - "Error:", - reason, - false - ); - - tc.sendMessageEmbeds(embed.build()).queue(); - } - - - public void sendPermError(TextChannel tc, Member member, Permission permission, boolean self){ - sendPermError(tc, member, null, permission, self); - } - - public void sendPermError(TextChannel tc, Member member, TextChannel channel, Permission permission, boolean self){ - if(permission.equals(Permission.MESSAGE_EMBED_LINKS)){ - if(channel == null){ - tc.sendMessage( - bot.getMsg( - tc.getGuild().getId(), - "errors.missing_perms.self" - ) - .replace("{permission}", permission.getName()) - ).queue(); - }else{ - tc.sendMessage( - bot.getMsg( - tc.getGuild().getId(), - "errors.missing_perms.self_channel" - ) - .replace("{permission}", permission.getName()) - .replace("{channel}", channel.getAsMention()) - ).queue(); - } - return; - } - - tc.sendMessageEmbeds(getPermErrorEmbed(member, tc.getGuild(), channel, permission, self)).queue(); - } -} diff --git a/src/main/java/site/purrbot/bot/util/message/MessageUtil.java b/src/main/java/site/purrbot/bot/util/message/MessageUtil.java deleted file mode 100644 index c7b00faf9..000000000 --- a/src/main/java/site/purrbot/bot/util/message/MessageUtil.java +++ /dev/null @@ -1,290 +0,0 @@ -/* - * Copyright 2018 - 2021 Andre601 - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated - * documentation files (the "Software"), to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, - * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or substantial - * portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package site.purrbot.bot.util.message; - -import net.dv8tion.jda.api.Permission; -import net.dv8tion.jda.api.entities.*; -import net.dv8tion.jda.api.utils.TimeFormat; -import site.purrbot.bot.PurrBot; - -import java.awt.Color; -import java.io.InputStream; -import java.text.DecimalFormat; -import java.time.temporal.TemporalAccessor; -import java.util.Arrays; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -public class MessageUtil { - - private final PurrBot bot; - - private final Pattern placeholder = Pattern.compile("(\\{(.+?)})", Pattern.CASE_INSENSITIVE); - private final Pattern rolePattern = Pattern.compile("(\\{r_(name|mention):(\\d+)})", Pattern.CASE_INSENSITIVE); - private final Pattern channelPattern = Pattern.compile("(\\{c_(name|mention):(\\d+)})", Pattern.CASE_INSENSITIVE); - - private final DecimalFormat decimalFormat = new DecimalFormat("#,###,###"); - - public MessageUtil(PurrBot bot){ - this.bot = bot; - } - - public String getRandomShutdownImg(){ - return bot.getShutdownImg().isEmpty() ? "" : bot.getShutdownImg().get( - bot.getRandom().nextInt(bot.getShutdownImg().size()) - ); - } - - public String getRandomShutdownMsg(){ - return bot.getShutdownMsg().isEmpty() ? "" : bot.getShutdownMsg().get( - bot.getRandom().nextInt(bot.getShutdownMsg().size()) - ); - } - - public String getRandomStartupMsg(){ - return bot.getStartupMsg().isEmpty() ? "Starting bot..." : bot.getStartupMsg().get( - bot.getRandom().nextInt(bot.getStartupMsg().size()) - ); - } - - public String formatTime(TemporalAccessor time){ - return String.format( - "%s (%s)", - TimeFormat.DATE_TIME_SHORT.format(time), - TimeFormat.RELATIVE.format(time) - ); - } - - public Color getColor(String input){ - input = input.toLowerCase(); - if(!input.equals("random") && !(input.startsWith("hex:") || input.startsWith("rgb:"))) - return null; - - Color color = null; - - if(input.equals("random")){ - int r = bot.getRandom().nextInt(256); - int g = bot.getRandom().nextInt(256); - int b = bot.getRandom().nextInt(256); - - return new Color(r, g, b); - } - - String[] split = input.split(":"); - if(split.length <= 1) - return null; - - String value = split[1]; - - switch(split[0]){ - case "hex": - if(value.isEmpty()) - return null; - try{ - color = Color.decode(value.startsWith("#") ? value : "#" + value); - }catch(NumberFormatException ignored){ - return null; - } - break; - - case "rgb": - if(value.isEmpty()) - return null; - - String[] rgb = Arrays.copyOf(value.split(","), 3); - - try{ - color = new Color(Integer.parseInt(rgb[0]), Integer.parseInt(rgb[1]), Integer.parseInt(rgb[2])); - }catch(NumberFormatException ignored){ - return null; - } - } - - return color; - } - - public void sendWelcomeMsg(TextChannel tc, String message, Member member, InputStream file){ - Guild guild = member.getGuild(); - - message = formatPlaceholders(message, member); - - if(file == null || !guild.getSelfMember().hasPermission(tc, Permission.MESSAGE_ATTACH_FILES)){ - tc.sendMessage(message).queue(); - return; - } - - tc.sendMessage(message) - .addFile(file, String.format( - "welcome_%s.jpg", - member.getId() - )) - .queue(); - } - - public String formatPlaceholders(String msg, Member member){ - Guild guild = member.getGuild(); - - Matcher roleMatcher = rolePattern.matcher(msg); - if(roleMatcher.find()){ - StringBuilder builder = new StringBuilder(); - do{ - Role role = guild.getRoleById(roleMatcher.group(3)); - if(role == null) - continue; - - switch(roleMatcher.group(2).toLowerCase()){ - case "name": - roleMatcher.appendReplacement(builder, role.getName()); - break; - - case "mention": - roleMatcher.appendReplacement(builder, role.getAsMention()); - break; - } - }while(roleMatcher.find()); - - roleMatcher.appendTail(builder); - msg = builder.toString(); - } - - Matcher channelMatcher = channelPattern.matcher(msg); - if(channelMatcher.find()){ - StringBuilder builder = new StringBuilder(); - do{ - GuildChannel channel = guild.getGuildChannelById(channelMatcher.group(3)); - if(channel == null) - continue; - - switch(channelMatcher.group(2).toLowerCase()){ - case "name": - channelMatcher.appendReplacement(builder, channel.getName()); - break; - - case "mention": - if(channel.getType().equals(ChannelType.CATEGORY)) - continue; - - channelMatcher.appendReplacement(builder, channel.getAsMention()); - break; - } - }while(channelMatcher.find()); - - channelMatcher.appendTail(builder); - msg = builder.toString(); - } - - Matcher matcher = placeholder.matcher(msg); - if(matcher.find()){ - StringBuilder builder = new StringBuilder(); - do{ - switch(matcher.group(2).toLowerCase()){ - case "mention": - matcher.appendReplacement(builder, member.getAsMention()); - break; - - case "name": - case "username": - matcher.appendReplacement(builder, member.getEffectiveName()); - break; - - case "guild": - case "server": - matcher.appendReplacement(builder, guild.getName()); - break; - - case "count": - case "members": - matcher.appendReplacement(builder, String.valueOf(guild.getMemberCount())); - break; - - case "count_formatted": - case "members_formatted": - matcher.appendReplacement(builder, formatNumber(guild.getMemberCount())); - break; - - case "tag": - matcher.appendReplacement(builder, member.getUser().getAsTag()); - } - }while(matcher.find()); - - matcher.appendTail(builder); - msg = builder.toString(); - } - - return msg; - } - - public String getBotGame(long guilds){ - String game = bot.isBeta() ? "My sister on %s guilds." : "https://purrbot.site | %s Guilds"; - - - return String.format(game, formatNumber(guilds)); - } - - public String getFormattedMembers(String id, String... members){ - if(members.length == 1) - return "**" + escapeAll(members[0]) + "**"; - - StringBuilder builder = new StringBuilder(); - for(String member : members){ - if(builder.length() > 0) - builder.append(", "); - - builder.append("**").append(escapeAll(member)).append("**"); - } - - return replaceLast(builder.toString(), ",", " " + bot.getMsg(id, "misc.and")); - } - - public String replaceLast(String input, String target, String replacement){ - if(!input.contains(target)) - return input; - - StringBuilder builder = new StringBuilder(input); - builder.replace(input.lastIndexOf(target), input.lastIndexOf(target) + 1, replacement); - - return builder.toString(); - } - - public String formatNumber(long number){ - return decimalFormat.format(number); - } - - public boolean hasArg(String value, String... args){ - if(args.length == 0) - return false; - - for(String arg : args){ - if(arg.equalsIgnoreCase("--" + value)) - return true; - - if(arg.equalsIgnoreCase("—" + value)) - return true; - } - - return false; - } - - private String escapeAll(String name){ - return name.replace("*", "\\*") - .replace("_", "\\_") - .replace("`", "\\`") - .replace("~", "\\~"); - } -} diff --git a/src/main/java/site/purrbot/bot/util/message/WebhookUtil.java b/src/main/java/site/purrbot/bot/util/message/WebhookUtil.java deleted file mode 100644 index 702a24b7c..000000000 --- a/src/main/java/site/purrbot/bot/util/message/WebhookUtil.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright 2018 - 2021 Andre601 - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated - * documentation files (the "Software"), to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, - * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or substantial - * portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, - * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. - * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, - * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE - * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - */ - -package site.purrbot.bot.util.message; - -import club.minnced.discord.webhook.WebhookClient; -import club.minnced.discord.webhook.WebhookClientBuilder; -import club.minnced.discord.webhook.send.WebhookEmbed; -import club.minnced.discord.webhook.send.WebhookMessage; -import club.minnced.discord.webhook.send.WebhookMessageBuilder; - -public class WebhookUtil { - - private final WebhookClient client; - - public WebhookUtil(String url){ - client = new WebhookClientBuilder(url).build(); - } - - public void sendMsg(String avatar, String name, String message, WebhookEmbed embed){ - - WebhookMessage msg = new WebhookMessageBuilder() - .setAvatarUrl(avatar) - .setUsername(name) - .setContent(message) - .addEmbeds(embed) - .build(); - - client.send(msg); - } - - public void sendMsg(String avatar, String name, WebhookEmbed embed){ - sendMsg(avatar, name, null, embed); - } -} From 40dada85c311da24905710257d7e33f46ba9ff29 Mon Sep 17 00:00:00 2001 From: Andre601 <11576465+Andre601@users.noreply.github.com> Date: Fri, 19 Aug 2022 13:35:50 +0200 Subject: [PATCH 2/6] push --- build.gradle | 2 + src/main/java/site/purrbot/bot/PurrBot.java | 83 +++++++- .../site/purrbot/bot/command/BotCommand.java | 78 ++++++++ .../purrbot/bot/command/ImageAPICommand.java | 45 +++++ .../site/purrbot/bot/command/fun/CmdBite.java | 90 +++++++++ .../site/purrbot/bot/constants/Emotes.java | 115 +++++++++++ .../site/purrbot/bot/manager/DBManager.java | 104 ++++++++++ .../purrbot/bot/manager/EmbedManager.java | 50 +++++ .../purrbot/bot/manager/api/ImageAPI.java | 99 ++++++++++ .../api/response/GenericAPIResponse.java | 26 +++ .../api/response/ImageAPIErrorResponse.java | 48 +++++ .../api/response/ImageAPISuccessResponse.java | 42 ++++ .../bot/manager/command/CommandError.java | 68 +++++++ .../bot/manager/command/CommandLoader.java | 46 +++++ .../bot/manager/command/CommandUtil.java | 86 ++++++++ .../purrbot/bot/manager/file/FileManager.java | 158 +++++++++++++++ .../manager/guild/GuildSettingsManager.java | 184 ++++++++++++++++++ .../bot/manager/string/MessageHandler.java | 83 ++++++++ .../bot/manager/string/StringReplacer.java | 49 +++++ 19 files changed, 1455 insertions(+), 1 deletion(-) create mode 100644 src/main/java/site/purrbot/bot/command/BotCommand.java create mode 100644 src/main/java/site/purrbot/bot/command/ImageAPICommand.java create mode 100644 src/main/java/site/purrbot/bot/command/fun/CmdBite.java create mode 100644 src/main/java/site/purrbot/bot/constants/Emotes.java create mode 100644 src/main/java/site/purrbot/bot/manager/DBManager.java create mode 100644 src/main/java/site/purrbot/bot/manager/EmbedManager.java create mode 100644 src/main/java/site/purrbot/bot/manager/api/ImageAPI.java create mode 100644 src/main/java/site/purrbot/bot/manager/api/response/GenericAPIResponse.java create mode 100644 src/main/java/site/purrbot/bot/manager/api/response/ImageAPIErrorResponse.java create mode 100644 src/main/java/site/purrbot/bot/manager/api/response/ImageAPISuccessResponse.java create mode 100644 src/main/java/site/purrbot/bot/manager/command/CommandError.java create mode 100644 src/main/java/site/purrbot/bot/manager/command/CommandLoader.java create mode 100644 src/main/java/site/purrbot/bot/manager/command/CommandUtil.java create mode 100644 src/main/java/site/purrbot/bot/manager/file/FileManager.java create mode 100644 src/main/java/site/purrbot/bot/manager/guild/GuildSettingsManager.java create mode 100644 src/main/java/site/purrbot/bot/manager/string/MessageHandler.java create mode 100644 src/main/java/site/purrbot/bot/manager/string/StringReplacer.java diff --git a/build.gradle b/build.gradle index 81f807177..89bc615db 100644 --- a/build.gradle +++ b/build.gradle @@ -54,6 +54,8 @@ dependencies { compile group: 'club.minnced', name: 'discord-webhooks', version: '0.8.2' compile group: 'com.github.ben-manes.caffeine', name: 'caffeine', version: '3.1.1' compile group: 'com.squareup.okhttp3', name: 'okhttp', version: '4.10.0' + compile group: 'com.google.code.gson', name: 'gson', version: '2.8.7' + compile group: 'org.spongepowered', name: 'configurate-gson', version: '4.1.2' } compileJava { diff --git a/src/main/java/site/purrbot/bot/PurrBot.java b/src/main/java/site/purrbot/bot/PurrBot.java index caf539c69..68a204ed8 100644 --- a/src/main/java/site/purrbot/bot/PurrBot.java +++ b/src/main/java/site/purrbot/bot/PurrBot.java @@ -21,10 +21,24 @@ import ch.qos.logback.classic.Logger; import com.jagrosh.jdautilities.command.CommandClient; import com.jagrosh.jdautilities.commons.waiter.EventWaiter; +import net.dv8tion.jda.api.OnlineStatus; +import net.dv8tion.jda.api.entities.Activity; +import net.dv8tion.jda.api.entities.Message; +import net.dv8tion.jda.api.requests.GatewayIntent; +import net.dv8tion.jda.api.requests.restaction.MessageAction; +import net.dv8tion.jda.api.sharding.DefaultShardManagerBuilder; import net.dv8tion.jda.api.sharding.ShardManager; +import net.dv8tion.jda.api.utils.ChunkingFilter; +import net.dv8tion.jda.api.utils.MemberCachePolicy; +import net.dv8tion.jda.api.utils.cache.CacheFlag; import org.slf4j.LoggerFactory; +import site.purrbot.bot.manager.DBManager; +import site.purrbot.bot.manager.command.CommandLoader; +import site.purrbot.bot.manager.file.FileManager; +import site.purrbot.bot.manager.guild.GuildSettingsManager; import javax.security.auth.login.LoginException; +import java.util.EnumSet; import java.util.Random; public class PurrBot{ @@ -33,7 +47,10 @@ public class PurrBot{ private static PurrBot bot; // Bot classes - + FileManager fileManager; + DBManager dbManager; + GuildSettingsManager guildSettingsManager; + CommandLoader commandLoader; // JDA private ShardManager shardManager = null; @@ -56,7 +73,71 @@ public static void main(String[] args){ } } + // Getter methods + public static PurrBot getBot(){ + return bot; + } + + public FileManager getFileManager(){ + return fileManager; + } + + public DBManager getDbManager(){ + return dbManager; + } + + public GuildSettingsManager getGuildSettingsManager(){ + return guildSettingsManager; + } + + public CommandLoader getCommandLoader(){ + return commandLoader; + } + + public ShardManager getShardManager(){ + return shardManager; + } + + public EventWaiter getEventWaiter(){ + return eventWaiter; + } + + public Random getRandom(){ + return random; + } + + + private void startBot() throws LoginException{ + fileManager = new FileManager(); + dbManager = new DBManager(); + guildSettingsManager = new GuildSettingsManager(); + commandLoader = new CommandLoader(); + + fileManager.addFile("config") + .addFile("random"); + + MessageAction.setDefaultMentions(EnumSet.of( + Message.MentionType.USER, + Message.MentionType.ROLE + )); + shardManager = DefaultShardManagerBuilder.createDefault(fileManager.getString("config", "", "token")) + .disableIntents(GatewayIntent.GUILD_VOICE_STATES) + .disableCache(CacheFlag.VOICE_STATE) + .enableIntents( + GatewayIntent.GUILD_MEMBERS, + GatewayIntent.GUILD_MESSAGES, + GatewayIntent.MESSAGE_CONTENT + ) + .setChunkingFilter(ChunkingFilter.include(0L)) + .setMemberCachePolicy(MemberCachePolicy.OWNER) + .addEventListeners( + commandClient + ) + .setActivity(Activity.of(Activity.ActivityType.PLAYING, "TODO")) + .setStatus(OnlineStatus.DO_NOT_DISTURB) + .addEventListeners() + .build(); } } diff --git a/src/main/java/site/purrbot/bot/command/BotCommand.java b/src/main/java/site/purrbot/bot/command/BotCommand.java new file mode 100644 index 000000000..bc5ef916a --- /dev/null +++ b/src/main/java/site/purrbot/bot/command/BotCommand.java @@ -0,0 +1,78 @@ +/* + * Copyright 2018 - 2022 Andre601 + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated + * documentation files (the "Software"), to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial + * portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +package site.purrbot.bot.command; + +import com.jagrosh.jdautilities.command.SlashCommand; +import com.jagrosh.jdautilities.command.SlashCommandEvent; +import net.dv8tion.jda.api.entities.Guild; +import net.dv8tion.jda.api.entities.Member; +import net.dv8tion.jda.api.entities.TextChannel; +import net.dv8tion.jda.api.interactions.InteractionHook; +import site.purrbot.bot.PurrBot; +import site.purrbot.bot.manager.command.CommandError; +import site.purrbot.bot.manager.string.MessageHandler; + +import java.util.Arrays; + +public abstract class BotCommand extends SlashCommand{ + + protected String[] replyMsgPath = new String[]{"misc", "default_loading"}; + + @Override + protected void execute(SlashCommandEvent event){ + Guild guild = event.getGuild(); + if(guild == null){ + CommandError.fromStatic("Commands can only be executed in a Server.").send(event); + return; + } + + Member member = event.getMember(); + if(member == null){ + CommandError.fromPath(guild.getId(), "errors", "null_member").send(event); + return; + } + + BotCommand command = Arrays.stream(PurrBot.getBot().getCommandLoader().getCommands()) + .filter(cmd -> cmd.getName().equals(event.getName())) + .findFirst() + .orElse(null); + + if(command == null){ + CommandError.fromPath(guild.getId(), "errors", "no_command_found") + .replace("{command}", event.getName()) + .send(event); + return; + } + + TextChannel tc = event.getTextChannel(); + + if(command.nsfwOnly && !tc.isNSFW()){ + CommandError.fromPath(guild.getId(), "errors", "no_nsfw") + .replace("{user}", member.getEffectiveName()) + .send(event); + return; + } + + event.reply(MessageHandler.getTranslation(guild.getId(), replyMsgPath).getMessage()).queue( + hook -> handle(event, hook, guild, tc, member) + ); + } + + protected abstract void handle(SlashCommandEvent event, InteractionHook hook, Guild guild, TextChannel tc, Member member); +} diff --git a/src/main/java/site/purrbot/bot/command/ImageAPICommand.java b/src/main/java/site/purrbot/bot/command/ImageAPICommand.java new file mode 100644 index 000000000..c32c95902 --- /dev/null +++ b/src/main/java/site/purrbot/bot/command/ImageAPICommand.java @@ -0,0 +1,45 @@ +/* + * Copyright 2018 - 2022 Andre601 + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated + * documentation files (the "Software"), to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial + * portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +package site.purrbot.bot.command; + +public abstract class ImageAPICommand extends BotCommand{ + + protected String apiName = null; + protected String[] apiMessagePath = null; + protected boolean apiGif = false; + protected boolean apiNsfw = false; + protected boolean apiRequest = false; + protected boolean apiRequired = false; + + public String getUrl(){ + return String.format("https://purrbot.site/api/img/%s/%s/%s", apiNsfw ? "nsfw" : "sfw", apiName, apiGif ? "gif" : "img"); + } + + public String[] getMessagePath(){ + return apiMessagePath; + } + + public boolean isRequest(){ + return apiRequest; + } + + public boolean isRequired(){ + return apiRequired; + } +} diff --git a/src/main/java/site/purrbot/bot/command/fun/CmdBite.java b/src/main/java/site/purrbot/bot/command/fun/CmdBite.java new file mode 100644 index 000000000..9eafae5be --- /dev/null +++ b/src/main/java/site/purrbot/bot/command/fun/CmdBite.java @@ -0,0 +1,90 @@ +/* + * Copyright 2018 - 2022 Andre601 + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated + * documentation files (the "Software"), to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial + * portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +package site.purrbot.bot.command.fun; + +import com.jagrosh.jdautilities.command.SlashCommandEvent; +import net.dv8tion.jda.api.entities.Guild; +import net.dv8tion.jda.api.entities.Member; +import net.dv8tion.jda.api.entities.TextChannel; +import net.dv8tion.jda.api.entities.User; +import net.dv8tion.jda.api.interactions.InteractionHook; +import net.dv8tion.jda.api.interactions.commands.OptionType; +import net.dv8tion.jda.api.interactions.commands.build.OptionData; +import site.purrbot.bot.command.ImageAPICommand; +import site.purrbot.bot.manager.api.ImageAPI; +import site.purrbot.bot.manager.command.CommandError; +import site.purrbot.bot.manager.command.CommandUtil; +import site.purrbot.bot.manager.string.MessageHandler; + +import java.util.Arrays; +import java.util.List; + +public class CmdBite extends ImageAPICommand{ + + public CmdBite(){ + this.name = "bite"; + this.help = "Bite some people."; + this.guildOnly = true; + + this.replyMsgPath = new String[]{"purr", "fun", "bite", "loading"}; + + this.apiName = "bite"; + this.apiMessagePath = new String[]{"purr", "fun", "bite", "message"}; + this.apiGif = true; + + this.options = Arrays.asList( + new OptionData(OptionType.USER, "user", "The first user to bite. Required.").setRequired(true), + new OptionData(OptionType.USER, "user2", "The second user to bite."), + new OptionData(OptionType.USER, "user3", "The second user to bite.") + ); + } + + @Override + protected void handle(SlashCommandEvent event, InteractionHook hook, Guild guild, TextChannel tc, Member member){ + List users = CommandUtil.getUsers(event, "user", "user2", "user3"); + if(users.isEmpty()){ + CommandError.fromPath(guild.getId(), "errors", "no_users_provided").send(hook); + return; + } + + if(users.contains(hook.getJDA().getSelfUser())){ + String msg = MessageHandler.getTranslation(guild.getId(), "purr", "fun", "bite", "mention_purr") + .replace("{user}", member.getAsMention()) + .getMessage(); + + tc.sendMessage(msg).queue(); + } + + if(users.contains(member.getUser())){ + String msg = MessageHandler.getTranslation(guild.getId(), "purr", "fun", "bite", "mention_self") + .replace("{user}", member.getAsMention()) + .getMessage(); + + tc.sendMessage(msg).queue(); + } + + String names = CommandUtil.convertUsersToString(guild.getId(), users, member.getUser()); + if(names == null || names.isEmpty()){ + hook.deleteOriginal().queue(); + return; + } + + ImageAPI.returnImage(hook, guild.getId(), this, member, names); + } +} diff --git a/src/main/java/site/purrbot/bot/constants/Emotes.java b/src/main/java/site/purrbot/bot/constants/Emotes.java new file mode 100644 index 000000000..20c644f7f --- /dev/null +++ b/src/main/java/site/purrbot/bot/constants/Emotes.java @@ -0,0 +1,115 @@ +/* + * Copyright 2018 - 2022 Andre601 + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated + * documentation files (the "Software"), to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial + * portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +package site.purrbot.bot.constants; + +import site.purrbot.bot.manager.string.StringReplacer; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public enum Emotes{ + // Animated emotes, + LOADING ("loading", "858052734859345930", true), + SENKO_TAIL_WAG("senkoTailWag", "858053594081918996", true), + SHIRO_TAIL_WAG("shiroTailWag", "858053594162135070", true), + TYPING ("typing", "858052735063818260", true), + + // Static/normal emotes + ACCEPT ("accept", "858052657204559872", false), + AWOO ("awoo", "858074817822195727", false), + BLANK ("blank", "669291169951252560", false), + BLOB_HOLO ("blobHolo", "858052852680622125", false), + BLUSH ("vanillaBlush", "858052852562526208", false), + BOOST_LEVEL_1 ("boost_level_1", "857291736133009489", false), + BOOST_LEVEL_2 ("boost_level_2", "857291736118984715", false), + BOOST_LEVEL_3 ("boost_level_3", "857291735906517003", false), + BOT ("bot", "855436906119299082", false), + BOT_TAG_1 ("botTag_1", "855439119005646908", false), + BOT_TAG_2 ("botTag_2", "855439119152054302", false), + BUGHUNTER ("bughunter", "857290795169611777", false), + BUGHUNTER_GOLD ("bughunterGold", "857290795530321960", false), + CATEGORY ("category", "855418148798857226", false), + CERTIFIED_MOD ("certifiedMod", "857290795438571520", false), + CLYDE ("clyde", "855436906100031489", false), + DENY ("deny", "858052657151475722", false), + DISCOVER ("discover", "855418148558471199", false), + DOWNLOAD ("download", "855439118997258270", false), + EARLY_SUPPORTER ("earlySupporter", "857290795640291370", false), + EARLY_VERIFIED_BOT_DEV("earlyVerifiedBotDev", "857290795194515516", false), + GIF ("gif", "855418148903714841", false), + HYPESQUAD_BALANCE ("hypesquadBalance", "857290795002363905", false), + HYPESQUAD_BRAVERY ("hypesquadBravery", "857290795505680434", false), + HYPESQUAD_BRILLIANCE ("hypesquadBrilliance", "857290795534516275", false), + HYPESQUAD_EVENTS ("hypesquadEvents", "857290795639504926", false), + IMAGES ("images", "855443695007301643", false), + INVITE ("invite", "855418148458332162", false), + KOFI ("kofi", "858075879837401098", false), + MEMBERS ("members", "855418149028495410", false), + MINUS ("minus", "592043203042213925", false), + NEKOWO ("nekOwO", "858052852717715475", false), + NEWS ("news", "855418148811440128", false), + OWNER ("owner", "855436906287988756", false), + PARTNER ("partner", "855418148962435082", false), + PARTNER_BADGE ("partner", "857290795581046864", false), + PATREON ("patreon", "858052657339957278", false), + PAYPAL ("paypal", "858052657163272212", false), + PENCIL ("pencil", "855442436515037225", false), + PLUS ("plus", "592043203629416459", false), + PURR ("purr", "858052891704295434", false), + RICH_RPESENCE ("rich_presence", "855418148949196830", false), + SEX ("sex", "858052656706355211", false), + SEX_ANAL ("sex_anal", "858052657277304842", false), + SEX_YAOI ("sex_yaoi", "858052657301159946", false), + SEX_YURI ("sex_yuri", "858052657239162900", false), + SLOWMODE ("slowmode", "855418148760977419", false), + SMILEY ("smiley", "855436906254434324", false), + SNUGGLE ("snuggle", "858052852639334430", false), + STAFF ("staff", "857290795090575391", false), + STATUS_DISCONNECT ("statusDisconnect", "592043203440410624", false), + STATUS_READY ("statusReady", "592043203646193692", false), + STORE ("store", "855418148895064075", false), + TEXT ("text", "855436906259021844", false), + VERIFIED_BOT_TAG_1 ("verifiedBotTag_1", "855439119006040067", false), + VERIFIED_BOT_TAG_2 ("verifiedBotTag_2", "855439119009447977", false), + VERIFIED ("verified", "855418151587807232", false), + VOICE ("voice", "855418149054578688", false); + + public static final Emotes[] VALUES = values(); + + private final String name; + private final String id; + private final boolean animated; + + Emotes(String name, String id, boolean animated){ + this.name = name; + this.id = id; + this.animated = animated; + } + + public static String parseEmotes(String message){ + for(Emotes emote : VALUES) + message = StringReplacer.replace(message, "{" + emote.name() + "}", emote.getAsMention()); + + return message; + } + + public String getAsMention(){ + return String.format("<%s:%s:%s>", animated ? "a" : "", name, id); + } +} diff --git a/src/main/java/site/purrbot/bot/manager/DBManager.java b/src/main/java/site/purrbot/bot/manager/DBManager.java new file mode 100644 index 000000000..ab70025cb --- /dev/null +++ b/src/main/java/site/purrbot/bot/manager/DBManager.java @@ -0,0 +1,104 @@ +/* + * Copyright 2018 - 2022 Andre601 + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated + * documentation files (the "Software"), to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial + * portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +package site.purrbot.bot.manager; + +import com.rethinkdb.RethinkDB; +import com.rethinkdb.gen.ast.Table; +import com.rethinkdb.net.Connection; +import com.rethinkdb.utils.Types; +import site.purrbot.bot.PurrBot; +import site.purrbot.bot.manager.guild.GuildSettingsManager; + +import java.util.Map; +import java.util.Objects; + +public class DBManager{ + + private final RethinkDB r; + private final Connection connection; + + private final String guildTable; + + public DBManager(){ + r = RethinkDB.r; + connection = r.connection() + .hostname(PurrBot.getBot().getFileManager().getString("config", "localhost", "database", "ip")) + .port(28015) + .db(PurrBot.getBot().getFileManager().getString("config", "main", "database", "name")) + .connect(); + guildTable = PurrBot.getBot().getFileManager().getString("config", "guilds", "database", "guildTable"); + } + + public void addGuild(String id){ + getTable().insert( + r.array(defaultMap(id)) + ).optArg("conflict", "update").run(connection); + } + + public void deleteGuild(String id){ + if(findGuild(id) == null) + return; + + getTable().get(id).delete().run(connection); + } + + public void updateSettings(String id, String key, String value){ + if(findGuild(id) == null) + addGuild(id); + + getTable().get(id) + .update(r.hashMap(key, value)) + .run(connection); + } + + public void resetSettings(String id){ + if(findGuild(id) == null){ + addGuild(id); + return; + } + + getTable().get(id) + .update(defaultMap(id)) + .run(connection); + } + + public Map findGuild(String id){ + return getTable() + .get(id) + .run(connection, Types.mapOf(String.class, String.class)) + .stream() + .filter(Objects::nonNull) + .findFirst() + .orElse(null); + } + + private Table getTable(){ + return r.table(guildTable); + } + + private Map defaultMap(String id){ + return r.hashMap("id", id) + .with(GuildSettingsManager.KEY_LANGUAGE, GuildSettingsManager.DEF_LANGUAGE) + .with(GuildSettingsManager.KEY_WELCOME_BACKGROUND, GuildSettingsManager.DEF_WELCOME_BACKGROUND) + .with(GuildSettingsManager.KEY_WELCOME_CHANNEL, GuildSettingsManager.DEF_WELCOME_CHANNEL) + .with(GuildSettingsManager.KEY_WELCOME_COLOR, GuildSettingsManager.DEF_WELCOME_COLOR) + .with(GuildSettingsManager.KEY_WELCOME_ICON, GuildSettingsManager.DEF_WELCOME_ICON) + .with(GuildSettingsManager.KEY_WELCOME_MESSAGE, GuildSettingsManager.DEF_WELCOME_MESSAGE); + } +} diff --git a/src/main/java/site/purrbot/bot/manager/EmbedManager.java b/src/main/java/site/purrbot/bot/manager/EmbedManager.java new file mode 100644 index 000000000..c99bf63bc --- /dev/null +++ b/src/main/java/site/purrbot/bot/manager/EmbedManager.java @@ -0,0 +1,50 @@ +/* + * Copyright 2018 - 2022 Andre601 + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated + * documentation files (the "Software"), to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial + * portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +package site.purrbot.bot.manager; + +import net.dv8tion.jda.api.EmbedBuilder; +import site.purrbot.bot.manager.string.MessageHandler; + +import java.time.Instant; + +public class EmbedManager{ + + private final MessageHandler messageHandler; + + private EmbedManager(String guildId, String[] path){ + this.messageHandler = MessageHandler.getTranslation(guildId, path); + } + + public static EmbedManager get(String guildId, String... path){ + return new EmbedManager(guildId, path); + } + + public static EmbedBuilder getDefaultEmbed(){ + return new EmbedBuilder().setTimestamp(Instant.now()).setColor(0x802F3136); + } + + public EmbedManager replace(String target, Object replacement){ + messageHandler.replace(target, replacement); + return this; + } + + public EmbedBuilder getEmbed(){ + return getDefaultEmbed().setDescription(messageHandler.getMessage()); + } +} diff --git a/src/main/java/site/purrbot/bot/manager/api/ImageAPI.java b/src/main/java/site/purrbot/bot/manager/api/ImageAPI.java new file mode 100644 index 000000000..b96a0ec4e --- /dev/null +++ b/src/main/java/site/purrbot/bot/manager/api/ImageAPI.java @@ -0,0 +1,99 @@ +/* + * Copyright 2018 - 2022 Andre601 + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated + * documentation files (the "Software"), to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial + * portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +package site.purrbot.bot.manager.api; + +import com.google.gson.Gson; +import net.dv8tion.jda.api.EmbedBuilder; +import net.dv8tion.jda.api.entities.Member; +import net.dv8tion.jda.api.interactions.InteractionHook; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; +import site.purrbot.bot.command.ImageAPICommand; +import site.purrbot.bot.manager.EmbedManager; +import site.purrbot.bot.manager.api.response.GenericAPIResponse; +import site.purrbot.bot.manager.api.response.ImageAPIErrorResponse; +import site.purrbot.bot.manager.api.response.ImageAPISuccessResponse; +import site.purrbot.bot.manager.command.CommandError; + +import java.io.IOException; +import java.util.concurrent.CompletableFuture; + +public class ImageAPI{ + + private static final OkHttpClient CLIENT = new OkHttpClient(); + private static final Gson GSON = new Gson(); + + public static void returnImage(InteractionHook hook, String guildId, ImageAPICommand command, Member member, String targets){ + getImage(command).whenComplete((response, throwable) -> { + if(throwable != null){ + CommandError.fromPath(guildId, "errors", "image_api", "unknown_error") + .replace("{error}", throwable.getMessage()) + .send(hook); + return; + } + + if((response instanceof ImageAPIErrorResponse) && command.isRequired()){ + CommandError.fromPath(guildId, "errors", "image_api", "not_successful") + .replace("{error}", ((ImageAPIErrorResponse)response).getMessage()) + .send(hook); + return; + } + + EmbedManager manager = EmbedManager.get(guildId, command.getMessagePath()); + if(member != null) + manager.replace("{user}", member.getEffectiveName()); + + if(targets != null && !targets.isEmpty()) + manager.replace("{targets}", targets); + + EmbedBuilder embed = manager.getEmbed(); + + if(response instanceof ImageAPISuccessResponse) + embed.setImage(((ImageAPISuccessResponse)response).getLink()); + + hook.editOriginalEmbeds(embed.build()).queue(); + }); + } + + private static CompletableFuture getImage(ImageAPICommand command){ + return CompletableFuture.supplyAsync(() -> { + Request request = new Request.Builder() + .url(command.getUrl()) + .build(); + + try(Response response = CLIENT.newCall(request).execute()){ + if(response.body() == null) + return new ImageAPIErrorResponse("Received empty response body for request."); + + String body = response.body().string(); + if(body.isEmpty()) + return new ImageAPIErrorResponse("Received empty response body for request."); + + if(!response.isSuccessful()){ + return GSON.fromJson(body, ImageAPIErrorResponse.class); + } + + return GSON.fromJson(body, ImageAPISuccessResponse.class); + }catch(IOException ex){ + return new ImageAPIErrorResponse("Encountered IOException during request. Reason: " + ex.getMessage()); + } + }); + } +} diff --git a/src/main/java/site/purrbot/bot/manager/api/response/GenericAPIResponse.java b/src/main/java/site/purrbot/bot/manager/api/response/GenericAPIResponse.java new file mode 100644 index 000000000..d2091b17d --- /dev/null +++ b/src/main/java/site/purrbot/bot/manager/api/response/GenericAPIResponse.java @@ -0,0 +1,26 @@ +/* + * Copyright 2018 - 2022 Andre601 + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated + * documentation files (the "Software"), to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial + * portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +package site.purrbot.bot.manager.api.response; + +public interface GenericAPIResponse{ + + boolean isError(); + + long getTime(); +} diff --git a/src/main/java/site/purrbot/bot/manager/api/response/ImageAPIErrorResponse.java b/src/main/java/site/purrbot/bot/manager/api/response/ImageAPIErrorResponse.java new file mode 100644 index 000000000..61a6b9f7b --- /dev/null +++ b/src/main/java/site/purrbot/bot/manager/api/response/ImageAPIErrorResponse.java @@ -0,0 +1,48 @@ +/* + * Copyright 2018 - 2022 Andre601 + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated + * documentation files (the "Software"), to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial + * portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +package site.purrbot.bot.manager.api.response; + +public class ImageAPIErrorResponse implements GenericAPIResponse{ + + private boolean error; + private String message; + private long time; + + public ImageAPIErrorResponse(){} + + public ImageAPIErrorResponse(String message){ + this.error = true; + this.message = message; + this.time = -1L; + } + + @Override + public boolean isError(){ + return error; + } + + @Override + public long getTime(){ + return time; + } + + public String getMessage(){ + return message; + } +} diff --git a/src/main/java/site/purrbot/bot/manager/api/response/ImageAPISuccessResponse.java b/src/main/java/site/purrbot/bot/manager/api/response/ImageAPISuccessResponse.java new file mode 100644 index 000000000..cabcf387a --- /dev/null +++ b/src/main/java/site/purrbot/bot/manager/api/response/ImageAPISuccessResponse.java @@ -0,0 +1,42 @@ +/* + * Copyright 2018 - 2022 Andre601 + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated + * documentation files (the "Software"), to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial + * portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +package site.purrbot.bot.manager.api.response; + +public class ImageAPISuccessResponse implements GenericAPIResponse{ + + private boolean error; + private String link; + private long time; + + public ImageAPISuccessResponse(){} + + @Override + public boolean isError(){ + return error; + } + + @Override + public long getTime(){ + return time; + } + + public String getLink(){ + return link; + } +} diff --git a/src/main/java/site/purrbot/bot/manager/command/CommandError.java b/src/main/java/site/purrbot/bot/manager/command/CommandError.java new file mode 100644 index 000000000..e0e5b76ae --- /dev/null +++ b/src/main/java/site/purrbot/bot/manager/command/CommandError.java @@ -0,0 +1,68 @@ +/* + * Copyright 2018 - 2022 Andre601 + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated + * documentation files (the "Software"), to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial + * portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +package site.purrbot.bot.manager.command; + +import com.jagrosh.jdautilities.command.SlashCommandEvent; +import net.dv8tion.jda.api.EmbedBuilder; +import net.dv8tion.jda.api.entities.MessageEmbed; +import net.dv8tion.jda.api.interactions.InteractionHook; +import site.purrbot.bot.manager.string.MessageHandler; +import site.purrbot.bot.manager.string.StringReplacer; + +import java.time.Instant; + +public class CommandError{ + + private String message; + + private CommandError(String guildId, String... path){ + this.message = guildId == null ? String.valueOf(path[0]) : MessageHandler.getTranslation(guildId, path).getMessage(); + } + + public static CommandError fromStatic(String message){ + return new CommandError(null, message); + } + + public static CommandError fromPath(String guildId, String... path){ + return new CommandError(guildId, path); + } + + public CommandError replace(String input, Object output){ + if(input == null || input.isEmpty() || output == null) + return this; + + this.message = StringReplacer.replace(message, input, output); + return this; + } + + public void send(SlashCommandEvent event){ + event.replyEmbeds(errorEmbed(message)).queue(); + } + + public void send(InteractionHook hook){ + hook.editOriginalEmbeds(errorEmbed(message)).queue(); + } + + private MessageEmbed errorEmbed(String message){ + return new EmbedBuilder().setColor(0xFF0000) + .setDescription(message) + .setTimestamp(Instant.now()) + .build(); + } +} diff --git a/src/main/java/site/purrbot/bot/manager/command/CommandLoader.java b/src/main/java/site/purrbot/bot/manager/command/CommandLoader.java new file mode 100644 index 000000000..3fe2997bc --- /dev/null +++ b/src/main/java/site/purrbot/bot/manager/command/CommandLoader.java @@ -0,0 +1,46 @@ +/* + * Copyright 2018 - 2022 Andre601 + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated + * documentation files (the "Software"), to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial + * portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +package site.purrbot.bot.manager.command; + +import ch.qos.logback.classic.Logger; +import org.slf4j.LoggerFactory; +import site.purrbot.bot.command.BotCommand; +import site.purrbot.bot.command.fun.CmdBite; + +public class CommandLoader{ + + private final BotCommand[] commands; + + public CommandLoader(){ + this.commands = load(); + + Logger logger = (Logger)LoggerFactory.getLogger(CommandLoader.class); + logger.info("Loaded {} commands for the bot.", commands.length); + } + + public BotCommand[] getCommands(){ + return commands; + } + + private BotCommand[] load(){ + return new BotCommand[]{ + new CmdBite() + }; + } +} diff --git a/src/main/java/site/purrbot/bot/manager/command/CommandUtil.java b/src/main/java/site/purrbot/bot/manager/command/CommandUtil.java new file mode 100644 index 000000000..5b47775de --- /dev/null +++ b/src/main/java/site/purrbot/bot/manager/command/CommandUtil.java @@ -0,0 +1,86 @@ +/* + * Copyright 2018 - 2022 Andre601 + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated + * documentation files (the "Software"), to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial + * portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +package site.purrbot.bot.manager.command; + +import com.jagrosh.jdautilities.command.SlashCommandEvent; +import net.dv8tion.jda.api.entities.User; +import site.purrbot.bot.manager.string.MessageHandler; + +import java.util.ArrayList; +import java.util.List; + +public class CommandUtil{ + + public static List getUsers(SlashCommandEvent event, String... keys){ + List users = new ArrayList<>(); + for(String key : keys){ + User user = event.optUser(key); + if(user == null) + continue; + + users.add(user); + } + + return users; + } + + public static String convertUsersToString(String guildId, List users, User commandExecutor){ + List names = new ArrayList<>(); + for(User user : users){ + if(equalsAny(user.getId(), commandExecutor.getId(), "TODO: Purr ID", "TODO: Snuggle ID")) + continue; + + names.add(user.getName()); + } + + if(names.isEmpty()) + return null; + + if(names.size() == 1) + return "**" + escapeAll(names.get(0)) + "**"; + + StringBuilder builder = new StringBuilder(String.join(", ", names)); + + int index = builder.lastIndexOf(","); + if(index == -1) + return builder.toString(); + + String and = MessageHandler.getTranslation(guildId, "misc", "and").getMessage(); + builder.replace(index, index + 1, " " + and); + + return builder.toString(); + } + + private static boolean equalsAny(String input, String... values){ + for(String value : values){ + if(value.equals(input)) + return true; + } + + return false; + } + + private static String escapeAll(String text){ + return text.replace("*", "\\*") + .replace("_", "\\_") + .replace("`", "\\`") + .replace("|", "\\|") + .replace("~", "\\~"); + } +} diff --git a/src/main/java/site/purrbot/bot/manager/file/FileManager.java b/src/main/java/site/purrbot/bot/manager/file/FileManager.java new file mode 100644 index 000000000..f12932669 --- /dev/null +++ b/src/main/java/site/purrbot/bot/manager/file/FileManager.java @@ -0,0 +1,158 @@ +/* + * Copyright 2018 - 2022 Andre601 + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated + * documentation files (the "Software"), to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial + * portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +package site.purrbot.bot.manager.file; + +import ch.qos.logback.classic.Logger; +import org.slf4j.LoggerFactory; +import org.spongepowered.configurate.ConfigurationNode; +import org.spongepowered.configurate.gson.GsonConfigurationLoader; +import org.spongepowered.configurate.serialize.SerializationException; +import site.purrbot.bot.PurrBot; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.StandardCopyOption; +import java.util.*; + +public class FileManager{ + + private final Logger logger = (Logger)LoggerFactory.getLogger(FileManager.class); + + private final Map files = new HashMap<>(); + private final List languages = new ArrayList<>(); + + public FileManager(){} + + public FileManager addLanguage(String language){ + String filePath = "/lang/" + language + ".json"; + if(!createOrLoad(language.toLowerCase(Locale.ROOT), filePath, "." + filePath)){ + logger.warn("Cannot create lang file {}. Skipping...", language); + return this; + } + + languages.add(language.toLowerCase(Locale.ROOT)); + return this; + } + + public List getLanguages(){ + return languages; + } + + public FileManager addFile(String name){ + String filePath = "/" + name + ".json"; + createOrLoad(name, filePath, "." + filePath); + return this; + } + + public String getString(String name, String def, String... path){ + ConfigurationNode node = files.get(name); + if(node == null) + return def; + + Object[] objPath = convertStringPath(path); + + return node.node(objPath).getString(def); + } + + public List getStringList(String name, String... path){ + ConfigurationNode node = files.get(name); + if(node == null) + return Collections.emptyList(); + + try{ + Object[] objPath = convertStringPath(path); + return node.node(objPath).getList(String.class); + }catch(SerializationException ex){ + return Collections.emptyList(); + } + } + + public boolean getBoolean(String name, boolean def, String... path){ + ConfigurationNode node = files.get(name); + if(node == null) + return def; + + Object[] objPath = convertStringPath(path); + return node.node(objPath).getBoolean(def); + } + + public int isList(String name, String... path){ + ConfigurationNode node = files.get(name); + if(node == null) + return -1; + + Object[] objPath = convertStringPath(path); + return node.node(objPath).isList() ? 1 : 0; + } + + private boolean createOrLoad(String name, String internalPath, String externalPath){ + File file = new File(externalPath); + + if(!file.getParentFile().exists() && !file.getParentFile().mkdirs()){ + logger.warn("Unable to create folder for file {}", name); + return false; + } + + if(!file.exists()){ + try(InputStream stream = PurrBot.class.getResourceAsStream(internalPath)){ + if(stream == null){ + logger.warn("Cannot create file {}! InputStream was null.", name); + return false; + } + + Files.copy(stream, file.toPath(), StandardCopyOption.REPLACE_EXISTING); + logger.info("Created {}.json", name); + }catch(IOException ex){ + logger.warn("Cannot create file {}! Encountered IOException.", name, ex); + return false; + } + } + + ConfigurationNode node = createNode(file); + if(node == null) + return false; + + files.put(name, node); + return true; + } + + private ConfigurationNode createNode(File file){ + GsonConfigurationLoader loader = GsonConfigurationLoader.builder() + .file(file) + .build(); + + try{ + return loader.load(); + }catch(IOException ex){ + logger.warn("Unable to create ConfigurationNode instance for file {}", file.getName(), ex); + return null; + } + } + + private Object[] convertStringPath(String[] path){ + Object[] newPath = new Object[path.length]; + System.arraycopy(path, 0, newPath, 0, newPath.length); + + return newPath; + } + + +} diff --git a/src/main/java/site/purrbot/bot/manager/guild/GuildSettingsManager.java b/src/main/java/site/purrbot/bot/manager/guild/GuildSettingsManager.java new file mode 100644 index 000000000..87092c05c --- /dev/null +++ b/src/main/java/site/purrbot/bot/manager/guild/GuildSettingsManager.java @@ -0,0 +1,184 @@ +/* + * Copyright 2018 - 2022 Andre601 + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated + * documentation files (the "Software"), to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial + * portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +package site.purrbot.bot.manager.guild; + +import com.github.benmanes.caffeine.cache.Cache; +import com.github.benmanes.caffeine.cache.Caffeine; +import site.purrbot.bot.PurrBot; + +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.TimeUnit; +import java.util.function.BiConsumer; + +public class GuildSettingsManager{ + + public static final String KEY_LANGUAGE = "language", + KEY_WELCOME_BACKGROUND = "welcome_background", + KEY_WELCOME_CHANNEL = "welcome_channel", + KEY_WELCOME_COLOR = "welcome_color", + KEY_WELCOME_ICON = "welcome_icon", + KEY_WELCOME_MESSAGE = "welcome_message"; + + public static final String DEF_LANGUAGE = "en", + DEF_WELCOME_BACKGROUND = "color_white", + DEF_WELCOME_CHANNEL = null, + DEF_WELCOME_COLOR = "hex:000000", + DEF_WELCOME_ICON = "purr", + DEF_WELCOME_MESSAGE = "Welcome {mention]!"; + + private final Cache guildSettingsCache = Caffeine.newBuilder() + .expireAfterWrite(10, TimeUnit.MINUTES) + .build(); + + public GuildSettingsManager(){} + + public String getLanguage(String id){ + return getSettings(id).getLanguage(); + } + + public String getWelcomeBackground(String id){ + return getSettings(id).getWelcomeBackground(); + } + + public String getWelcomeChannel(String id){ + return getSettings(id).getWelcomeChannel(); + } + + public String getWelcomeColor(String id){ + return getSettings(id).getWelcomeColor(); + } + + public String getWelcomeIcon(String id){ + return getSettings(id).getWelcomeIcon(); + } + + public String getWelcomeMessage(String id){ + return getSettings(id).getWelcomeMessage(); + } + + public void updateSettings(String id, String key, String value, BiConsumer consumer){ + GuildSettings settings = getSettings(id); + + consumer.accept(settings, value); + + guildSettingsCache.put(id, settings); + } + + public void resetSettings(String id){ + guildSettingsCache.put(id, GuildSettings.createDefault()); + } + + private GuildSettings getSettings(String id){ + return guildSettingsCache.get(id, k -> { + Map guild = PurrBot.getBot().getDbManager().findGuild(id); + if(guild == null){ + PurrBot.getBot().getDbManager().addGuild(id); + + return GuildSettings.createDefault(); + } + + return new GuildSettings() + .setLanguage(guild.getOrDefault(KEY_LANGUAGE, DEF_LANGUAGE)) + .setBackground(guild.getOrDefault(KEY_WELCOME_BACKGROUND, DEF_WELCOME_BACKGROUND)) + .setChannel(guild.getOrDefault(KEY_WELCOME_CHANNEL, DEF_WELCOME_CHANNEL)) + .setColor(guild.getOrDefault(KEY_WELCOME_COLOR, DEF_WELCOME_COLOR)) + .setIcon(guild.getOrDefault(KEY_WELCOME_ICON, DEF_WELCOME_ICON)) + .setMessage(guild.getOrDefault(KEY_WELCOME_MESSAGE, DEF_WELCOME_MESSAGE)); + }); + } + + public static class GuildSettings{ + + private String language; + + private String welcomeBackground; + private String welcomeChannel; + private String welcomeColor; + private String welcomeIcon; + private String welcomeMessage; + + public GuildSettings(){ + this.language = "en"; + this.welcomeBackground = "color_white"; + this.welcomeChannel = "none"; + this.welcomeColor = "hex:000000"; + this.welcomeIcon = "purr"; + this.welcomeMessage = "Welcome {mention}!"; + } + + public static GuildSettings createDefault(){ + return new GuildSettings(); + } + + public GuildSettings setLanguage(String language){ + this.language = language; + return this; + } + + public GuildSettings setBackground(String welcomeBackground){ + this.welcomeBackground = welcomeBackground; + return this; + } + + public GuildSettings setChannel(String welcomeChannel){ + this.welcomeChannel = welcomeChannel; + return this; + } + + public GuildSettings setColor(String welcomeColor){ + this.welcomeColor = welcomeColor; + return this; + } + + public GuildSettings setIcon(String welcomeIcon){ + this.welcomeIcon = welcomeIcon; + return this; + } + + public GuildSettings setMessage(String welcomeMessage){ + this.welcomeMessage = welcomeMessage; + return this; + } + + public String getLanguage(){ + return language; + } + + public String getWelcomeBackground(){ + return welcomeBackground; + } + + public String getWelcomeChannel(){ + return welcomeChannel; + } + + public String getWelcomeColor(){ + return welcomeColor; + } + + public String getWelcomeIcon(){ + return welcomeIcon; + } + + public String getWelcomeMessage(){ + return welcomeMessage; + } + } +} diff --git a/src/main/java/site/purrbot/bot/manager/string/MessageHandler.java b/src/main/java/site/purrbot/bot/manager/string/MessageHandler.java new file mode 100644 index 000000000..c80b6c04a --- /dev/null +++ b/src/main/java/site/purrbot/bot/manager/string/MessageHandler.java @@ -0,0 +1,83 @@ +/* + * Copyright 2018 - 2022 Andre601 + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated + * documentation files (the "Software"), to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial + * portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +package site.purrbot.bot.manager.string; + +import org.jetbrains.annotations.NotNull; +import site.purrbot.bot.PurrBot; +import site.purrbot.bot.constants.Emotes; +import site.purrbot.bot.manager.file.FileManager; + +import java.util.*; + +public class MessageHandler{ + + private String message; + + public MessageHandler(String message){ + this.message = message; + } + + @NotNull + public static MessageHandler getTranslation(String guildId, String... path){ + String language = PurrBot.getBot().getGuildSettingsManager().getLanguage(guildId); + FileManager fileManager = PurrBot.getBot().getFileManager(); + String textPath = String.join(".", path); + + String msg = null; + for(String lang : fileManager.getLanguages()){ + if(lang.equalsIgnoreCase(language)){ + int isListResult = fileManager.isList(language, path); + if(isListResult == -1){ + msg = "ERROR: Invalid path `" + textPath + "` for guild id `" + guildId + "`! String was empty/null."; + break; + }else + if(isListResult == 1){ + List lines = fileManager.getStringList(language, path); + if(lines.isEmpty()){ + msg = "ERROR: Invalid path `" + textPath + "` for guild id `" + guildId + "`! List was empty."; + }else{ + msg = lines.get(PurrBot.getBot().getRandom().nextInt(lines.size())); + } + break; + }else{ + msg = fileManager.getString( + language, + "ERROR: Could not get message from path `" + textPath + "`!", + path + ); + break; + } + } + } + + if(msg == null || msg.isEmpty()) + msg = "ERROR: Invalid path `" + textPath + "` for guild id `" + guildId + "`! String was empty/null."; + + return new MessageHandler(msg); + } + + public MessageHandler replace(String target, Object replacement){ + this.message = StringReplacer.replace(message, target, replacement); + return this; + } + + public String getMessage(){ + return Emotes.parseEmotes(message); + } +} diff --git a/src/main/java/site/purrbot/bot/manager/string/StringReplacer.java b/src/main/java/site/purrbot/bot/manager/string/StringReplacer.java new file mode 100644 index 000000000..4b760364a --- /dev/null +++ b/src/main/java/site/purrbot/bot/manager/string/StringReplacer.java @@ -0,0 +1,49 @@ +/* + * Copyright 2018 - 2022 Andre601 + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated + * documentation files (the "Software"), to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial + * portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +package site.purrbot.bot.manager.string; + +import java.util.Map; + +public class StringReplacer{ + + public static String replace(String input, String target, Object replacement){ + StringBuilder output = new StringBuilder(input); + int index = 0; + while((index = output.indexOf(target, index)) != -1){ + output.replace(index, index + target.length(), String.valueOf(replacement)); + index += String.valueOf(output).length(); + } + + return output.toString(); + } + + public static String replace(String input, Map replacements){ + StringBuilder output = new StringBuilder(input); + int index; + for(Map.Entry entry : replacements.entrySet()){ + index = 0; + while((index = output.indexOf(entry.getKey(), index)) != -1){ + output.replace(index, index + entry.getKey().length(), String.valueOf(entry.getValue())); + index += String.valueOf(entry.getValue()).length(); + } + } + + return output.toString(); + } +} From d1886f4fbbaaf8c3d7a6a5fc6ce5b4fdb3ed7db2 Mon Sep 17 00:00:00 2001 From: Taz03 Date: Mon, 10 Oct 2022 20:00:17 +0530 Subject: [PATCH 3/6] used implentation --- build.gradle | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/build.gradle b/build.gradle index 89bc615db..afc9a980b 100644 --- a/build.gradle +++ b/build.gradle @@ -43,19 +43,19 @@ repositories { } dependencies { - compile group: 'ch.qos.logback', name: 'logback-classic', version: '1.2.11' - compile group: 'pw.chew', name: 'jda-chewtils-commons', version: '2.0-SNAPSHOT' - compile group: 'pw.chew', name: 'jda-chewtils-menu', version: '2.0-SNAPSHOT' - compile group: 'pw.chew', name: 'jda-chewtils-command', version: '2.0-SNAPSHOT' - compile group: 'com.rethinkdb', name: 'rethinkdb-driver', version:'2.4.4' - compile(group: 'net.dv8tion', name: 'JDA', version:'5.0.0-alpha.17'){ + implementation group: 'ch.qos.logback', name: 'logback-classic', version: '1.2.11' + implementation group: 'pw.chew', name: 'jda-chewtils-commons', version: '2.0-SNAPSHOT' + implementation group: 'pw.chew', name: 'jda-chewtils-menu', version: '2.0-SNAPSHOT' + implementation group: 'pw.chew', name: 'jda-chewtils-command', version: '2.0-SNAPSHOT' + implementation group: 'com.rethinkdb', name: 'rethinkdb-driver', version:'2.4.4' + implementation (group: 'net.dv8tion', name: 'JDA', version:'5.0.0-alpha.17'){ exclude(module: 'opus-java') } - compile group: 'club.minnced', name: 'discord-webhooks', version: '0.8.2' - compile group: 'com.github.ben-manes.caffeine', name: 'caffeine', version: '3.1.1' - compile group: 'com.squareup.okhttp3', name: 'okhttp', version: '4.10.0' - compile group: 'com.google.code.gson', name: 'gson', version: '2.8.7' - compile group: 'org.spongepowered', name: 'configurate-gson', version: '4.1.2' + implementation group: 'club.minnced', name: 'discord-webhooks', version: '0.8.2' + implementation group: 'com.github.ben-manes.caffeine', name: 'caffeine', version: '3.1.1' + implementation group: 'com.squareup.okhttp3', name: 'okhttp', version: '4.10.0' + implementation group: 'com.google.code.gson', name: 'gson', version: '2.8.7' + implementation group: 'org.spongepowered', name: 'configurate-gson', version: '4.1.2' } compileJava { From f31b033cf064f1bacb31d9dab33f7971ec21edc0 Mon Sep 17 00:00:00 2001 From: Taz03 Date: Wed, 12 Oct 2022 14:30:53 +0530 Subject: [PATCH 4/6] upgraded jda --- .gitignore | 3 ++- build.gradle | 2 +- src/main/java/site/purrbot/bot/PurrBot.java | 6 ++---- src/main/java/site/purrbot/bot/command/BotCommand.java | 6 +++--- src/main/java/site/purrbot/bot/command/fun/CmdBite.java | 2 +- src/main/java/site/purrbot/bot/constants/Emotes.java | 3 --- 6 files changed, 9 insertions(+), 13 deletions(-) diff --git a/.gitignore b/.gitignore index ead6044d4..3cade8d73 100644 --- a/.gitignore +++ b/.gitignore @@ -73,4 +73,5 @@ buildNumber.properties !/.mvn/wrapper/maven-wrapper.jar .gradle/ -build/ \ No newline at end of file +build/ +logs/ \ No newline at end of file diff --git a/build.gradle b/build.gradle index afc9a980b..ba7114262 100644 --- a/build.gradle +++ b/build.gradle @@ -48,7 +48,7 @@ dependencies { implementation group: 'pw.chew', name: 'jda-chewtils-menu', version: '2.0-SNAPSHOT' implementation group: 'pw.chew', name: 'jda-chewtils-command', version: '2.0-SNAPSHOT' implementation group: 'com.rethinkdb', name: 'rethinkdb-driver', version:'2.4.4' - implementation (group: 'net.dv8tion', name: 'JDA', version:'5.0.0-alpha.17'){ + implementation (group: 'net.dv8tion', name: 'JDA', version:'5.0.0-alpha.21'){ exclude(module: 'opus-java') } implementation group: 'club.minnced', name: 'discord-webhooks', version: '0.8.2' diff --git a/src/main/java/site/purrbot/bot/PurrBot.java b/src/main/java/site/purrbot/bot/PurrBot.java index 68a204ed8..d2b0c3f97 100644 --- a/src/main/java/site/purrbot/bot/PurrBot.java +++ b/src/main/java/site/purrbot/bot/PurrBot.java @@ -25,12 +25,12 @@ import net.dv8tion.jda.api.entities.Activity; import net.dv8tion.jda.api.entities.Message; import net.dv8tion.jda.api.requests.GatewayIntent; -import net.dv8tion.jda.api.requests.restaction.MessageAction; import net.dv8tion.jda.api.sharding.DefaultShardManagerBuilder; import net.dv8tion.jda.api.sharding.ShardManager; import net.dv8tion.jda.api.utils.ChunkingFilter; import net.dv8tion.jda.api.utils.MemberCachePolicy; import net.dv8tion.jda.api.utils.cache.CacheFlag; +import net.dv8tion.jda.api.utils.messages.MessageRequest; import org.slf4j.LoggerFactory; import site.purrbot.bot.manager.DBManager; import site.purrbot.bot.manager.command.CommandLoader; @@ -106,8 +106,6 @@ public Random getRandom(){ return random; } - - private void startBot() throws LoginException{ fileManager = new FileManager(); dbManager = new DBManager(); @@ -117,7 +115,7 @@ private void startBot() throws LoginException{ fileManager.addFile("config") .addFile("random"); - MessageAction.setDefaultMentions(EnumSet.of( + MessageRequest.setDefaultMentions(EnumSet.of( Message.MentionType.USER, Message.MentionType.ROLE )); diff --git a/src/main/java/site/purrbot/bot/command/BotCommand.java b/src/main/java/site/purrbot/bot/command/BotCommand.java index bc5ef916a..f3d0ec8fe 100644 --- a/src/main/java/site/purrbot/bot/command/BotCommand.java +++ b/src/main/java/site/purrbot/bot/command/BotCommand.java @@ -22,7 +22,7 @@ import com.jagrosh.jdautilities.command.SlashCommandEvent; import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.Member; -import net.dv8tion.jda.api.entities.TextChannel; +import net.dv8tion.jda.api.entities.channel.concrete.TextChannel; import net.dv8tion.jda.api.interactions.InteractionHook; import site.purrbot.bot.PurrBot; import site.purrbot.bot.manager.command.CommandError; @@ -59,9 +59,9 @@ protected void execute(SlashCommandEvent event){ .send(event); return; } - + TextChannel tc = event.getTextChannel(); - + if(command.nsfwOnly && !tc.isNSFW()){ CommandError.fromPath(guild.getId(), "errors", "no_nsfw") .replace("{user}", member.getEffectiveName()) diff --git a/src/main/java/site/purrbot/bot/command/fun/CmdBite.java b/src/main/java/site/purrbot/bot/command/fun/CmdBite.java index 9eafae5be..aac113016 100644 --- a/src/main/java/site/purrbot/bot/command/fun/CmdBite.java +++ b/src/main/java/site/purrbot/bot/command/fun/CmdBite.java @@ -21,7 +21,7 @@ import com.jagrosh.jdautilities.command.SlashCommandEvent; import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.Member; -import net.dv8tion.jda.api.entities.TextChannel; +import net.dv8tion.jda.api.entities.channel.concrete.TextChannel; import net.dv8tion.jda.api.entities.User; import net.dv8tion.jda.api.interactions.InteractionHook; import net.dv8tion.jda.api.interactions.commands.OptionType; diff --git a/src/main/java/site/purrbot/bot/constants/Emotes.java b/src/main/java/site/purrbot/bot/constants/Emotes.java index 20c644f7f..180784174 100644 --- a/src/main/java/site/purrbot/bot/constants/Emotes.java +++ b/src/main/java/site/purrbot/bot/constants/Emotes.java @@ -20,9 +20,6 @@ import site.purrbot.bot.manager.string.StringReplacer; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - public enum Emotes{ // Animated emotes, LOADING ("loading", "858052734859345930", true), From 99f64687da53e325fd16f2ad4784cb90f2fce037 Mon Sep 17 00:00:00 2001 From: Andre601 Date: Sun, 2 Apr 2023 16:39:21 +0200 Subject: [PATCH 5/6] More work on the rewrite --- build.gradle | 22 +- src/main/java/site/purrbot/bot/PurrBot.java | 26 +-- .../site/purrbot/bot/command/BotCommand.java | 9 +- .../site/purrbot/bot/command/fun/CmdBite.java | 13 +- .../purrbot/bot/command/fun/CmdBlush.java | 46 ++++ .../site/purrbot/bot/command/fun/CmdCry.java | 46 ++++ .../site/purrbot/bot/command/fun/CmdImg.java | 219 ++++++++++++++++++ .../site/purrbot/bot/manager/DBManager.java | 7 +- .../purrbot/bot/manager/EmbedManager.java | 6 + .../purrbot/bot/manager/api/ImageAPI.java | 19 +- .../bot/manager/command/CommandError.java | 11 +- .../purrbot/bot/manager/file/FileManager.java | 66 ++++-- .../manager/guild/GuildSettingsManager.java | 13 ++ .../bot/manager/string/MessageHandler.java | 55 ++--- .../bot/manager/string/StringReplacer.java | 3 + 15 files changed, 459 insertions(+), 102 deletions(-) create mode 100644 src/main/java/site/purrbot/bot/command/fun/CmdBlush.java create mode 100644 src/main/java/site/purrbot/bot/command/fun/CmdCry.java create mode 100644 src/main/java/site/purrbot/bot/command/fun/CmdImg.java diff --git a/build.gradle b/build.gradle index ba7114262..1a0c8cbaf 100644 --- a/build.gradle +++ b/build.gradle @@ -43,19 +43,19 @@ repositories { } dependencies { - implementation group: 'ch.qos.logback', name: 'logback-classic', version: '1.2.11' - implementation group: 'pw.chew', name: 'jda-chewtils-commons', version: '2.0-SNAPSHOT' - implementation group: 'pw.chew', name: 'jda-chewtils-menu', version: '2.0-SNAPSHOT' - implementation group: 'pw.chew', name: 'jda-chewtils-command', version: '2.0-SNAPSHOT' - implementation group: 'com.rethinkdb', name: 'rethinkdb-driver', version:'2.4.4' - implementation (group: 'net.dv8tion', name: 'JDA', version:'5.0.0-alpha.21'){ + compile group: 'ch.qos.logback', name: 'logback-classic', version: '1.2.11' + compile group: 'pw.chew', name: 'jda-chewtils-commons', version: '2.0-SNAPSHOT' + compile group: 'pw.chew', name: 'jda-chewtils-menu', version: '2.0-SNAPSHOT' + compile group: 'pw.chew', name: 'jda-chewtils-command', version: '2.0-SNAPSHOT' + compile group: 'com.rethinkdb', name: 'rethinkdb-driver', version:'2.4.4' + compile(group: 'net.dv8tion', name: 'JDA', version:'5.0.0-beta.6'){ exclude(module: 'opus-java') } - implementation group: 'club.minnced', name: 'discord-webhooks', version: '0.8.2' - implementation group: 'com.github.ben-manes.caffeine', name: 'caffeine', version: '3.1.1' - implementation group: 'com.squareup.okhttp3', name: 'okhttp', version: '4.10.0' - implementation group: 'com.google.code.gson', name: 'gson', version: '2.8.7' - implementation group: 'org.spongepowered', name: 'configurate-gson', version: '4.1.2' + compile group: 'club.minnced', name: 'discord-webhooks', version: '0.8.2' + compile group: 'com.github.ben-manes.caffeine', name: 'caffeine', version: '3.1.1' + compile group: 'com.squareup.okhttp3', name: 'okhttp', version: '4.10.0' + compile group: 'com.google.code.gson', name: 'gson', version: '2.8.9' + compile group: 'org.spongepowered', name: 'configurate-gson', version: '4.1.2' } compileJava { diff --git a/src/main/java/site/purrbot/bot/PurrBot.java b/src/main/java/site/purrbot/bot/PurrBot.java index d2b0c3f97..4e34ce452 100644 --- a/src/main/java/site/purrbot/bot/PurrBot.java +++ b/src/main/java/site/purrbot/bot/PurrBot.java @@ -25,6 +25,7 @@ import net.dv8tion.jda.api.entities.Activity; import net.dv8tion.jda.api.entities.Message; import net.dv8tion.jda.api.requests.GatewayIntent; +import net.dv8tion.jda.api.requests.restaction.MessageAction; import net.dv8tion.jda.api.sharding.DefaultShardManagerBuilder; import net.dv8tion.jda.api.sharding.ShardManager; import net.dv8tion.jda.api.utils.ChunkingFilter; @@ -47,7 +48,6 @@ public class PurrBot{ private static PurrBot bot; // Bot classes - FileManager fileManager; DBManager dbManager; GuildSettingsManager guildSettingsManager; CommandLoader commandLoader; @@ -78,18 +78,10 @@ public static PurrBot getBot(){ return bot; } - public FileManager getFileManager(){ - return fileManager; - } - public DBManager getDbManager(){ return dbManager; } - public GuildSettingsManager getGuildSettingsManager(){ - return guildSettingsManager; - } - public CommandLoader getCommandLoader(){ return commandLoader; } @@ -106,21 +98,25 @@ public Random getRandom(){ return random; } + + private void startBot() throws LoginException{ - fileManager = new FileManager(); dbManager = new DBManager(); - guildSettingsManager = new GuildSettingsManager(); commandLoader = new CommandLoader(); - fileManager.addFile("config") - .addFile("random"); - + FileManager.get() + .addFile("config") + .addFile("random") + .addFile("data") + .addLanguage("en") + .addLanguage("de_CH"); + MessageRequest.setDefaultMentions(EnumSet.of( Message.MentionType.USER, Message.MentionType.ROLE )); - shardManager = DefaultShardManagerBuilder.createDefault(fileManager.getString("config", "", "token")) + shardManager = DefaultShardManagerBuilder.createDefault(FileManager.get().getString("config", "token")) .disableIntents(GatewayIntent.GUILD_VOICE_STATES) .disableCache(CacheFlag.VOICE_STATE) .enableIntents( diff --git a/src/main/java/site/purrbot/bot/command/BotCommand.java b/src/main/java/site/purrbot/bot/command/BotCommand.java index f3d0ec8fe..73a29709d 100644 --- a/src/main/java/site/purrbot/bot/command/BotCommand.java +++ b/src/main/java/site/purrbot/bot/command/BotCommand.java @@ -27,12 +27,13 @@ import site.purrbot.bot.PurrBot; import site.purrbot.bot.manager.command.CommandError; import site.purrbot.bot.manager.string.MessageHandler; +import site.purrbot.bot.manager.string.StringReplacer; import java.util.Arrays; public abstract class BotCommand extends SlashCommand{ - protected String[] replyMsgPath = new String[]{"misc", "default_loading"}; + protected String[] loadingMsgPath = new String[]{"misc", "default_loading"}; @Override protected void execute(SlashCommandEvent event){ @@ -55,7 +56,7 @@ protected void execute(SlashCommandEvent event){ if(command == null){ CommandError.fromPath(guild.getId(), "errors", "no_command_found") - .replace("{command}", event.getName()) + .modify(text -> StringReplacer.replace(text, "{command}", event.getName())) .send(event); return; } @@ -64,12 +65,12 @@ protected void execute(SlashCommandEvent event){ if(command.nsfwOnly && !tc.isNSFW()){ CommandError.fromPath(guild.getId(), "errors", "no_nsfw") - .replace("{user}", member.getEffectiveName()) + .modify(text -> StringReplacer.replace(text, "{user}", member.getEffectiveName())) .send(event); return; } - event.reply(MessageHandler.getTranslation(guild.getId(), replyMsgPath).getMessage()).queue( + event.reply(MessageHandler.getTranslation(guild.getId(), loadingMsgPath).getMessage()).queue( hook -> handle(event, hook, guild, tc, member) ); } diff --git a/src/main/java/site/purrbot/bot/command/fun/CmdBite.java b/src/main/java/site/purrbot/bot/command/fun/CmdBite.java index aac113016..37d2d57c3 100644 --- a/src/main/java/site/purrbot/bot/command/fun/CmdBite.java +++ b/src/main/java/site/purrbot/bot/command/fun/CmdBite.java @@ -21,8 +21,9 @@ import com.jagrosh.jdautilities.command.SlashCommandEvent; import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.Member; -import net.dv8tion.jda.api.entities.channel.concrete.TextChannel; +import net.dv8tion.jda.api.entities.TextChannel; import net.dv8tion.jda.api.entities.User; +import net.dv8tion.jda.api.entities.channel.concrete.TextChannel; import net.dv8tion.jda.api.interactions.InteractionHook; import net.dv8tion.jda.api.interactions.commands.OptionType; import net.dv8tion.jda.api.interactions.commands.build.OptionData; @@ -31,6 +32,7 @@ import site.purrbot.bot.manager.command.CommandError; import site.purrbot.bot.manager.command.CommandUtil; import site.purrbot.bot.manager.string.MessageHandler; +import site.purrbot.bot.manager.string.StringReplacer; import java.util.Arrays; import java.util.List; @@ -40,9 +42,8 @@ public class CmdBite extends ImageAPICommand{ public CmdBite(){ this.name = "bite"; this.help = "Bite some people."; - this.guildOnly = true; - this.replyMsgPath = new String[]{"purr", "fun", "bite", "loading"}; + this.loadingMsgPath = new String[]{"purr", "fun", "bite", "loading"}; this.apiName = "bite"; this.apiMessagePath = new String[]{"purr", "fun", "bite", "message"}; @@ -51,7 +52,7 @@ public CmdBite(){ this.options = Arrays.asList( new OptionData(OptionType.USER, "user", "The first user to bite. Required.").setRequired(true), new OptionData(OptionType.USER, "user2", "The second user to bite."), - new OptionData(OptionType.USER, "user3", "The second user to bite.") + new OptionData(OptionType.USER, "user3", "The third user to bite.") ); } @@ -65,7 +66,7 @@ protected void handle(SlashCommandEvent event, InteractionHook hook, Guild guild if(users.contains(hook.getJDA().getSelfUser())){ String msg = MessageHandler.getTranslation(guild.getId(), "purr", "fun", "bite", "mention_purr") - .replace("{user}", member.getAsMention()) + .modify(text -> StringReplacer.replace(text, "{user}", member.getAsMention())) .getMessage(); tc.sendMessage(msg).queue(); @@ -73,7 +74,7 @@ protected void handle(SlashCommandEvent event, InteractionHook hook, Guild guild if(users.contains(member.getUser())){ String msg = MessageHandler.getTranslation(guild.getId(), "purr", "fun", "bite", "mention_self") - .replace("{user}", member.getAsMention()) + .modify(text -> StringReplacer.replace(text, "{user}", member.getAsMention())) .getMessage(); tc.sendMessage(msg).queue(); diff --git a/src/main/java/site/purrbot/bot/command/fun/CmdBlush.java b/src/main/java/site/purrbot/bot/command/fun/CmdBlush.java new file mode 100644 index 000000000..9e255dbec --- /dev/null +++ b/src/main/java/site/purrbot/bot/command/fun/CmdBlush.java @@ -0,0 +1,46 @@ +/* + * Copyright 2018 - 2023 Andre601 + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated + * documentation files (the "Software"), to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial + * portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +package site.purrbot.bot.command.fun; + +import com.jagrosh.jdautilities.command.SlashCommandEvent; +import net.dv8tion.jda.api.entities.Guild; +import net.dv8tion.jda.api.entities.Member; +import net.dv8tion.jda.api.entities.channel.concrete.TextChannel; +import net.dv8tion.jda.api.interactions.InteractionHook; +import site.purrbot.bot.command.ImageAPICommand; +import site.purrbot.bot.manager.api.ImageAPI; + +public class CmdBlush extends ImageAPICommand{ + + public CmdBlush(){ + this.name = "blush"; + this.help = "Lets you blush."; + + this.loadingMsgPath = new String[]{"purr", "fun", "blush", "loading"}; + + this.apiName = "blush"; + this.apiMessagePath = new String[]{"purr", "fun", "blush", "message"}; + this.apiGif = true; + } + + @Override + protected void handle(SlashCommandEvent event, InteractionHook hook, Guild guild, TextChannel tc, Member member){ + ImageAPI.returnImage(hook, guild.getId(), this, member); + } +} diff --git a/src/main/java/site/purrbot/bot/command/fun/CmdCry.java b/src/main/java/site/purrbot/bot/command/fun/CmdCry.java new file mode 100644 index 000000000..804a09f77 --- /dev/null +++ b/src/main/java/site/purrbot/bot/command/fun/CmdCry.java @@ -0,0 +1,46 @@ +/* + * Copyright 2018 - 2023 Andre601 + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated + * documentation files (the "Software"), to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial + * portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +package site.purrbot.bot.command.fun; + +import com.jagrosh.jdautilities.command.SlashCommandEvent; +import net.dv8tion.jda.api.entities.Guild; +import net.dv8tion.jda.api.entities.Member; +import net.dv8tion.jda.api.entities.channel.concrete.TextChannel; +import net.dv8tion.jda.api.interactions.InteractionHook; +import site.purrbot.bot.command.ImageAPICommand; +import site.purrbot.bot.manager.api.ImageAPI; + +public class CmdCry extends ImageAPICommand{ + + public CmdCry(){ + this.name = "cry"; + this.help = "Lets you cry."; + + this.loadingMsgPath = new String[]{"purr", "fun", "cry", "loading"}; + + this.apiName = "cry"; + this. apiMessagePath = new String[]{"purr", "fun", "cry", "message"}; + this.apiGif = true; + } + + @Override + protected void handle(SlashCommandEvent event, InteractionHook hook, Guild guild, TextChannel tc, Member member){ + ImageAPI.returnImage(hook, guild.getId(), this, member); + } +} diff --git a/src/main/java/site/purrbot/bot/command/fun/CmdImg.java b/src/main/java/site/purrbot/bot/command/fun/CmdImg.java new file mode 100644 index 000000000..e6094ae78 --- /dev/null +++ b/src/main/java/site/purrbot/bot/command/fun/CmdImg.java @@ -0,0 +1,219 @@ +/* + * Copyright 2018 - 2023 Andre601 + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated + * documentation files (the "Software"), to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial + * portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, + * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE + * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +package site.purrbot.bot.command.fun; + +import com.jagrosh.jdautilities.command.SlashCommand; +import com.jagrosh.jdautilities.command.SlashCommandEvent; +import net.dv8tion.jda.api.entities.Guild; +import net.dv8tion.jda.api.entities.Member; +import net.dv8tion.jda.api.entities.channel.concrete.TextChannel; +import net.dv8tion.jda.api.interactions.InteractionHook; +import net.dv8tion.jda.api.interactions.commands.OptionType; +import net.dv8tion.jda.api.interactions.commands.build.OptionData; +import site.purrbot.bot.command.ImageAPICommand; +import site.purrbot.bot.manager.api.ImageAPI; + +import java.util.Collections; + +public class CmdImg extends ImageAPICommand{ + + public CmdImg(){ + this.name = "img"; + this.help = "Contains various sub-commands to get images/gifs."; + + this.children = new SlashCommand[]{ + new Eevee(), + new Holo(), + new Kitsune(), + new Neko(), + new NSFWNeko(), + new Okami(), + new Senko(), + new Shiro() + }; + } + + @Override + protected void handle(SlashCommandEvent event, InteractionHook hook, Guild guild, TextChannel tc, Member member){} + + private static class Eevee extends ImageAPICommand{ + + public Eevee(){ + this.name = "eevee"; + this.help = "Gives an image/gif of a cute Eevee."; + + this.loadingMsgPath = new String[]{"purr", "fun", "img", "eevee", "loading"}; + + this.apiName = "eevee"; + this.apiMessagePath = new String[]{"purr", "fun", "img", "eevee", "message"}; + + this.options = Collections.singletonList( + new OptionData(OptionType.BOOLEAN, "gif", "Whether to return a gif or image") + ); + } + + @Override + protected void handle(SlashCommandEvent event, InteractionHook hook, Guild guild, TextChannel tc, Member member){ + this.apiGif = event.optBoolean("gif"); + + ImageAPI.returnImage(hook, guild.getId(), this, member); + } + } + + private static class Holo extends ImageAPICommand{ + + public Holo(){ + this.name = "holo"; + this.help = "Gives an image from the character Holo from 'Spice & Wolf'"; + + this.loadingMsgPath = new String[]{"purr", "fun", "img", "holo", "loading"}; + + this.apiName = "eevee"; + this.apiMessagePath = new String[]{"purr", "fun", "img", "holo", "message"}; + } + + @Override + protected void handle(SlashCommandEvent event, InteractionHook hook, Guild guild, TextChannel tc, Member member){ + ImageAPI.returnImage(hook, guild.getId(), this, member); + } + } + + private static class Kitsune extends ImageAPICommand{ + + public Kitsune(){ + this.name = "kitsune"; + this.help = "Gives an image of a cute fox girl."; + + this.loadingMsgPath = new String[]{"purr", "fun", "img", "kitsune", "loading"}; + + this.apiName = "eevee"; + this.apiMessagePath = new String[]{"purr", "fun", "img", "kitsune", "message"}; + } + + @Override + protected void handle(SlashCommandEvent event, InteractionHook hook, Guild guild, TextChannel tc, Member member){ + ImageAPI.returnImage(hook, guild.getId(), this, member); + } + } + + private static class Neko extends ImageAPICommand{ + + public Neko(){ + this.name = "neko"; + this.help = "Gives an image/gif of a cute cat girl"; + + this.loadingMsgPath = new String[]{"purr", "fun", "img", "neko", "loading"}; + + this.apiName = "eevee"; + this.apiMessagePath = new String[]{"purr", "fun", "img", "neko", "message"}; + + this.options = Collections.singletonList( + new OptionData(OptionType.BOOLEAN, "gif", "Whether to return a gif or image") + ); + } + + @Override + protected void handle(SlashCommandEvent event, InteractionHook hook, Guild guild, TextChannel tc, Member member){ + this.apiGif = event.optBoolean("gif"); + + ImageAPI.returnImage(hook, guild.getId(), this, member); + } + } + + private static class NSFWNeko extends ImageAPICommand{ + + public NSFWNeko(){ + this.name = "eevee"; + this.help = "Gives an image/gif of a nsfw Cat girl."; + + this.loadingMsgPath = new String[]{"purr", "fun", "img", "nsfw_neko", "loading"}; + + this.nsfwOnly = true; + + this.apiName = "eevee"; + this.apiMessagePath = new String[]{"purr", "fun", "img", "nsfw_neko", "message"}; + this.apiNsfw = true; + + this.options = Collections.singletonList( + new OptionData(OptionType.BOOLEAN, "gif", "Whether to return a gif or image") + ); + } + + @Override + protected void handle(SlashCommandEvent event, InteractionHook hook, Guild guild, TextChannel tc, Member member){ + this.apiGif = event.optBoolean("gif"); + + ImageAPI.returnImage(hook, guild.getId(), this, member); + } + } + + private static class Okami extends ImageAPICommand{ + + public Okami(){ + this.name = "okami"; + this.help = "Gives an image of a cute wolf girl"; + + this.loadingMsgPath = new String[]{"purr", "fun", "img", "okami", "loading"}; + + this.apiName = "okami"; + this.apiMessagePath = new String[]{"purr", "fun", "img", "okami", "message"}; + } + + @Override + protected void handle(SlashCommandEvent event, InteractionHook hook, Guild guild, TextChannel tc, Member member){ + ImageAPI.returnImage(hook, guild.getId(), this, member); + } + } + + private static class Senko extends ImageAPICommand{ + + public Senko(){ + this.name = "senko"; + this.help = "Gives an image of the character Senko-San."; + + this.loadingMsgPath = new String[]{"purr", "fun", "img", "senko", "loading"}; + + this.apiName = "eevee"; + this.apiMessagePath = new String[]{"purr", "fun", "img", "senko", "message"}; + } + + @Override + protected void handle(SlashCommandEvent event, InteractionHook hook, Guild guild, TextChannel tc, Member member){ + ImageAPI.returnImage(hook, guild.getId(), this, member); + } + } + + private static class Shiro extends ImageAPICommand{ + + public Shiro(){ + this.name = "shiro"; + this.help = "Gives an image of the character Shiro."; + + this.loadingMsgPath = new String[]{"purr", "fun", "img", "shiro", "loading"}; + + this.apiName = "eevee"; + this.apiMessagePath = new String[]{"purr", "fun", "img", "shiro", "message"}; + } + + @Override + protected void handle(SlashCommandEvent event, InteractionHook hook, Guild guild, TextChannel tc, Member member){ + ImageAPI.returnImage(hook, guild.getId(), this, member); + } + } +} diff --git a/src/main/java/site/purrbot/bot/manager/DBManager.java b/src/main/java/site/purrbot/bot/manager/DBManager.java index ab70025cb..ad761cb51 100644 --- a/src/main/java/site/purrbot/bot/manager/DBManager.java +++ b/src/main/java/site/purrbot/bot/manager/DBManager.java @@ -23,6 +23,7 @@ import com.rethinkdb.net.Connection; import com.rethinkdb.utils.Types; import site.purrbot.bot.PurrBot; +import site.purrbot.bot.manager.file.FileManager; import site.purrbot.bot.manager.guild.GuildSettingsManager; import java.util.Map; @@ -38,11 +39,11 @@ public class DBManager{ public DBManager(){ r = RethinkDB.r; connection = r.connection() - .hostname(PurrBot.getBot().getFileManager().getString("config", "localhost", "database", "ip")) + .hostname(FileManager.get().getString("config", "database", "ip")) .port(28015) - .db(PurrBot.getBot().getFileManager().getString("config", "main", "database", "name")) + .db(FileManager.get().getString("config", "database", "name")) .connect(); - guildTable = PurrBot.getBot().getFileManager().getString("config", "guilds", "database", "guildTable"); + guildTable = FileManager.get().getString("config", "database", "guildTable"); } public void addGuild(String id){ diff --git a/src/main/java/site/purrbot/bot/manager/EmbedManager.java b/src/main/java/site/purrbot/bot/manager/EmbedManager.java index c99bf63bc..74a2d7b2c 100644 --- a/src/main/java/site/purrbot/bot/manager/EmbedManager.java +++ b/src/main/java/site/purrbot/bot/manager/EmbedManager.java @@ -22,6 +22,7 @@ import site.purrbot.bot.manager.string.MessageHandler; import java.time.Instant; +import java.util.function.Function; public class EmbedManager{ @@ -39,6 +40,11 @@ public static EmbedBuilder getDefaultEmbed(){ return new EmbedBuilder().setTimestamp(Instant.now()).setColor(0x802F3136); } + public EmbedManager modify(Function function){ + messageHandler.modify(function); + return this; + } + public EmbedManager replace(String target, Object replacement){ messageHandler.replace(target, replacement); return this; diff --git a/src/main/java/site/purrbot/bot/manager/api/ImageAPI.java b/src/main/java/site/purrbot/bot/manager/api/ImageAPI.java index b96a0ec4e..59bfb1b99 100644 --- a/src/main/java/site/purrbot/bot/manager/api/ImageAPI.java +++ b/src/main/java/site/purrbot/bot/manager/api/ImageAPI.java @@ -31,6 +31,7 @@ import site.purrbot.bot.manager.api.response.ImageAPIErrorResponse; import site.purrbot.bot.manager.api.response.ImageAPISuccessResponse; import site.purrbot.bot.manager.command.CommandError; +import site.purrbot.bot.manager.string.StringReplacer; import java.io.IOException; import java.util.concurrent.CompletableFuture; @@ -40,33 +41,37 @@ public class ImageAPI{ private static final OkHttpClient CLIENT = new OkHttpClient(); private static final Gson GSON = new Gson(); + public static void returnImage(InteractionHook hook, String guildId, ImageAPICommand command, Member member){ + returnImage(hook, guildId, command, member, null); + } + public static void returnImage(InteractionHook hook, String guildId, ImageAPICommand command, Member member, String targets){ getImage(command).whenComplete((response, throwable) -> { if(throwable != null){ CommandError.fromPath(guildId, "errors", "image_api", "unknown_error") - .replace("{error}", throwable.getMessage()) + .modify(text -> StringReplacer.replace(text, "{error}", throwable.getMessage())) .send(hook); return; } - if((response instanceof ImageAPIErrorResponse) && command.isRequired()){ + if((response instanceof ImageAPIErrorResponse error) && command.isRequired()){ CommandError.fromPath(guildId, "errors", "image_api", "not_successful") - .replace("{error}", ((ImageAPIErrorResponse)response).getMessage()) + .modify(text -> StringReplacer.replace(text, "{error}", error.getMessage())) .send(hook); return; } EmbedManager manager = EmbedManager.get(guildId, command.getMessagePath()); if(member != null) - manager.replace("{user}", member.getEffectiveName()); + manager.modify(text -> StringReplacer.replace(text, "{user}", member.getEffectiveName())); if(targets != null && !targets.isEmpty()) - manager.replace("{targets}", targets); + manager.modify(text -> StringReplacer.replace(text, "{targets}", targets)); EmbedBuilder embed = manager.getEmbed(); - if(response instanceof ImageAPISuccessResponse) - embed.setImage(((ImageAPISuccessResponse)response).getLink()); + if(response instanceof ImageAPISuccessResponse imgResponse) + embed.setImage(imgResponse.getLink()); hook.editOriginalEmbeds(embed.build()).queue(); }); diff --git a/src/main/java/site/purrbot/bot/manager/command/CommandError.java b/src/main/java/site/purrbot/bot/manager/command/CommandError.java index e0e5b76ae..acbaac3e4 100644 --- a/src/main/java/site/purrbot/bot/manager/command/CommandError.java +++ b/src/main/java/site/purrbot/bot/manager/command/CommandError.java @@ -23,16 +23,16 @@ import net.dv8tion.jda.api.entities.MessageEmbed; import net.dv8tion.jda.api.interactions.InteractionHook; import site.purrbot.bot.manager.string.MessageHandler; -import site.purrbot.bot.manager.string.StringReplacer; import java.time.Instant; +import java.util.function.Function; public class CommandError{ private String message; private CommandError(String guildId, String... path){ - this.message = guildId == null ? String.valueOf(path[0]) : MessageHandler.getTranslation(guildId, path).getMessage(); + this.message = guildId == null ? path[0] : MessageHandler.getTranslation(guildId, path).getMessage(); } public static CommandError fromStatic(String message){ @@ -43,11 +43,8 @@ public static CommandError fromPath(String guildId, String... path){ return new CommandError(guildId, path); } - public CommandError replace(String input, Object output){ - if(input == null || input.isEmpty() || output == null) - return this; - - this.message = StringReplacer.replace(message, input, output); + public CommandError modify(Function function){ + this.message = function.apply(message); return this; } diff --git a/src/main/java/site/purrbot/bot/manager/file/FileManager.java b/src/main/java/site/purrbot/bot/manager/file/FileManager.java index f12932669..8604416bd 100644 --- a/src/main/java/site/purrbot/bot/manager/file/FileManager.java +++ b/src/main/java/site/purrbot/bot/manager/file/FileManager.java @@ -18,7 +18,7 @@ package site.purrbot.bot.manager.file; -import ch.qos.logback.classic.Logger; +import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.spongepowered.configurate.ConfigurationNode; import org.spongepowered.configurate.gson.GsonConfigurationLoader; @@ -34,42 +34,64 @@ public class FileManager{ - private final Logger logger = (Logger)LoggerFactory.getLogger(FileManager.class); + private static FileManager instance = null; + private final Logger logger = LoggerFactory.getLogger(FileManager.class); + + private final Random random = new Random(); private final Map files = new HashMap<>(); - private final List languages = new ArrayList<>(); public FileManager(){} + public static FileManager get(){ + if(instance != null) + return instance; + + return (instance = new FileManager()); + } + public FileManager addLanguage(String language){ String filePath = "/lang/" + language + ".json"; if(!createOrLoad(language.toLowerCase(Locale.ROOT), filePath, "." + filePath)){ logger.warn("Cannot create lang file {}. Skipping...", language); - return this; } - languages.add(language.toLowerCase(Locale.ROOT)); return this; } - public List getLanguages(){ - return languages; - } - public FileManager addFile(String name){ String filePath = "/" + name + ".json"; createOrLoad(name, filePath, "." + filePath); return this; } - public String getString(String name, String def, String... path){ + public String getString(String name, String... path){ ConfigurationNode node = files.get(name); if(node == null) - return def; + return "ERROR: Unknown file `" + name + "` provided!"; - Object[] objPath = convertStringPath(path); + return fromPath(node, path).getString("ERROR: Invalid path `" + String.join(" -> ", path) + "` provided!"); + } + + public String getRandomString(String name, String... path){ + ConfigurationNode node = files.get(name); + if(node == null) + return "ERROR: Unknown file `" + name + "` provided!"; + + ConfigurationNode listNode = fromPath(node, path); + if(!listNode.isList()) + return "ERROR: Path `" + String.join(" -> ", path) + "` is not a list!"; + + List list = getStringList(name, path); + if(list.isEmpty()) + return "ERROR: Provided path `" + String.join(" -> ", path) + "` had no entries."; - return node.node(objPath).getString(def); + if(list.size() == 1) + return list.get(0); // No need to use random on a list with 1 entry. + + synchronized(random){ + return list.get(random.nextInt(list.size())); + } } public List getStringList(String name, String... path){ @@ -78,8 +100,7 @@ public List getStringList(String name, String... path){ return Collections.emptyList(); try{ - Object[] objPath = convertStringPath(path); - return node.node(objPath).getList(String.class); + return fromPath(node, path).getList(String.class); }catch(SerializationException ex){ return Collections.emptyList(); } @@ -94,13 +115,22 @@ public boolean getBoolean(String name, boolean def, String... path){ return node.node(objPath).getBoolean(def); } - public int isList(String name, String... path){ + public boolean hasLanguage(String language){ + return files.containsKey(language.toLowerCase(Locale.ROOT)); + } + + public int resolveType(String name, String... path){ ConfigurationNode node = files.get(name); if(node == null) return -1; - Object[] objPath = convertStringPath(path); - return node.node(objPath).isList() ? 1 : 0; + return fromPath(node, path).isList() ? 1 : 0; + } + + private ConfigurationNode fromPath(ConfigurationNode node, String... path){ + Object[] finalPath = convertStringPath(path); + + return node.node(finalPath); } private boolean createOrLoad(String name, String internalPath, String externalPath){ diff --git a/src/main/java/site/purrbot/bot/manager/guild/GuildSettingsManager.java b/src/main/java/site/purrbot/bot/manager/guild/GuildSettingsManager.java index 87092c05c..1dab492aa 100644 --- a/src/main/java/site/purrbot/bot/manager/guild/GuildSettingsManager.java +++ b/src/main/java/site/purrbot/bot/manager/guild/GuildSettingsManager.java @@ -43,12 +43,25 @@ public class GuildSettingsManager{ DEF_WELCOME_ICON = "purr", DEF_WELCOME_MESSAGE = "Welcome {mention]!"; + private static GuildSettingsManager instance = null; + private final Cache guildSettingsCache = Caffeine.newBuilder() .expireAfterWrite(10, TimeUnit.MINUTES) .build(); public GuildSettingsManager(){} + public static GuildSettingsManager get(){ + if(instance != null) + return instance; + + return (instance = new GuildSettingsManager()); + } + + public GuildSettings settings(String id){ + return getSettings(id); + } + public String getLanguage(String id){ return getSettings(id).getLanguage(); } diff --git a/src/main/java/site/purrbot/bot/manager/string/MessageHandler.java b/src/main/java/site/purrbot/bot/manager/string/MessageHandler.java index c80b6c04a..2fcfc039f 100644 --- a/src/main/java/site/purrbot/bot/manager/string/MessageHandler.java +++ b/src/main/java/site/purrbot/bot/manager/string/MessageHandler.java @@ -19,11 +19,11 @@ package site.purrbot.bot.manager.string; import org.jetbrains.annotations.NotNull; -import site.purrbot.bot.PurrBot; import site.purrbot.bot.constants.Emotes; import site.purrbot.bot.manager.file.FileManager; +import site.purrbot.bot.manager.guild.GuildSettingsManager; -import java.util.*; +import java.util.function.Function; public class MessageHandler{ @@ -35,43 +35,36 @@ public MessageHandler(String message){ @NotNull public static MessageHandler getTranslation(String guildId, String... path){ - String language = PurrBot.getBot().getGuildSettingsManager().getLanguage(guildId); - FileManager fileManager = PurrBot.getBot().getFileManager(); - String textPath = String.join(".", path); + String language = GuildSettingsManager.get().settings(guildId).getLanguage(); + String textPath = String.join(" -> ", path); - String msg = null; - for(String lang : fileManager.getLanguages()){ - if(lang.equalsIgnoreCase(language)){ - int isListResult = fileManager.isList(language, path); - if(isListResult == -1){ - msg = "ERROR: Invalid path `" + textPath + "` for guild id `" + guildId + "`! String was empty/null."; - break; - }else - if(isListResult == 1){ - List lines = fileManager.getStringList(language, path); - if(lines.isEmpty()){ - msg = "ERROR: Invalid path `" + textPath + "` for guild id `" + guildId + "`! List was empty."; - }else{ - msg = lines.get(PurrBot.getBot().getRandom().nextInt(lines.size())); - } - break; - }else{ - msg = fileManager.getString( - language, - "ERROR: Could not get message from path `" + textPath + "`!", - path - ); - break; - } - } + String msg; + if(!FileManager.get().hasLanguage(language)) + language = "en"; + + int type = FileManager.get().resolveType(language, path); + if(type == -1){ + // Unknown/Invalid type + msg = "ERROR: Invalid path `" + textPath + "`! `" + language + "` had no matching language file."; + }else + if(type == 1){ + // Type is a list, so get a random String from it. + msg = FileManager.get().getRandomString(language, path); + }else{ + msg = FileManager.get().getString(language, path); } if(msg == null || msg.isEmpty()) - msg = "ERROR: Invalid path `" + textPath + "` for guild id `" + guildId + "`! String was empty/null."; + msg = "ERROR: Invalid path `" + textPath + "`! Retrieved text was empty/null."; return new MessageHandler(msg); } + public MessageHandler modify(Function function){ + this.message = function.apply(message); + return this; + } + public MessageHandler replace(String target, Object replacement){ this.message = StringReplacer.replace(message, target, replacement); return this; diff --git a/src/main/java/site/purrbot/bot/manager/string/StringReplacer.java b/src/main/java/site/purrbot/bot/manager/string/StringReplacer.java index 4b760364a..3f1894c02 100644 --- a/src/main/java/site/purrbot/bot/manager/string/StringReplacer.java +++ b/src/main/java/site/purrbot/bot/manager/string/StringReplacer.java @@ -23,6 +23,9 @@ public class StringReplacer{ public static String replace(String input, String target, Object replacement){ + if(input == null || input.isEmpty() || target == null || target.isEmpty() || replacement == null) + return input; + StringBuilder output = new StringBuilder(input); int index = 0; while((index = output.indexOf(target, index)) != -1){ From 57b44be220dc1cdda325ad5588f71c17093d7c0c Mon Sep 17 00:00:00 2001 From: Andre601 Date: Sun, 2 Apr 2023 16:43:40 +0200 Subject: [PATCH 6/6] Change to implementation --- build.gradle | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/build.gradle b/build.gradle index 1a0c8cbaf..c436022ba 100644 --- a/build.gradle +++ b/build.gradle @@ -43,19 +43,19 @@ repositories { } dependencies { - compile group: 'ch.qos.logback', name: 'logback-classic', version: '1.2.11' - compile group: 'pw.chew', name: 'jda-chewtils-commons', version: '2.0-SNAPSHOT' - compile group: 'pw.chew', name: 'jda-chewtils-menu', version: '2.0-SNAPSHOT' - compile group: 'pw.chew', name: 'jda-chewtils-command', version: '2.0-SNAPSHOT' - compile group: 'com.rethinkdb', name: 'rethinkdb-driver', version:'2.4.4' - compile(group: 'net.dv8tion', name: 'JDA', version:'5.0.0-beta.6'){ + implementation group: 'ch.qos.logback', name: 'logback-classic', version: '1.2.11' + implementation group: 'pw.chew', name: 'jda-chewtils-commons', version: '2.0-SNAPSHOT' + implementation group: 'pw.chew', name: 'jda-chewtils-menu', version: '2.0-SNAPSHOT' + implementation group: 'pw.chew', name: 'jda-chewtils-command', version: '2.0-SNAPSHOT' + implementation group: 'com.rethinkdb', name: 'rethinkdb-driver', version:'2.4.4' + implementation(group: 'net.dv8tion', name: 'JDA', version:'5.0.0-beta.6'){ exclude(module: 'opus-java') } - compile group: 'club.minnced', name: 'discord-webhooks', version: '0.8.2' - compile group: 'com.github.ben-manes.caffeine', name: 'caffeine', version: '3.1.1' - compile group: 'com.squareup.okhttp3', name: 'okhttp', version: '4.10.0' - compile group: 'com.google.code.gson', name: 'gson', version: '2.8.9' - compile group: 'org.spongepowered', name: 'configurate-gson', version: '4.1.2' + implementation group: 'club.minnced', name: 'discord-webhooks', version: '0.8.2' + implementation group: 'com.github.ben-manes.caffeine', name: 'caffeine', version: '3.1.1' + implementation group: 'com.squareup.okhttp3', name: 'okhttp', version: '4.10.0' + implementation group: 'com.google.code.gson', name: 'gson', version: '2.8.9' + implementation group: 'org.spongepowered', name: 'configurate-gson', version: '4.1.2' } compileJava {