📝 Add discord webhook

This commit is contained in:
Maxlego08 2024-02-22 19:04:09 +01:00
parent fe6f486b27
commit 4bf67103ac
10 changed files with 641 additions and 7 deletions

View File

@ -170,6 +170,13 @@
<scope>system</scope>
<systemPath>${basedir}/libs/TitleManager-2.3.6.jar</systemPath>
</dependency>
<dependency>
<groupId>com.github.decentsoftware-eu</groupId>
<artifactId>decentholograms</artifactId>
<version>2.8.6</version>
<scope>system</scope>
<systemPath>${basedir}/libs/DecentHolograms-2.8.6.jar</systemPath>
</dependency>
</dependencies>
<properties>
<maven.compiler.target>8</maven.compiler.target>

View File

@ -1,9 +1,11 @@
package fr.maxlego08.koth;
import fr.maxlego08.koth.api.Koth;
import fr.maxlego08.koth.api.KothEvent;
import fr.maxlego08.koth.api.KothStatus;
import fr.maxlego08.koth.api.KothTeam;
import fr.maxlego08.koth.api.KothType;
import fr.maxlego08.koth.api.discord.DiscordWebhookConfig;
import fr.maxlego08.koth.api.events.KothCapEvent;
import fr.maxlego08.koth.api.events.KothCatchEvent;
import fr.maxlego08.koth.api.events.KothLooseEvent;
@ -68,8 +70,9 @@ public class ZKoth extends ZUtils implements Koth {
private AtomicInteger remainingSeconds;
private TimerTask timerTask;
private TimerTask timerTaskStop;
private DiscordWebhookConfig discordWebhookConfig;
public ZKoth(KothPlugin plugin, String fileName, KothType kothType, String name, int captureSeconds, Location minLocation, Location maxLocation, List<String> startCommands, List<String> endCommands, ScoreboardConfiguration cooldownScoreboard, ScoreboardConfiguration startScoreboard, int cooldownStart, int stopAfterSeconds, boolean enableStartCapMessage, boolean enableLooseCapMessage, boolean enableEverySecondsCapMessage, HologramConfig hologramConfig) {
public ZKoth(KothPlugin plugin, String fileName, KothType kothType, String name, int captureSeconds, Location minLocation, Location maxLocation, List<String> startCommands, List<String> endCommands, ScoreboardConfiguration cooldownScoreboard, ScoreboardConfiguration startScoreboard, int cooldownStart, int stopAfterSeconds, boolean enableStartCapMessage, boolean enableLooseCapMessage, boolean enableEverySecondsCapMessage, HologramConfig hologramConfig, DiscordWebhookConfig discordWebhookConfig) {
this.plugin = plugin;
this.fileName = fileName;
this.kothType = kothType;
@ -87,6 +90,7 @@ public class ZKoth extends ZUtils implements Koth {
this.enableLooseCapMessage = enableLooseCapMessage;
this.enableEverySecondsCapMessage = enableEverySecondsCapMessage;
this.hologramConfig = hologramConfig;
this.discordWebhookConfig = discordWebhookConfig;
}
public ZKoth(KothPlugin plugin, String fileName, KothType kothType, String name, int captureSeconds, Location minLocation, Location maxLocation) {
@ -105,6 +109,7 @@ public class ZKoth extends ZUtils implements Koth {
this.enableLooseCapMessage = true;
this.enableEverySecondsCapMessage = false;
this.hologramConfig = new HologramConfig(false, new ArrayList<>(), getCenter());
this.discordWebhookConfig = null;
}
@Override
@ -234,10 +239,14 @@ public class ZKoth extends ZUtils implements Koth {
@Override
public void stop() {
if (this.kothStatus != KothStatus.STOP) return;
KothStopEvent event = new KothStopEvent(this);
event.call();
if (event.isCancelled()) return;
this.discordWebhookConfig.send(this.plugin, this, KothEvent.STOP);
broadcast(Message.EVENT_STOP);
@ -279,6 +288,8 @@ public class ZKoth extends ZUtils implements Koth {
if (event.isCancelled()) return;
this.discordWebhookConfig.send(this.plugin, this, KothEvent.START);
if (this.cooldownScoreboard.isEnable()) {
ScoreBoardManager scoreBoardManager = this.plugin.getScoreBoardManager();
scoreBoardManager.setLinesAndSchedule(onScoreboard());
@ -324,6 +335,7 @@ public class ZKoth extends ZUtils implements Koth {
event.call();
if (event.isCancelled()) return;
this.discordWebhookConfig.send(this.plugin, this, KothEvent.SPAWN);
this.remainingSeconds = new AtomicInteger(this.captureSeconds);
@ -361,7 +373,7 @@ public class ZKoth extends ZUtils implements Koth {
this.timerTaskStop = new TimerTask() {
@Override
public void run() {
// plugin.getKothHologram().end(koth);
plugin.getKothHologram().end(koth);
Bukkit.getScheduler().runTask(plugin, () -> stop(Bukkit.getConsoleSender()));
}
};
@ -400,6 +412,8 @@ public class ZKoth extends ZUtils implements Koth {
KothLooseEvent event = new KothLooseEvent(this.currentPlayer, this);
event.call();
this.discordWebhookConfig.send(this.plugin, this, KothEvent.LOOSE);
if (event.isCancelled()) return;
this.plugin.getKothHologram().update(this);
@ -433,6 +447,8 @@ public class ZKoth extends ZUtils implements Koth {
return;
}
this.discordWebhookConfig.send(this.plugin, this, KothEvent.START_CAP);
if (enableStartCapMessage) {
broadcast(Message.EVENT_CATCH);
}
@ -473,9 +489,9 @@ public class ZKoth extends ZUtils implements Koth {
KothLooseEvent kothLooseEvent = new KothLooseEvent(null, this);
kothLooseEvent.call();
if (kothLooseEvent.isCancelled()) {
return;
}
if (kothLooseEvent.isCancelled()) return;
this.discordWebhookConfig.send(this.plugin, this, KothEvent.LOOSE);
if (this.timerTask != null) {
this.timerTask.cancel();
@ -533,6 +549,8 @@ public class ZKoth extends ZUtils implements Koth {
if (kothWinEvent.isCancelled()) return;
this.discordWebhookConfig.send(this.plugin, this, KothEvent.WIN);
this.plugin.getKothHologram().end(this);
task.cancel();
broadcast(Message.EVENT_WIN);
@ -668,6 +686,8 @@ public class ZKoth extends ZUtils implements Koth {
@Override
public String replaceMessage(String string) {
if (string == null) return null;
string = string.replace("%playerName%", this.currentPlayer != null ? this.currentPlayer.getName() : Config.noPlayer);
string = string.replace("%teamName%", this.currentPlayer != null ? this.currentPlayer.getName() : Config.noPlayer);
@ -678,6 +698,11 @@ public class ZKoth extends ZUtils implements Koth {
return replaceKothInformations(string);
}
@Override
public DiscordWebhookConfig getDiscordWebhookConfig() {
return this.discordWebhookConfig;
}
private String replaceKothInformations(String string) {
Location centerLocation = getCenter();

View File

@ -1,6 +1,7 @@
package fr.maxlego08.koth.api;
import fr.maxlego08.koth.KothPlugin;
import fr.maxlego08.koth.api.discord.DiscordWebhookConfig;
import fr.maxlego08.koth.api.utils.HologramConfig;
import fr.maxlego08.koth.api.utils.ScoreboardConfiguration;
import fr.maxlego08.koth.zcore.utils.Cuboid;
@ -70,4 +71,6 @@ public interface Koth {
HologramConfig getHologramConfig();
String replaceMessage(String string);
DiscordWebhookConfig getDiscordWebhookConfig();
}

View File

@ -0,0 +1,10 @@
package fr.maxlego08.koth.api;
public enum KothEvent {
START,
STOP,
START_CAP,
WIN, SPAWN, LOOSE,
}

View File

@ -0,0 +1,49 @@
package fr.maxlego08.koth.api.discord;
import java.awt.Color;
import org.bukkit.configuration.file.YamlConfiguration;
public class DiscordColor {
private final int r;
private final int g;
private final int b;
public DiscordColor(int r, int g, int b) {
super();
this.r = r;
this.g = g;
this.b = b;
}
public DiscordColor(YamlConfiguration configuration, String path) {
this(configuration.getInt(path + "r"), configuration.getInt(path + "g"), configuration.getInt(path + "b"));
}
/**
* @return the r
*/
public int getR() {
return r;
}
/**
* @return the g
*/
public int getG() {
return g;
}
/**
* @return the b
*/
public int getB() {
return b;
}
public Color getColor() {
return new Color(this.r, this.g, this.b);
}
}

View File

@ -0,0 +1,433 @@
package fr.maxlego08.koth.api.discord;
import fr.maxlego08.koth.api.Koth;
import fr.maxlego08.koth.api.KothEvent;
import fr.maxlego08.koth.zcore.utils.ZUtils;
import org.bukkit.configuration.file.YamlConfiguration;
import javax.net.ssl.HttpsURLConnection;
import java.awt.*;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Array;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
/**
* Class used to execute Discord Webhooks with low effort
*/
public class DiscordWebhook extends ZUtils {
private final String url;
private transient final Pattern STRIP_EXTRAS_PATTERN = Pattern.compile("(?i)§[0-9A-FK-ORX]");
private String content;
private String username;
private String avatarUrl;
private boolean tts;
private List<EmbedObject> embeds = new ArrayList<>();
/**
* Constructs a new DiscordWebhook instance
*
* @param url The webhook URL obtained in Discord
*/
public DiscordWebhook(String url) {
this.url = url;
}
public void setContent(String content) {
this.content = content;
}
public void setUsername(String username) {
this.username = username;
}
public void setAvatarUrl(String avatarUrl) {
this.avatarUrl = avatarUrl;
}
public void setTts(boolean tts) {
this.tts = tts;
}
public void addEmbed(EmbedObject embed) {
this.embeds.add(embed);
}
public void execute(Koth koth) throws IOException {
if (this.content == null && this.embeds.isEmpty()) {
throw new IllegalArgumentException("Set content or add at least one EmbedObject");
}
JSONObject json = new JSONObject();
if (this.content != null) json.put("content", koth.replaceMessage(this.content));
if (this.username != null) json.put("username", koth.replaceMessage(this.username));
if (this.avatarUrl != null) json.put("avatar_url", this.avatarUrl);
if (this.tts) json.put("tts", true);
if (!this.embeds.isEmpty()) {
List<JSONObject> embedObjects = new ArrayList<>();
for (EmbedObject embed : this.embeds) {
JSONObject jsonEmbed = new JSONObject();
jsonEmbed.put("title", koth.replaceMessage(embed.getTitle()));
jsonEmbed.put("description", koth.replaceMessage(embed.getDescription()));
jsonEmbed.put("url", koth.replaceMessage(embed.getUrl()));
if (embed.getColor() != null) {
Color color = embed.getColor().getColor();
int rgb = color.getRed();
rgb = (rgb << 8) + color.getGreen();
rgb = (rgb << 8) + color.getBlue();
jsonEmbed.put("color", rgb);
}
EmbedObject.Footer footer = embed.getFooter();
String image = embed.getImage();
String thumbnail = embed.getThumbnail();
EmbedObject.Author author = embed.getAuthor();
List<EmbedObject.Field> fields = embed.getFields();
if (footer != null) {
JSONObject jsonFooter = new JSONObject();
if (footer.getText() != null) {
jsonFooter.put("text", koth.replaceMessage(footer.getText()));
}
if (footer.getIconUrl() != null) {
jsonFooter.put("icon_url", koth.replaceMessage(footer.getIconUrl()));
}
if (footer.getIconUrl() != null || footer.getText() != null) {
jsonEmbed.put("footer", jsonFooter);
}
}
if (image != null) {
JSONObject jsonImage = new JSONObject();
jsonImage.put("url", koth.replaceMessage(image));
jsonEmbed.put("image", jsonImage);
}
if (thumbnail != null) {
JSONObject jsonThumbnail = new JSONObject();
jsonThumbnail.put("url", koth.replaceMessage(thumbnail));
jsonEmbed.put("thumbnail", jsonThumbnail);
}
if (author != null) {
if (author.getName() != null && author.getUrl() != null && author.getIconUrl() != null) {
JSONObject jsonAuthor = new JSONObject();
jsonAuthor.put("url", koth.replaceMessage(author.getUrl()));
jsonAuthor.put("name", koth.replaceMessage(author.getName()));
jsonAuthor.put("icon_url", koth.replaceMessage(author.getIconUrl()));
jsonEmbed.put("author", jsonAuthor);
}
}
List<JSONObject> jsonFields = new ArrayList<>();
for (EmbedObject.Field field : fields) {
JSONObject jsonField = new JSONObject();
jsonField.put("name", koth.replaceMessage(field.getName()));
jsonField.put("value", koth.replaceMessage(field.getValue()));
jsonField.put("inline", field.isInline());
jsonFields.add(jsonField);
}
jsonEmbed.put("fields", jsonFields.toArray());
embedObjects.add(jsonEmbed);
}
json.put("embeds", embedObjects.toArray());
}
URL url = new URL(this.url);
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.addRequestProperty("Content-Type", "application/json");
connection.addRequestProperty("User-Agent", "Java-DiscordWebhook-BY-Gelox_");
connection.setDoOutput(true);
connection.setRequestMethod("POST");
OutputStream stream = connection.getOutputStream();
stream.write(json.toString().getBytes(StandardCharsets.UTF_8));
stream.flush();
stream.close();
connection.getInputStream().close();
connection.disconnect();
}
public static class EmbedObject {
private KothEvent event;
private String title;
private String description;
private String url;
private DiscordColor color;
private Footer footer;
private String thumbnail;
private String image;
private Author author;
private List<Field> fields = new ArrayList<>();
public EmbedObject(YamlConfiguration configuration, String path) {
this.event = KothEvent.valueOf(configuration.getString(path + "event", "START").toUpperCase());
this.title = configuration.getString(path + "title", null);
this.description = configuration.getString(path + "description", null);
this.url = configuration.getString(path + "url", null);
this.color = new DiscordColor(configuration, path + "color.");
this.footer = new Footer(configuration, path);
this.thumbnail = configuration.getString(path + "thumbnail", null);
this.image = configuration.getString(path + "image", null);
this.author = new Author(configuration, path);
List<?> list = configuration.getList(path + "fields", new ArrayList<>());
this.fields = ((List<Map<String, Object>>) list).stream().map(Field::new).collect(Collectors.toList());
}
public KothEvent getEvent() {
return event;
}
public String getTitle() {
return title;
}
public EmbedObject setTitle(String title) {
this.title = title;
return this;
}
public String getDescription() {
return description;
}
public EmbedObject setDescription(String description) {
this.description = description;
return this;
}
public String getUrl() {
return url;
}
public EmbedObject setUrl(String url) {
this.url = url;
return this;
}
public DiscordColor getColor() {
return color;
}
public EmbedObject setColor(DiscordColor color) {
this.color = color;
return this;
}
public Footer getFooter() {
return footer;
}
public String getThumbnail() {
return thumbnail;
}
public EmbedObject setThumbnail(String url) {
this.thumbnail = url;
return this;
}
public String getImage() {
return image;
}
public EmbedObject setImage(String url) {
this.image = url;
return this;
}
public Author getAuthor() {
return author;
}
public List<Field> getFields() {
return fields;
}
public EmbedObject setFooter(String text, String icon) {
this.footer = new Footer(text, icon);
return this;
}
public EmbedObject setAuthor(String name, String url, String icon) {
this.author = new Author(name, url, icon);
return this;
}
public EmbedObject addField(String name, String value, boolean inline) {
this.fields.add(new Field(name, value, inline));
return this;
}
private class Footer {
private String text;
private String iconUrl;
private Footer(String text, String iconUrl) {
this.text = text;
this.iconUrl = iconUrl;
}
public Footer(YamlConfiguration configuration, String path) {
this(configuration.getString(path + "text"), configuration.getString(path + "iconUrl"));
}
private String getText() {
return text;
}
private String getIconUrl() {
return iconUrl;
}
}
private class Author {
private String name;
private String url;
private String iconUrl;
private Author(String name, String url, String iconUrl) {
this.name = name;
this.url = url;
this.iconUrl = iconUrl;
}
public Author(YamlConfiguration configuration, String path) {
this(configuration.getString(path + "name"), configuration.getString(path + "url"),
configuration.getString(path + "iconUrl"));
}
private String getName() {
return name;
}
private String getUrl() {
return url;
}
private String getIconUrl() {
return iconUrl;
}
}
private class Field {
private String name;
private String value;
private boolean inline;
private Field(String name, String value, boolean inline) {
this.name = name;
this.value = value;
this.inline = inline;
}
private Field(Map<String, Object> map) {
this((String) map.get("name"), (String) map.get("value"), (boolean) map.get("inline"));
}
private String getName() {
return name;
}
private String getValue() {
return value;
}
private boolean isInline() {
return inline;
}
}
@Override
public String toString() {
return "EmbedObject{" +
"event=" + event +
", title='" + title + '\'' +
", description='" + description + '\'' +
", url='" + url + '\'' +
", color=" + color +
", footer=" + footer +
", thumbnail='" + thumbnail + '\'' +
", image='" + image + '\'' +
", author=" + author +
", fields=" + fields +
'}';
}
}
private class JSONObject {
private final HashMap<String, Object> map = new HashMap<>();
void put(String key, Object value) {
if (value != null) {
map.put(key, value);
}
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
Set<Map.Entry<String, Object>> entrySet = map.entrySet();
builder.append("{");
int i = 0;
for (Map.Entry<String, Object> entry : entrySet) {
Object val = entry.getValue();
builder.append(quote(entry.getKey())).append(":");
if (val instanceof String) {
builder.append(quote(String.valueOf(val)));
} else if (val instanceof Integer) {
builder.append(Integer.valueOf(String.valueOf(val)));
} else if (val instanceof Boolean) {
builder.append(val);
} else if (val instanceof JSONObject) {
builder.append(val.toString());
} else if (val.getClass().isArray()) {
builder.append("[");
int len = Array.getLength(val);
for (int j = 0; j < len; j++) {
builder.append(Array.get(val, j).toString()).append(j != len - 1 ? "," : "");
}
builder.append("]");
}
builder.append(++i == entrySet.size() ? "}" : ",");
}
return builder.toString();
}
private String quote(String string) {
return "\"" + string + "\"";
}
}
}

View File

@ -0,0 +1,67 @@
package fr.maxlego08.koth.api.discord;
import fr.maxlego08.koth.api.Koth;
import fr.maxlego08.koth.api.KothEvent;
import fr.maxlego08.koth.zcore.utils.ZUtils;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.Plugin;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
public class DiscordWebhookConfig extends ZUtils {
private final String url;
private final boolean isEnable;
private final List<DiscordWebhook.EmbedObject> embeds = new ArrayList<>();
public DiscordWebhookConfig(YamlConfiguration configuration) {
super();
this.url = configuration.getString("webhook.url", "https://discord.com/api/webhooks/xxxxx/xxxxxxxxxxxx");
this.isEnable = configuration.getBoolean("webhook.enable", false);
ConfigurationSection configurationSection = configuration.getConfigurationSection("webhook.events");
if (configurationSection != null) {
configurationSection.getKeys(false).forEach(key -> {
String path = "webhook.events." + key + ".";
this.embeds.add(new DiscordWebhook.EmbedObject(configuration, path));
});
}
}
public String getUrl() {
return url;
}
public boolean isEnable() {
return isEnable;
}
public List<DiscordWebhook.EmbedObject> getEmbeds() {
return embeds;
}
public void send(Plugin plugin, Koth koth, KothEvent event) {
if (this.isEnable) {
DiscordWebhook discordWebhook = new DiscordWebhook(this.url);
Optional<DiscordWebhook.EmbedObject> optional = this.embeds.stream().filter(e -> e.getEvent() == event).findFirst();
if (!optional.isPresent()) return;
discordWebhook.addEmbed(optional.get());
this.runAsync(plugin, () -> {
try {
discordWebhook.execute(koth);
} catch (IOException exception) {
exception.printStackTrace();
}
});
}
}
}

View File

@ -21,6 +21,8 @@ public class DecentHologram implements KothHologram {
HologramConfig config = koth.getHologramConfig();
if (!config.isEnable()) return;
DHAPI.removeHologram("ZKOTH-" + koth.getFileName());
Hologram hologram = DHAPI.createHologram("ZKOTH-" + koth.getFileName(), config.getLocation());
this.holograms.put(koth, hologram);
updateLine(koth, hologram);

View File

@ -4,6 +4,7 @@ import fr.maxlego08.koth.KothPlugin;
import fr.maxlego08.koth.ZKoth;
import fr.maxlego08.koth.api.Koth;
import fr.maxlego08.koth.api.KothType;
import fr.maxlego08.koth.api.discord.DiscordWebhookConfig;
import fr.maxlego08.koth.api.utils.HologramConfig;
import fr.maxlego08.koth.api.utils.ScoreboardConfiguration;
import fr.maxlego08.koth.zcore.utils.ZUtils;
@ -45,8 +46,10 @@ public class KothLoader extends ZUtils implements Loader<Koth> {
ScoreboardConfiguration startScoreboard = scoreboardLoaderLoader.load(configuration, "scoreboard.start.", file);
HologramConfig hologramConfig = hologramConfigLoader.load(configuration, "hologram.", file);
DiscordWebhookConfig discordWebhookConfig = new DiscordWebhookConfig(configuration);
return new ZKoth(this.plugin, fileName, kothType, name, captureSeconds, minLocation, maxLocation, startCommands, endCommands, cooldownScoreboard,
startScoreboard, cooldownStart, stopAfterSeconds, enableStartCapMessage, enableLooseCapMessage, enableEverySecondsCapMessage, hologramConfig);
startScoreboard, cooldownStart, stopAfterSeconds, enableStartCapMessage, enableLooseCapMessage, enableEverySecondsCapMessage, hologramConfig, discordWebhookConfig);
}
@Override

View File

@ -97,4 +97,39 @@ hologram:
world: world
x: 0
y: 0
z: 0
z: 0
webhook:
enable: true
url: "https://discord.com/api/webhooks/1187068418923438190/eHBOLr52d7S28rcMqtNAdHbCi-9Gpk1tG0IU1ulbf3p6z9IbM2UqoSl9MxRT1TdX5k-W"
# Available event:
# - SPAWN
# - START
# - STOP
# - START_CAP
# - WIN
# - LOOSE
events:
START:
event: START
title: 'Start Koth'
description: "Koth %name% has been started !"
# url: "<your url>"
color:
r: 40
g: 240
b: 40
footer:
text: zKoth
iconUrl: https://groupez.dev/storage/images/9.png
# thumbnail: "<your thumbnail>"
# image: "<your image>
# author:
# name: "Maxlego08"
# url: ""
# iconUrl: ""
# fields:
# - name: Info
# value: "A new koth"
# inline: false