SteamWar/BungeeCore
Archiviert
13
2

Message deprecation, Discord refactoring
Alle Prüfungen waren erfolgreich
SteamWarCI Build successful

Signed-off-by: Lixfel <git-5w3l@lixfel.de>
Dieser Commit ist enthalten in:
Lixfel 2024-06-15 12:16:18 +02:00
Ursprung a188ce2c6f
Commit c39e2a0566
100 geänderte Dateien mit 1806 neuen und 2907 gelöschten Zeilen

Datei anzeigen

@ -19,6 +19,7 @@
package de.steamwar.bungeecore;
import de.steamwar.messages.Chatter;
import net.md_5.bungee.api.ProxyServer;
import java.util.concurrent.TimeUnit;
@ -28,10 +29,10 @@ class Broadcaster {
private static String [] broadCastMsgs;
private int lastBroadCast = 0;
Broadcaster(){
Broadcaster() {
ProxyServer.getInstance().getScheduler().schedule(BungeeCore.get(), () -> {
if(!ProxyServer.getInstance().getPlayers().isEmpty() && broadCastMsgs.length > 0)
BungeeCore.broadcast(BungeeCore.CHAT_PREFIX + broadCastMsgs[lastBroadCast]);
Chatter.broadcast().system("PLAIN_STRING", broadCastMsgs[lastBroadCast]);
lastBroadCast++;
if(lastBroadCast == broadCastMsgs.length){
lastBroadCast = 0;

Datei anzeigen

@ -19,29 +19,23 @@
package de.steamwar.bungeecore;
import de.steamwar.bungeecore.bot.SteamwarDiscordBot;
import de.steamwar.bungeecore.bot.config.SteamwarDiscordBotConfig;
import de.steamwar.bungeecore.commands.*;
import de.steamwar.bungeecore.discord.DiscordBot;
import de.steamwar.bungeecore.discord.config.DiscordConfig;
import de.steamwar.bungeecore.listeners.*;
import de.steamwar.bungeecore.mods.ServerListPing;
import de.steamwar.bungeecore.mods.*;
import de.steamwar.bungeecore.network.BungeeNetworkHandler;
import de.steamwar.bungeecore.network.handlers.*;
import de.steamwar.bungeecore.tablist.TablistManager;
import de.steamwar.command.*;
import de.steamwar.messages.Chatter;
import de.steamwar.network.packets.PacketHandler;
import de.steamwar.sql.Punishment;
import de.steamwar.sql.SteamwarUser;
import de.steamwar.sql.Team;
import de.steamwar.sql.UserElo;
import de.steamwar.sql.internal.Statement;
import net.md_5.bungee.api.ChatMessageType;
import net.md_5.bungee.api.CommandSender;
import lombok.Getter;
import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.chat.ClickEvent;
import net.md_5.bungee.api.chat.HoverEvent;
import net.md_5.bungee.api.chat.TextComponent;
import net.md_5.bungee.api.config.ServerInfo;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import net.md_5.bungee.api.plugin.Plugin;
import net.md_5.bungee.config.Configuration;
import net.md_5.bungee.config.ConfigurationProvider;
@ -58,18 +52,19 @@ import java.util.logging.Level;
public class BungeeCore extends Plugin {
public static boolean MAIN_SERVER;
@Deprecated
public static String CHAT_PREFIX;
public static String LOBBY_SERVER;
public static boolean EVENT_MODE;
public static String LOBBY_SERVER;
private static BungeeCore instance;
public static Node local;
private ErrorLogger errorLogger;
private TablistManager tablistManager;
@Getter
private TeamCommand teamCommand;
@Override
public void onEnable(){
setInstance(this);
@ -120,7 +115,7 @@ public class BungeeCore extends Plugin {
new JoinmeCommand();
new TpCommand();
HelpCommand helpCommand = new HelpCommand();
new TeamCommand();
teamCommand = new TeamCommand();
new ServerTeamchatCommand();
new DevCommand();
new EventCommand();
@ -129,7 +124,7 @@ public class BungeeCore extends Plugin {
new PollCommand();
new BugCommand();
new WhoisCommand();
new RegelnCommand();
new RulesCommand();
new IgnoreCommand();
new UnIgnoreCommand();
new PollresultCommand();
@ -143,6 +138,7 @@ public class BungeeCore extends Plugin {
new LocalCommand();
new SetLocaleCommand();
new BuilderCloudCommand();
new CheckCommand();
new ModCommand();
@ -163,7 +159,6 @@ public class BungeeCore extends Plugin {
new FightCommand();
new ChallengeCommand();
new HistoricCommand();
new CheckCommand();
new ReplayCommand();
new TutorialCommand();
@ -172,9 +167,14 @@ public class BungeeCore extends Plugin {
new EventModeListener();
}
for(PacketHandler handler : new PacketHandler[] {
new EloPlayerHandler(), new EloSchemHandler(), new ExecuteCommandHandler(), new FightInfoHandler(),
new ImALobbyHandler(), new InventoryCallbackHandler(), new PrepareSchemHandler()
})
handler.register();
new EventStarter();
new SessionManager();
BungeeNetworkHandler.register();
tablistManager = new TablistManager();
new SettingsChangedListener();
@ -184,9 +184,9 @@ public class BungeeCore extends Plugin {
Team.clear();
}, 1, 1, TimeUnit.HOURS);
if (SteamwarDiscordBotConfig.loaded) {
if (DiscordConfig.loaded) {
try {
new SteamwarDiscordBot();
new DiscordBot();
} catch (Throwable e) {
getLogger().log(Level.SEVERE, "Could not initialize discord bot", e);
}
@ -195,13 +195,11 @@ public class BungeeCore extends Plugin {
@Override
public void onDisable(){
if (SteamwarDiscordBotConfig.loaded) {
try {
SteamwarDiscordBot.instance().getJda().shutdown();
DiscordBot.withBot(bot -> bot.getJda().shutdown());
} catch (Throwable e) {
getLogger().log(Level.SEVERE, "Could not shutdown discord bot", e);
}
}
if(tablistManager != null)
tablistManager.disable();
@ -213,73 +211,6 @@ public class BungeeCore extends Plugin {
return instance;
}
@Deprecated
public static TextComponent stringToText(String msg){
return new TextComponent(TextComponent.fromLegacyText(msg));
}
@Deprecated
public static void send(ProxiedPlayer player, String msg){
send(player, msg, null, null);
}
@Deprecated
public static void send(CommandSender sender, String msg){
sender.sendMessage(stringToText(msg));
}
@Deprecated
public static void send(ProxiedPlayer player, ChatMessageType type, String msg){
send(player, type, msg, null, null);
}
@Deprecated
public static void send(ProxiedPlayer player, String msg, String onHover, ClickEvent onClick){
send(player, ChatMessageType.SYSTEM, msg, onHover, onClick);
}
@Deprecated
public static void send(ProxiedPlayer player, ChatMessageType type, String msg, String onHover, ClickEvent onClick){
if(type == ChatMessageType.CHAT && player.getChatMode() != ProxiedPlayer.ChatMode.SHOWN)
return;
TextComponent message = stringToText(msg);
if(onHover != null)
message.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, TextComponent.fromLegacyText(onHover)));
if(onClick != null)
message.setClickEvent(onClick);
player.sendMessage(type, message);
}
@Deprecated
public static void broadcast(String msg){
ProxyServer.getInstance().broadcast(stringToText(msg));
}
@Deprecated
public static void broadcast(String msg, String onHover, ClickEvent onClick){
TextComponent message = stringToText(msg);
if(onHover != null)
message.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, TextComponent.fromLegacyText(onHover)));
if(onClick != null)
message.setClickEvent(onClick);
ProxyServer.getInstance().broadcast(message);
}
@Deprecated
public static void log(final ServerInfo server, final String msg){
log(server.getName() + ": " + msg);
}
@Deprecated
public static void log(final ProxiedPlayer player, final String msg){
log(player.getName() + ": " + msg);
}
@Deprecated
public static void log(final String msg){
log(Level.INFO, msg);
}
@Deprecated
public static void log(final Level logLevel, final String msg){
get().getLogger().log(logLevel, msg);
}
@Deprecated
public static void log(final String msg, final Throwable e){
get().getLogger().log(Level.SEVERE, msg, e);
}
private static void loadConfig(){
Configuration config;
try{
@ -296,12 +227,11 @@ public class BungeeCore extends Plugin {
}
config = ConfigurationProvider.getProvider(YamlConfiguration.class).load(configFile);
}catch(Exception e){
log("Could not save/load config.yml", e);
get().getLogger().log(Level.SEVERE, "Could not save/load config.yml", e);
ProxyServer.getInstance().stop();
return;
}
CHAT_PREFIX = config.getString("prefix");
LOBBY_SERVER = config.getString("lobbyserver");
EVENT_MODE = config.getBoolean("eventmode");
Broadcaster.setBroadCastMsgs(config.getStringList("broadcasts").toArray(new String[1]));
@ -322,15 +252,6 @@ public class BungeeCore extends Plugin {
cmds.toArray(new String[0])
);
}
File discordFile = new File(System.getProperty("user.home"), "discord.yml");
if(discordFile.exists() && !EVENT_MODE) {
try {
SteamwarDiscordBotConfig.loadConfig(ConfigurationProvider.getProvider(YamlConfiguration.class).load(discordFile));
} catch (IOException e) {
get().getLogger().log(Level.SEVERE, "Could not load discord bot configuration", e);
}
}
}
private static void setInstance(BungeeCore core){

Datei anzeigen

@ -1,118 +0,0 @@
/*
This file is a part of the SteamWar software.
Copyright (C) 2020 SteamWar.de-Serverteam
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bungeecore;
import de.steamwar.messages.Chatter;
import de.steamwar.messages.SteamwarResourceBundle;
import net.md_5.bungee.api.ChatMessageType;
import net.md_5.bungee.api.CommandSender;
import net.md_5.bungee.api.chat.ClickEvent;
import java.text.DateFormat;
import java.text.MessageFormat;
import java.util.Date;
import java.util.Locale;
import java.util.ResourceBundle;
public class Message {
@Deprecated
public static String parse(String message, CommandSender sender, Object... params){
return parse(message, false, locale(sender), params);
}
@Deprecated
public static String parse(String message, Locale locale, Object... params){
return parse(message, false, locale, params);
}
@Deprecated
private static Locale locale(CommandSender sender) {
return Chatter.of(sender).getLocale();
}
@Deprecated
private static String parse(String message, boolean prefixed, Locale locale, Object... params){
if(locale == null)
locale = Locale.getDefault();
ResourceBundle resourceBundle = SteamwarResourceBundle.getResourceBundle(locale);
String pattern = "";
if(prefixed)
pattern = resourceBundle.getObject("PREFIX") + " ";
pattern += (String)resourceBundle.getObject(message);
MessageFormat format = new MessageFormat(pattern, locale);
for (int i = 0; i < params.length; i++) {
if(params[i] instanceof Message) {
Message msg = (Message) params[i];
params[i] = parse(msg.getFormat(), false, locale, msg.getParams());
} else if(params[i] instanceof Date) {
params[i] = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, locale).format((Date) params[i]);
}
}
return format.format(params);
}
@Deprecated
public static void send(String message, CommandSender sender, Object... params){
send(message, true, sender, ChatMessageType.SYSTEM, null, null, params);
}
@Deprecated
public static void sendPrefixless(String message, CommandSender sender, Object... params){
send(message, false, sender, ChatMessageType.SYSTEM, null, null, params);
}
@Deprecated
public static void send(String message, CommandSender sender, String onHover, ClickEvent onClick, Object... params){
send(message, true, sender, ChatMessageType.SYSTEM, onHover, onClick, params);
}
@Deprecated
public static void sendPrefixless(String message, CommandSender sender, String onHover, ClickEvent onClick, Object... params){
send(message, false, sender, ChatMessageType.SYSTEM, onHover, onClick, params);
}
@Deprecated
private static void send(String message, boolean prefixed, CommandSender s, ChatMessageType type, String onHover, ClickEvent onClick, Object... params){
Chatter sender = Chatter.of(s);
if(type == ChatMessageType.CHAT && !sender.chatShown())
return;
sender.send(prefixed, type, onHover != null ? new Message("PLAIN_STRING", onHover) : null, onClick, new Message(message, params));
}
private final String format;
private final Object[] params;
public Message(String format, Object... params) {
this.format = format;
this.params = params;
}
public String getFormat() {
return format;
}
public Object[] getParams() {
return params;
}
}

Datei anzeigen

@ -22,10 +22,10 @@ package de.steamwar.bungeecore;
import de.steamwar.bungeecore.network.NetworkSender;
import de.steamwar.bungeecore.network.handlers.FightInfoHandler;
import de.steamwar.messages.Chatter;
import de.steamwar.messages.Message;
import de.steamwar.network.packets.server.StartingServerPacket;
import de.steamwar.sql.IgnoreSystem;
import de.steamwar.sql.SteamwarUser;
import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.chat.ClickEvent;
import net.md_5.bungee.api.connection.ProxiedPlayer;
@ -38,22 +38,20 @@ public class SubserverSystem {
node.execute("rm", "-r", worldName);
}
public static void sendDeniedMessage(Chatter p, UUID owner){
ProxiedPlayer o = ProxyServer.getInstance().getPlayer(owner);
if(o == null)
return;
public static void sendDeniedMessage(Chatter p, UUID owner) {
if(IgnoreSystem.isIgnored(owner, p.user().getUUID())){
p.system("SERVER_IGNORED");
return;
}
Message.send("SERVER_ADD_MEMBER", o, p);
Message.sendPrefixless("SERVER_ADD_MESSAGE", o, "SERVER_ADD_MESSAGE_HOVER", new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/bau addmember " + p.user().getUserName()));
Chatter o = Chatter.of(owner);
o.system("SERVER_ADD_MEMBER", p);
o.prefixless("SERVER_ADD_MESSAGE", new Message("SERVER_ADD_MESSAGE_HOVER"), new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/bau addmember " + p.user().getUserName()));
}
public static void sendPlayer(Subserver subserver, ProxiedPlayer player) {
subserver.sendPlayer(player);
if(!subserver.hasStarted() && FightInfoHandler.onLobby(player))
if(!subserver.isStarted() && FightInfoHandler.onLobby(player))
NetworkSender.send(player, new StartingServerPacket(SteamwarUser.get(player.getUniqueId()).getId()));
}
}

Datei anzeigen

@ -1,81 +0,0 @@
/*
This file is a part of the SteamWar software.
Copyright (C) 2020 SteamWar.de-Serverteam
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bungeecore.bot;
import de.steamwar.bungeecore.BungeeCore;
import de.steamwar.bungeecore.bot.config.SteamwarDiscordBotConfig;
import de.steamwar.sql.SteamwarUser;
import net.dv8tion.jda.api.MessageBuilder;
import net.dv8tion.jda.api.entities.Emoji;
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.interactions.components.ActionRow;
import net.dv8tion.jda.api.interactions.components.Button;
import java.util.*;
import java.util.concurrent.TimeUnit;
public class AuthManager {
private static final Map<String, Long> TOKENS = new HashMap<>();
private static final Random rand = new Random();
public static String createDiscordAuthToken(Member member) {
if(TOKENS.containsValue(member.getIdLong())) return null;
byte[] randBytes = new byte[16];
rand.nextBytes(randBytes);
randBytes[0] = 'D';
randBytes[1] = 'C';
String code = Base64.getEncoder().encodeToString(randBytes);
TOKENS.put(code, member.getIdLong());
BungeeCore.log("Created Discord Auth-Token: " + code + " for: " + member.getUser().getAsTag());
BungeeCore.get().getProxy().getScheduler().schedule(BungeeCore.get(), () -> TOKENS.remove(code), 10, TimeUnit.MINUTES);
return code;
}
public static Member connectAuth(SteamwarUser user, String code) {
if (TOKENS.containsKey(code)) {
Member member = SteamwarDiscordBot.instance().getJda().getGuildById(SteamwarDiscordBotConfig.GUILD).retrieveMemberById(TOKENS.get(code).longValue()).complete();
if(member == null) return null;
user.setDiscordId(member.getIdLong());
MessageBuilder builder = new MessageBuilder();
builder.setContent(":white_check_mark: Dein Discord Konto wurde mit **" + user.getUserName() + "** verknüpft");
builder.setActionRows(ActionRow.of(Button.success("tada", Emoji.fromUnicode("U+1F389")), Button.danger("invalid", "Ich war das nicht")));
try {
member.getUser().openPrivateChannel().queue(privateChannel -> privateChannel.sendMessage(builder.build()).queue());
if (member.getNickname() == null) {
try {
member.getGuild().modifyNickname(member, user.getUserName()).queue();
} catch (Exception e) {
// Ignored
}
}
TOKENS.remove(code);
return member;
} catch (Exception e) {
return null;
}
} else {
return null;
}
}
}

Datei anzeigen

@ -1,166 +0,0 @@
/*
This file is a part of the SteamWar software.
Copyright (C) 2020 SteamWar.de-Serverteam
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bungeecore.bot;
import de.steamwar.bungeecore.BungeeCore;
import de.steamwar.bungeecore.bot.commands.*;
import de.steamwar.bungeecore.bot.config.SteamwarDiscordBotConfig;
import de.steamwar.bungeecore.bot.events.EventManager;
import de.steamwar.bungeecore.bot.events.SchematicsManager;
import de.steamwar.bungeecore.bot.listeners.*;
import de.steamwar.bungeecore.bot.util.DiscordRolesMessage;
import de.steamwar.bungeecore.bot.util.DiscordRulesMessage;
import de.steamwar.bungeecore.bot.util.DiscordTicketMessage;
import de.steamwar.messages.Chatter;
import de.steamwar.sql.Event;
import lombok.Getter;
import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.JDABuilder;
import net.dv8tion.jda.api.OnlineStatus;
import net.dv8tion.jda.api.entities.Activity;
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.exceptions.ErrorResponseException;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
import net.dv8tion.jda.api.requests.restaction.CommandListUpdateAction;
import net.dv8tion.jda.api.utils.MemberCachePolicy;
import net.md_5.bungee.api.ProxyServer;
import javax.security.auth.login.LoginException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
public class SteamwarDiscordBot {
private static SteamwarDiscordBot INSTANCE;
public static SteamwarDiscordBot instance() {
return INSTANCE;
}
@Getter
private volatile AnnouncementListener announcementListener;
@Getter
private volatile DiscordChatListener ingameChatListener;
@Getter
private volatile DiscordChatListener serverTeamChatListener;
@Getter
private final JDA jda;
@Getter
private static Map<String, BasicDiscordCommand> discordCommandMap = new HashMap<>();
public SteamwarDiscordBot() {
INSTANCE = this;
JDABuilder builder = JDABuilder.createDefault(SteamwarDiscordBotConfig.TOKEN);
builder.setStatus(OnlineStatus.ONLINE);
builder.setMemberCachePolicy(MemberCachePolicy.ONLINE);
try {
jda = builder.build();
} catch (LoginException e) {
throw new SecurityException("Could not Login: " + SteamwarDiscordBotConfig.TOKEN, e);
}
ProxyServer.getInstance().getScheduler().runAsync(BungeeCore.get(), () -> {
try {
jda.awaitReady();
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
activity();
} catch (Exception e) {
BungeeCore.get().getLogger().log(Level.SEVERE, "Could not set initial activity to discord", e);
}
EventManager.update();
SchematicsManager.update();
ProxyServer.getInstance().getScheduler().schedule(BungeeCore.get(), () -> {
try {
activity();
EventManager.update();
SchematicsManager.update();
} catch (ErrorResponseException e) {
//ignored
}
}, 30, 30, TimeUnit.SECONDS);
DiscordRolesMessage.sendMessage();
DiscordRulesMessage.sendMessage();
DiscordTicketMessage.sendMessage();
new RolesInteractionButtonListener();
new DiscordTicketListener();
new DiscordAuthListener();
new DiscordEventListener();
new PrivateMessageListener();
announcementListener = new AnnouncementListener();
ingameChatListener = new DiscordChatListener(SteamwarDiscordBotConfig.INGAME_CHANNEL, "CHAT_DISCORD_GLOBAL", Chatter::broadcast);
serverTeamChatListener = new DiscordChatListener(SteamwarDiscordBotConfig.SERVER_TEAM_CHANNEL, "CHAT_SERVERTEAM", Chatter::serverteam);
new SlashCommandListener();
jda.retrieveCommands().complete().forEach(command -> jda.deleteCommandById(command.getId()).queue());
Guild guild = jda.getGuildById(SteamwarDiscordBotConfig.GUILD);
guild.retrieveCommands().complete().forEach(command -> guild.deleteCommandById(command.getId()).complete());
CommandListUpdateAction commands = jda.getGuildById(SteamwarDiscordBotConfig.GUILD).updateCommands();
addCommand(commands, new MuteCommand());
addCommand(commands, new BanCommand());
addCommand(commands, new WhoisCommand());
addCommand(commands, new TeamCommand());
addCommand(commands, new ListCommand());
addCommand(commands, new UnbanCommand());
commands.complete();
});
}
private void addCommand(CommandListUpdateAction commands, BasicDiscordCommand basicDiscordCommand) {
commands.addCommands(basicDiscordCommand);
discordCommandMap.put(basicDiscordCommand.getName(), basicDiscordCommand);
}
private int index = 0;
private void activity() {
switch (index) {
case 0:
Event event = Event.get();
if (event != null) {
jda.getPresence().setActivity(Activity.competing("dem Event " + event.getEventName()));
} else {
jda.getPresence().setActivity(Activity.playing("auf SteamWar.de"));
}
break;
case 1:
int count = BungeeCore.get().getProxy().getOnlineCount();
if (count == 1) {
jda.getPresence().setActivity(Activity.playing("mit 1 Spieler"));
} else {
jda.getPresence().setActivity(Activity.playing("mit " + count + " Spielern"));
}
index = 0;
return;
}
index++;
}
public void addListener(ListenerAdapter listenerAdapter) {
jda.addEventListener(listenerAdapter);
}
}

Datei anzeigen

@ -1,67 +0,0 @@
/*
* This file is a part of the SteamWar software.
*
* Copyright (C) 2020 SteamWar.de-Serverteam
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bungeecore.bot.commands;
import de.steamwar.bungeecore.Message;
import de.steamwar.bungeecore.commands.PunishmentCommand;
import de.steamwar.messages.Chatter;
import de.steamwar.sql.SteamwarUser;
import net.dv8tion.jda.api.events.interaction.SlashCommandEvent;
import net.dv8tion.jda.api.interactions.commands.OptionType;
import java.sql.Timestamp;
public class BanCommand extends BasicDiscordCommand {
public BanCommand() {
super("ban", "Banne einen Nutzer, wenn du die Rechte hast.");
addOption(OptionType.STRING, "user", "Der Benutzer", true);
addOption(OptionType.STRING, "time", "Bis Wann", true);
addOption(OptionType.STRING, "reason", "Warum", true);
}
@Override
public void run(SlashCommandEvent event) {
if (!testPermission(event)) {
return;
}
SteamwarUser sender = SteamwarUser.get(event.getMember().getIdLong());
SteamwarUser target = PunishmentCommand.getOrCreateOfflinePlayer(event.getOption("user").getAsString());
if (target == null) {
event.reply("Angegebener User invalide").setEphemeral(true).queue();
return;
}
Timestamp time = PunishmentCommand.parseTime(null, event.getOption("time").getAsString());
if (time == null) {
event.reply("Angegebene Zeit invalide").setEphemeral(true).queue();
return;
}
String msg = event.getOption("reason").getAsString();
boolean isPerma = event.getOption("time").getAsString().equals("perma");
PunishmentCommand.ban(target, time, msg, sender, isPerma);
Chatter.serverteam().system("BAN_TEAM", new Message("PREFIX"), target.getUserName(), sender.getUserName(), new Message((isPerma ? "BAN_PERMA" : "BAN_UNTIL"), time), msg);
event.reply("Erfolgreich " + target.getUserName() + (isPerma ? " permanent" : " bis " + time) + " gebannt").setEphemeral(true).queue();
}
}

Datei anzeigen

@ -1,54 +0,0 @@
/*
* This file is a part of the SteamWar software.
*
* Copyright (C) 2020 SteamWar.de-Serverteam
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bungeecore.bot.commands;
import de.steamwar.sql.SteamwarUser;
import de.steamwar.sql.UserPerm;
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.events.interaction.SlashCommandEvent;
import net.dv8tion.jda.api.interactions.commands.build.CommandData;
public abstract class BasicDiscordCommand extends CommandData {
protected BasicDiscordCommand(String name, String description) {
super(name, description);
}
public abstract void run(SlashCommandEvent event);
protected SteamwarUser getSteamwarUser(SlashCommandEvent event) {
Member member = event.getMember();
SteamwarUser steamwarUser = SteamwarUser.get(member.getIdLong());
if (steamwarUser == null) {
return null;
}
return steamwarUser;
}
protected boolean testPermission(SlashCommandEvent event) {
Member member = event.getMember();
SteamwarUser steamwarUser = SteamwarUser.get(member.getIdLong());
if (steamwarUser == null || (!steamwarUser.hasPerm(UserPerm.TEAM))) {
event.reply("Du hast für " + event.getName() + " keine Rechte oder es existiert keine Verknüpfung für dich.").setEphemeral(true).queue();
return false;
}
return true;
}
}

Datei anzeigen

@ -1,43 +0,0 @@
/*
* This file is a part of the SteamWar software.
*
* Copyright (C) 2020 SteamWar.de-Serverteam
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bungeecore.bot.commands;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.events.interaction.SlashCommandEvent;
import java.util.stream.Collectors;
public class ListCommand extends BasicDiscordCommand {
public ListCommand() {
super("list", "Gebe eine Liste aller online Spieler");
}
@Override
public void run(SlashCommandEvent event) {
de.steamwar.bungeecore.commands.ListCommand.getCustomTablist();
EmbedBuilder embedBuilder = new EmbedBuilder();
embedBuilder.setTitle("List");
de.steamwar.bungeecore.commands.ListCommand.getCustomTablist().forEach((s, proxiedPlayers) -> {
embedBuilder.addField(s, proxiedPlayers.stream().map(player -> "`" + player.getName() + "`").collect(Collectors.joining(", ")), true);
});
event.replyEmbeds(embedBuilder.build()).setEphemeral(true).queue();
}
}

Datei anzeigen

@ -1,68 +0,0 @@
/*
* This file is a part of the SteamWar software.
*
* Copyright (C) 2020 SteamWar.de-Serverteam
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bungeecore.bot.commands;
import de.steamwar.bungeecore.Message;
import de.steamwar.bungeecore.commands.PunishmentCommand;
import de.steamwar.messages.Chatter;
import de.steamwar.sql.Punishment;
import de.steamwar.sql.SteamwarUser;
import net.dv8tion.jda.api.events.interaction.SlashCommandEvent;
import net.dv8tion.jda.api.interactions.commands.OptionType;
import java.sql.Timestamp;
public class MuteCommand extends BasicDiscordCommand {
public MuteCommand() {
super("mute", "Mute einen Nutzer, wenn du die Rechte hast.");
addOption(OptionType.STRING, "user", "Der Benutzer", true);
addOption(OptionType.STRING, "time", "Bis Wann", true);
addOption(OptionType.STRING, "reason", "Warum", true);
}
@Override
public void run(SlashCommandEvent event) {
if (!testPermission(event)) {
return;
}
SteamwarUser sender = SteamwarUser.get(event.getMember().getIdLong());
SteamwarUser target = PunishmentCommand.getOrCreateOfflinePlayer(event.getOption("user").getAsString());
if (target == null) {
event.reply("Angegebener User invalide").setEphemeral(true).complete();
return;
}
Timestamp time = PunishmentCommand.parseTime(null, event.getOption("time").getAsString());
if (time == null) {
event.reply("Angegebene Zeit invalide").setEphemeral(true).complete();
return;
}
String msg = event.getOption("reason").getAsString();
boolean isPerma = event.getOption("time").getAsString().equals("perma");
target.punish(Punishment.PunishmentType.Mute, time, msg, sender.getId(), isPerma);
Chatter.serverteam().system("MUTE_TEAM", new Message("PREFIX"), target.getUserName(), sender.getUserName(), new Message((isPerma ? "BAN_PERMA" : "BAN_UNTIL"), time), msg);
event.reply("Erfolgreich " + target.getUserName() + (isPerma ? " permanent" : " bis " + time) + " gemutet").setEphemeral(true).queue();
}
}

Datei anzeigen

@ -1,96 +0,0 @@
/*
* This file is a part of the SteamWar software.
*
* Copyright (C) 2020 SteamWar.de-Serverteam
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bungeecore.bot.commands;
import de.steamwar.sql.Event;
import de.steamwar.sql.SteamwarUser;
import de.steamwar.sql.Team;
import de.steamwar.sql.TeamTeilnahme;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.entities.Emoji;
import net.dv8tion.jda.api.events.interaction.SlashCommandEvent;
import net.dv8tion.jda.api.interactions.commands.OptionMapping;
import net.dv8tion.jda.api.interactions.commands.OptionType;
import net.dv8tion.jda.api.interactions.commands.build.SubcommandData;
import net.md_5.bungee.api.ProxyServer;
import java.awt.*;
import java.util.List;
import java.util.stream.Collectors;
public class TeamCommand extends BasicDiscordCommand {
public TeamCommand() {
super("team", "Alle Team bezogenen Befehle");
addSubcommands(new SubcommandData("info", "Infos über das Team oder deins")
.addOption(OptionType.STRING, "team", "Name oder Kuerzel", false)
);
}
private Emoji emoji = Emoji.fromUnicode("U+1F7E2");
@Override
public void run(SlashCommandEvent event) {
SteamwarUser steamwarUser = getSteamwarUser(event);
if (event.getSubcommandName() != null) {
switch (event.getSubcommandName()) {
case "info":
OptionMapping optionMapping = event.getOption("team");
Team team;
if (optionMapping == null) {
if (steamwarUser == null) {
event.reply("Dein Discord ist nicht verknüpft").setEphemeral(true).queue();
return;
}
if (steamwarUser.getTeam() == 0) {
event.reply("Du bist in keinem Team").setEphemeral(true).queue();
return;
}
team = Team.get(steamwarUser.getTeam());
} else {
team = Team.get(optionMapping.getAsString());
}
if (team == null) {
event.reply("Unbekanntes Team").setEphemeral(true).queue();
return;
}
EmbedBuilder embedBuilder = new EmbedBuilder();
embedBuilder.setTitle("Team: " + team.getTeamName() + " [" + team.getTeamKuerzel() + "]");
embedBuilder.setColor(Color.GRAY);
List<SteamwarUser> members = team.getMembers().stream().map(SteamwarUser::get).collect(Collectors.toList());
embedBuilder.addField("Leader", members.stream().filter(SteamwarUser::isLeader).map(user -> "`" + (isOnline(user) ? emoji.getAsMention() : "") + user.getUserName() + "`").collect(Collectors.joining(" ")), false);
embedBuilder.addField("Member", members.stream().filter(user -> !user.isLeader()).map(user -> "`" + (isOnline(user) ? emoji.getAsMention() : "") + user.getUserName() + "`").collect(Collectors.joining(" ")), false);
embedBuilder.addField("Events", "`" + TeamTeilnahme.getEvents(team.getTeamId()).stream().map(Event::getEventName).collect(Collectors.joining("` `")) + "`", false);
event.replyEmbeds(embedBuilder.build()).setEphemeral(true).queue();
return;
default:
event.reply("Unbekannter Befehl").setEphemeral(true).queue();
return;
}
}
}
private boolean isOnline(SteamwarUser user) {
return ProxyServer.getInstance().getPlayer(user.getUUID()) != null;
}
}

Datei anzeigen

@ -1,62 +0,0 @@
/*
* This file is a part of the SteamWar software.
*
* Copyright (C) 2020 SteamWar.de-Serverteam
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bungeecore.bot.commands;
import de.steamwar.bungeecore.commands.PunishmentCommand;
import de.steamwar.sql.BannedUserIPs;
import de.steamwar.sql.Punishment;
import de.steamwar.sql.SteamwarUser;
import net.dv8tion.jda.api.events.interaction.SlashCommandEvent;
import net.dv8tion.jda.api.interactions.commands.OptionType;
import java.sql.Timestamp;
import java.util.Date;
public class UnbanCommand extends BasicDiscordCommand {
public UnbanCommand() {
super("unban", "Entbannt einen Nutzer, wenn du die Rechte hast.");
addOption(OptionType.STRING, "user", "Der Benutzer", true);
}
@Override
public void run(SlashCommandEvent event) {
if (!testPermission(event)) {
return;
}
SteamwarUser sender = SteamwarUser.get(event.getMember().getIdLong());
SteamwarUser target = PunishmentCommand.getOrCreateOfflinePlayer(event.getOption("user").getAsString());
if (target == null) {
event.reply("Angegebener User invalide").setEphemeral(true).queue();
return;
}
if (!target.isPunished(Punishment.PunishmentType.Ban)) {
event.reply("Angegebener User ist nicht gebannt").setEphemeral(true).queue();
return;
}
target.punish(Punishment.PunishmentType.Ban, Timestamp.from(new Date().toInstant()), "Unban", sender.getId(), false);
BannedUserIPs.unbanIPs(target.getId());
event.reply("Erfolgreich " + target.getUserName() + " entbannt").setEphemeral(true).queue();
}
}

Datei anzeigen

@ -1,94 +0,0 @@
/*
* This file is a part of the SteamWar software.
*
* Copyright (C) 2020 SteamWar.de-Serverteam
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bungeecore.bot.commands;
import de.steamwar.sql.Punishment;
import de.steamwar.sql.SteamwarUser;
import de.steamwar.sql.Team;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.events.interaction.SlashCommandEvent;
import net.dv8tion.jda.api.interactions.commands.OptionType;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.util.List;
public class WhoisCommand extends BasicDiscordCommand {
public WhoisCommand() {
super("whois", "Der whois Befehl");
addOption(OptionType.STRING, "user", "Der Benutzer", true);
}
@Override
public void run(SlashCommandEvent event) {
if (!testPermission(event)) {
return;
}
String s = event.getOption("user").getAsString();
SteamwarUser user = SteamwarUser.get(s);
if (user == null) {
try {
int id = Integer.parseInt(s);
user = SteamwarUser.get(id);
} catch (NumberFormatException ignored) {
// Ignored
}
}
if (user == null) {
try {
long id = Long.parseLong(s);
user = SteamwarUser.get(id);
} catch (NumberFormatException ignored) {
// Ignored
}
}
if (user == null) {
event.reply("Der angegebene Spieler ist unbekannt").setEphemeral(true).complete();
return;
}
EmbedBuilder embedBuilder = new EmbedBuilder();
embedBuilder.setTitle("Whois: " + user.getUserName());
StringBuilder st = new StringBuilder();
st.append("UUID: ").append(user.getUUID()).append("\n");
st.append("ID: ").append(user.getId()).append("\n");
if (user.getDiscordId() != null) {
st.append("DiscordID: ").append(user.getDiscordId()).append("\n");
}
Timestamp timestamp = user.getFirstjoin();
st.append("Beigetreten am: ").append(timestamp == null ? "0000-00-00 00:00:00" : timestamp.toString()).append("\n");
st.append("Online Time: ").append(new DecimalFormat("###.##").format(user.getOnlinetime() / (double) 3600)).append("h\n");
Team team = Team.get(user.getTeam());
st.append("Team: [").append(team.getTeamKuerzel()).append("] ").append(team.getTeamName());
embedBuilder.addField("Daten:", st.toString(), false);
List<Punishment> punishmentList = Punishment.getAllPunishmentsOfPlayer(user.getId());
for (Punishment punishment : punishmentList) {
embedBuilder.addField(punishment.getType().name() + " von " + SteamwarUser.get(punishment.getPunisher()).getUserName(), "Von: " + punishment.getBantime(punishment.getStartTime(), false) + "\nBis: " + punishment.getBantime(punishment.getEndTime(), punishment.isPerma()) + "\nGrund: " + punishment.getReason(), true);
}
event.replyEmbeds(embedBuilder.build()).setEphemeral(true).queue();
}
}

Datei anzeigen

@ -1,50 +0,0 @@
/*
* This file is a part of the SteamWar software.
*
* Copyright (C) 2020 SteamWar.de-Serverteam
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bungeecore.bot.listeners;
import de.steamwar.bungeecore.bot.SteamwarDiscordBot;
import de.steamwar.bungeecore.bot.config.SteamwarDiscordBotConfig;
import de.steamwar.messages.Chatter;
import net.dv8tion.jda.api.MessageBuilder;
import net.dv8tion.jda.api.entities.TextChannel;
import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent;
import org.jetbrains.annotations.NotNull;
public class AnnouncementListener extends BasicDiscordListener {
@Override
public void onGuildMessageReceived(@NotNull GuildMessageReceivedEvent event) {
if (!event.getChannel().getId().equals(SteamwarDiscordBotConfig.ANNOUNCEMENTS_CHANNEL)) {
return;
}
if (event.getAuthor().isBot()) {
return;
}
Chatter.broadcast().system("ALERT", event.getMessage().getContentDisplay());
}
public void announce(String message) {
TextChannel textChannel = SteamwarDiscordBot.instance().getJda().getGuildById(SteamwarDiscordBotConfig.GUILD).getTextChannelById(SteamwarDiscordBotConfig.ANNOUNCEMENTS_CHANNEL);
assert textChannel != null;
MessageBuilder messageBuilder = new MessageBuilder();
messageBuilder.append(message.replace("&", ""));
textChannel.sendMessage(messageBuilder.build()).queue();
}
}

Datei anzeigen

@ -1,30 +0,0 @@
/*
This file is a part of the SteamWar software.
Copyright (C) 2020 SteamWar.de-Serverteam
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bungeecore.bot.listeners;
import de.steamwar.bungeecore.bot.SteamwarDiscordBot;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
public abstract class BasicDiscordListener extends ListenerAdapter {
BasicDiscordListener() {
SteamwarDiscordBot.instance().addListener(this);
}
}

Datei anzeigen

@ -1,59 +0,0 @@
/*
This file is a part of the SteamWar software.
Copyright (C) 2020 SteamWar.de-Serverteam
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bungeecore.bot.listeners;
import de.steamwar.bungeecore.bot.AuthManager;
import de.steamwar.bungeecore.bot.config.SteamwarDiscordBotConfig;
import de.steamwar.sql.SteamwarUser;
import net.dv8tion.jda.api.entities.ChannelType;
import net.dv8tion.jda.api.events.interaction.GenericComponentInteractionCreateEvent;
import net.dv8tion.jda.api.interactions.InteractionType;
import org.jetbrains.annotations.NotNull;
public class DiscordAuthListener extends BasicDiscordListener {
@Override
public void onGenericComponentInteractionCreate(@NotNull GenericComponentInteractionCreateEvent event) {
if(event.getType() == InteractionType.COMPONENT) {
if(event.getChannel().getId().equals(SteamwarDiscordBotConfig.RULES_CHANNEL) && event.getComponentId().equals("auth")) {
String authMessage = AuthManager.createDiscordAuthToken(event.getMember());
if(authMessage != null) {
event.reply("Gebe innerhalb der nächsten 10 Minuten ``/verify " + authMessage + "`` auf dem Minecraft Server ein").setEphemeral(true).queue();
} else {
event.reply("Du hast bereits einen Code am laufen").setEphemeral(true).queue();
}
}
if(event.getComponentId().equals("tada") && event.getChannelType() == ChannelType.PRIVATE) {
event.reply(":tada:").setEphemeral(false).queue();
}
if(event.getComponentId().equals("invalid") && event.getChannelType() == ChannelType.PRIVATE) {
SteamwarUser user = SteamwarUser.get(event.getUser().getIdLong());
if(user == null) {
event.reply(":question: Da ist keine verknüpfung?").setEphemeral(false).queue();
} else {
user.setDiscordId(null);
event.reply(":x: Die Verknüpfung wurde beendet").setEphemeral(false).queue();
}
}
}
}
}

Datei anzeigen

@ -1,71 +0,0 @@
/*
* This file is a part of the SteamWar software.
*
* Copyright (C) 2020 SteamWar.de-Serverteam
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bungeecore.bot.listeners;
import de.steamwar.bungeecore.bot.SteamwarDiscordBot;
import de.steamwar.bungeecore.bot.config.SteamwarDiscordBotConfig;
import de.steamwar.bungeecore.listeners.ChatListener;
import de.steamwar.messages.Chatter;
import de.steamwar.messages.ChatterGroup;
import de.steamwar.sql.Punishment;
import de.steamwar.sql.SteamwarUser;
import net.dv8tion.jda.api.MessageBuilder;
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.TextChannel;
import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent;
import org.jetbrains.annotations.NotNull;
import java.util.function.Supplier;
public class DiscordChatListener extends BasicDiscordListener {
private final String channel;
private final String format;
private final Supplier<ChatterGroup> targets;
public DiscordChatListener(String channel, String format, Supplier<ChatterGroup> targets) {
this.channel = channel;
this.format = format;
this.targets = targets;
}
@Override
public void onGuildMessageReceived(@NotNull GuildMessageReceivedEvent event) {
if (!event.getChannel().getId().equals(channel) || event.getAuthor().isBot())
return;
Member member = event.getMember();
SteamwarUser steamwarUser = SteamwarUser.get(member.getIdLong());
if (steamwarUser == null || event.getMessage().getContentRaw().length() > 250 || steamwarUser.isPunished(Punishment.PunishmentType.Ban)) {
event.getMessage().delete().queue();
} else {
ChatListener.sendChat(Chatter.of(event.getMessage(), steamwarUser), targets.get(), format, null, event.getMessage().getContentDisplay().replace('§', '&').replace('\n', ' '));
}
}
public void send(String message) {
TextChannel textChannel = SteamwarDiscordBot.instance().getJda().getGuildById(SteamwarDiscordBotConfig.GUILD).getTextChannelById(channel);
assert textChannel != null;
MessageBuilder messageBuilder = new MessageBuilder();
messageBuilder.append(message.replace("&", "").replace("@everyone", "`@everyone`").replace("@here", "`@here`").replaceAll("<[@#]!?\\d+>", "`$0`"));
textChannel.sendMessage(messageBuilder.build()).queue();
}
}

Datei anzeigen

@ -1,93 +0,0 @@
/*
This file is a part of the SteamWar software.
Copyright (C) 2020 SteamWar.de-Serverteam
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bungeecore.bot.listeners;
import de.steamwar.bungeecore.bot.config.SteamwarDiscordBotConfig;
import de.steamwar.bungeecore.bot.events.EventManager;
import de.steamwar.sql.SteamwarUser;
import de.steamwar.sql.Team;
import de.steamwar.sql.TeamTeilnahme;
import de.steamwar.sql.Event;
import net.dv8tion.jda.api.events.interaction.SelectionMenuEvent;
import net.dv8tion.jda.api.interactions.components.Component;
import org.jetbrains.annotations.NotNull;
import java.time.Instant;
public class DiscordEventListener extends BasicDiscordListener {
@Override
public void onSelectionMenu(@NotNull SelectionMenuEvent event) {
if(event.getChannel().getId().equals(SteamwarDiscordBotConfig.EVENTS_CHANNEL) && event.getComponentType() == Component.Type.SELECTION_MENU) {
if(event.getSelectedOptions().isEmpty()) {
event.deferReply(true).queue();
return;
}
if(event.getSelectedOptions().get(0).getValue().matches("([0-9]+)")) {
SteamwarUser user = SteamwarUser.get(event.getUser().getIdLong());
if(user == null) {
event.reply("Du hast dein Minecraft nicht verknüpft").setEphemeral(true).queue();
return;
}
if(user.getTeam() == 0) {
event.reply("Du bist in keinem Team").setEphemeral(true).queue();
return;
}
if(!user.isLeader()) {
event.reply("Du bist kein Leader in deinem Team").setEphemeral(true).queue();
return;
}
if(Event.get() != null) {
event.reply("Du kannst dich nicht während einem Event an einem Event anmelden").setEphemeral(true).queue();
return;
}
Event swEvent = Event.get(Integer.decode(event.getSelectedOptions().get(0).getValue()));
if(swEvent == null){
event.reply("Das Event gibt es nicht").setEphemeral(true).queue();
return;
}
if(Instant.now().isAfter(swEvent.getDeadline().toInstant())){
event.reply("Du kannst dich nicht mehr an diesen Event anmelden").setEphemeral(true).queue();
return;
}
Team team = Team.get(user.getTeam());
if(TeamTeilnahme.nimmtTeil(team.getTeamId(), swEvent.getEventID())){
TeamTeilnahme.notTeilnehmen(team.getTeamId(), swEvent.getEventID());
event.reply("Dein Team **" + team.getTeamName() + "** nimmt nun nicht mehr an **" + swEvent.getEventName() + "** teil!").setEphemeral(true).queue();
}else{
TeamTeilnahme.teilnehmen(team.getTeamId(), swEvent.getEventID());
event.reply("Dein Team **" + team.getTeamName() + "** nimmt nun an **" + swEvent.getEventName() + "** teil!").setEphemeral(true).queue();
}
EventManager.update();
} else {
event.reply("Lefuq?").setEphemeral(true).queue();
}
}
}
}

Datei anzeigen

@ -1,158 +0,0 @@
/*
This file is a part of the SteamWar software.
Copyright (C) 2020 SteamWar.de-Serverteam
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bungeecore.bot.listeners;
import de.steamwar.bungeecore.BungeeCore;
import de.steamwar.bungeecore.Message;
import de.steamwar.bungeecore.bot.config.DiscordTicketType;
import de.steamwar.bungeecore.bot.config.SteamwarDiscordBotConfig;
import de.steamwar.messages.Chatter;
import de.steamwar.sql.SteamwarUser;
import de.steamwar.sql.UserPerm;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.MessageBuilder;
import net.dv8tion.jda.api.Permission;
import net.dv8tion.jda.api.entities.*;
import net.dv8tion.jda.api.events.interaction.GenericComponentInteractionCreateEvent;
import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent;
import net.dv8tion.jda.api.interactions.InteractionType;
import net.dv8tion.jda.api.interactions.components.ActionRow;
import net.dv8tion.jda.api.interactions.components.Button;
import net.md_5.bungee.api.chat.ClickEvent;
import org.jetbrains.annotations.NotNull;
import java.awt.*;
import java.time.Instant;
import java.util.LinkedList;
public class DiscordTicketListener extends BasicDiscordListener {
@Override
public void onGenericComponentInteractionCreate(@NotNull GenericComponentInteractionCreateEvent event) {
if(event.getType() == InteractionType.COMPONENT && event.getChannelType() == ChannelType.TEXT && event.getTextChannel().getParent() != null && event.getTextChannel().getParent().getId().equals(SteamwarDiscordBotConfig.TICKET_CATEGORY)) {
if(event.getTextChannel().getId().equals(SteamwarDiscordBotConfig.TICKET_CHANNEL) && SteamwarDiscordBotConfig.TICKET_TYPES.containsKey(event.getComponentId())) {
DiscordTicketType ticketType = SteamwarDiscordBotConfig.TICKET_TYPES.get(event.getComponentId());
Category ct = event.getGuild().getCategoryById(SteamwarDiscordBotConfig.TICKET_CATEGORY);
SteamwarUser swUser = SteamwarUser.get(event.getUser().getIdLong());
TextChannel ticketChannel = ct.createTextChannel((swUser == null?event.getUser().getName():swUser.getUserName()) + "-" + event.getComponentId() + "-" + System.currentTimeMillis() % 1000).complete();
ticketChannel.createPermissionOverride(event.getMember()).setAllow(Permission.VIEW_CHANNEL,
Permission.MESSAGE_WRITE,
Permission.MESSAGE_ATTACH_FILES,
Permission.MESSAGE_ADD_REACTION,
Permission.MESSAGE_READ,
Permission.MESSAGE_EMBED_LINKS,
Permission.MESSAGE_HISTORY).complete();
ticketChannel.getManager().setTopic(event.getUser().getId()).complete();
MessageBuilder messageBuilder = new MessageBuilder();
EmbedBuilder builder = new EmbedBuilder();
builder.setDescription(ticketType.getPreMessage());
builder.setTitle("Steamwar Ticket");
builder.setColor(Color.GREEN);
Button closeButton = Button.danger("close-" + ticketChannel.getName(), "Schließen").withEmoji(Emoji.fromUnicode("U+26A0"));
messageBuilder.setEmbeds(builder.build());
messageBuilder.setActionRows(ActionRow.of(closeButton));
ticketChannel.sendMessage(messageBuilder.build()).complete();
event.reply(SteamwarDiscordBotConfig.TICKET_CREATED.replace("%channel%", ticketChannel.getAsMention())).setEphemeral(true).complete();
Chatter.serverteam().prefixless("DISCORD_TICKET_NEW", ticketChannel.getName());
} else if(event.getComponentId().startsWith("close-")) {
TextChannel logChannel = event.getGuild().getTextChannelById(SteamwarDiscordBotConfig.TICKET_LOG);
LinkedList<StringBuilder> stringBuilders = new LinkedList<>();
stringBuilders.add(new StringBuilder());
new LinkedList<>(event.getTextChannel().getIterableHistory().complete()).descendingIterator().forEachRemaining(message -> {
if(message.getAuthor().isSystem() || message.getAuthor().isBot()) return;
StringBuilder currentBuilder = new StringBuilder();
currentBuilder.append("<t:").append(message.getTimeCreated().toInstant().getEpochSecond()).append("> ")
.append("**")
.append(message.getAuthor().getName())
.append("**: ")
.append(message.getContentRaw());
if(!message.getAttachments().isEmpty()) {
currentBuilder.append("\n")
.append("Files: ").append("\n");
message.getAttachments().forEach(attachment -> currentBuilder.append(attachment.getUrl()).append("\n"));
}
currentBuilder.append("\n");
if(currentBuilder.length() >= 4096) {
stringBuilders.getLast().append(currentBuilder.substring(0, 4090));
stringBuilders.add(new StringBuilder(currentBuilder.substring(4090, currentBuilder.length() - 1)));
} else if (currentBuilder.length() + stringBuilders.getLast().length() >= 4096) {
stringBuilders.add(new StringBuilder(currentBuilder.toString()));
} else {
stringBuilders.getLast().append(currentBuilder);
}
});
String footer = "<t:" + Instant.now().getEpochSecond() + "> **" + event.getUser().getName() + "**: Ticket geschlossen";
if(stringBuilders.getLast().length() + footer.length() > 4090) {
stringBuilders.add(new StringBuilder(footer));
} else {
stringBuilders.getLast().append(footer);
}
EmbedBuilder embedBuilder = new EmbedBuilder();
embedBuilder.setColor(Color.GREEN);
User user = event.getJDA().retrieveUserById(event.getTextChannel().getTopic()).complete();
SteamwarUser swuser = SteamwarUser.get(user.getIdLong());
embedBuilder.setAuthor(user.getName(), swuser==null?"https://steamwar.de/":("https://steamwar.de/users/" + swuser.getUserName().toLowerCase() + "/"), user.getAvatarUrl());
embedBuilder.setTimestamp(Instant.now());
embedBuilder.setTitle(event.getTextChannel().getName());
stringBuilders.forEach(stringBuilder -> {
embedBuilder.setDescription(stringBuilder.toString());
MessageBuilder builder = new MessageBuilder();
builder.setEmbeds(embedBuilder.build());
logChannel.sendMessage(builder.build()).queue();
});
Chatter.serverteam().prefixless("DISCORD_TICKET_CLOSED", event.getTextChannel().getName());
event.getTextChannel().delete().reason("Closed").queue();
}
}
}
@Override
public void onGuildMessageReceived(@NotNull GuildMessageReceivedEvent event) {
if(event.getChannel().getParent() != null && event.getChannel().getParent().getId().equals(SteamwarDiscordBotConfig.TICKET_CATEGORY)) {
if(!event.getChannel().getId().equals(SteamwarDiscordBotConfig.TICKET_CHANNEL) && !event.getChannel().getId().equals(SteamwarDiscordBotConfig.TICKET_LOG)) {
BungeeCore.get().getProxy().getPlayers().forEach(player -> {
if(event.getAuthor().isBot() || event.getAuthor().isSystem()) return;
SteamwarUser user = SteamwarUser.get(player.getUniqueId());
boolean sendMessage;
if(user.getDiscordId() == null) {
sendMessage = user.hasPerm(UserPerm.CHECK);
} else {
if(event.getAuthor().getId().equals(user.getDiscordId())) return;
sendMessage = user.getDiscordId().equals(event.getChannel().getTopic()) || user.hasPerm(UserPerm.CHECK);
}
if(sendMessage) {
Message.sendPrefixless("DISCORD_TICKET_MESSAGE", player, "Zur nachricht", new ClickEvent(ClickEvent.Action.OPEN_URL, event.getMessage().getJumpUrl()), event.getChannel().getName(), event.getAuthor().getName(), event.getMessage().getContentRaw());
}
});
}
}
}
}

Datei anzeigen

@ -1,80 +0,0 @@
/*
* This file is a part of the SteamWar software.
* <p>
* Copyright (C) 2021 SteamWar.de-Serverteam
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* <p>
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
* <p>
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bungeecore.bot.listeners;
import de.steamwar.bungeecore.BungeeCore;
import de.steamwar.sql.NodeData;
import de.steamwar.sql.Punishment;
import de.steamwar.sql.SchematicNode;
import de.steamwar.sql.SteamwarUser;
import net.dv8tion.jda.api.entities.Message;
import net.dv8tion.jda.api.events.message.priv.PrivateMessageReceivedEvent;
import java.io.InputStream;
public class PrivateMessageListener extends BasicDiscordListener {
@Override
public void onPrivateMessageReceived(PrivateMessageReceivedEvent event) {
if(!event.getMessage().getAttachments().isEmpty()) {
SteamwarUser user = SteamwarUser.get(event.getAuthor().getIdLong());
if (user == null) {
event.getMessage().reply("Du must dein Minecraft Account mit dem Bot verbinden, gehe dazu auf dem SteamWar Discord in den `regeln-infos` Channel und Klicke auf `Minecraft Verknüpfen`").complete();
return;
}
if(user.isPunished(Punishment.PunishmentType.NoSchemReceiving)) {
event.getMessage().reply("Du darfst keine Schematics hochladen").complete();
return;
}
for (Message.Attachment attachment : event.getMessage().getAttachments()) {
if(attachment.getFileExtension() == null ||
(!attachment.getFileExtension().equalsIgnoreCase("schem") &&
!attachment.getFileExtension().equalsIgnoreCase("schematic"))) {
event.getMessage().reply("`" + attachment.getFileName() + "` wird ignoriert, da die Datei keine Schematic ist").queue();
continue;
}
boolean newFormat = attachment.getFileExtension().equalsIgnoreCase("schem");
int dot = attachment.getFileName().lastIndexOf(".");
String name = attachment.getFileName().substring(0, dot);
if(SchematicNode.invalidSchemName(new String[] {name})) {
event.getMessage().reply("`" + name + "` hat nicht zugelassene Zeichen im Namen").queue();
continue;
}
SchematicNode node = SchematicNode.getSchematicNode(user.getId(), name, (Integer) null);
if(node == null) {
node = SchematicNode.createSchematic(user.getId(), name, null);
}
try {
InputStream in = attachment.retrieveInputStream().get();
NodeData.get(node).saveFromStream(in, newFormat);
in.close();
event.getMessage().reply("`" + name + "` wurde erfolgreich hochgeladen").queue();
} catch (Exception e) {
event.getMessage().reply("`" + name + "` konnte nicht hochgeladen werden, bitte versuche es später nochmal oder wende dich an einen Developer").queue();
BungeeCore.log("Could not Upload Schem \"" + name + "\" from User \"" + user.getUserName() + "\"", e);
}
}
}
}
}

Datei anzeigen

@ -1,42 +0,0 @@
/*
This file is a part of the SteamWar software.
Copyright (C) 2020 SteamWar.de-Serverteam
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bungeecore.bot.listeners;
import de.steamwar.bungeecore.bot.config.SteamwarDiscordBotConfig;
import net.dv8tion.jda.api.entities.ChannelType;
import net.dv8tion.jda.api.events.interaction.GenericComponentInteractionCreateEvent;
import net.dv8tion.jda.api.interactions.InteractionType;
import org.jetbrains.annotations.NotNull;
public class RolesInteractionButtonListener extends BasicDiscordListener {
@Override
public void onGenericComponentInteractionCreate(@NotNull GenericComponentInteractionCreateEvent event) {
if(event.getType() == InteractionType.COMPONENT && event.getChannelType() == ChannelType.TEXT && event.getTextChannel().getId().equals(SteamwarDiscordBotConfig.ROLES_CHANNEL) && SteamwarDiscordBotConfig.ROLES.stream().anyMatch(discordRole -> discordRole.getRoleId().equals(event.getComponentId()))) {
if (event.getMember().getRoles().stream().anyMatch(role -> role.getId().equals(event.getComponentId()))) {
event.getGuild().removeRoleFromMember(event.getMember(), event.getGuild().getRoleById(event.getComponentId())).complete();
event.reply(SteamwarDiscordBotConfig.ROLES_REMOVED.replace("%role%", event.getGuild().getRoleById(event.getComponentId()).getAsMention())).setEphemeral(true).queue();
} else {
event.getGuild().addRoleToMember(event.getMember(), event.getGuild().getRoleById(event.getComponentId())).complete();
event.reply(SteamwarDiscordBotConfig.ROLES_ADDED.replace("%role%", event.getGuild().getRoleById(event.getComponentId()).getAsMention())).setEphemeral(true).queue();
}
}
}
}

Datei anzeigen

@ -1,32 +0,0 @@
/*
* This file is a part of the SteamWar software.
*
* Copyright (C) 2020 SteamWar.de-Serverteam
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bungeecore.bot.listeners;
import de.steamwar.bungeecore.bot.SteamwarDiscordBot;
import net.dv8tion.jda.api.events.interaction.SlashCommandEvent;
import org.jetbrains.annotations.NotNull;
public class SlashCommandListener extends BasicDiscordListener {
@Override
public void onSlashCommand(@NotNull SlashCommandEvent event) {
SteamwarDiscordBot.getDiscordCommandMap().get(event.getName()).run(event);
}
}

Datei anzeigen

@ -1,69 +0,0 @@
/*
* This file is a part of the SteamWar software.
*
* Copyright (C) 2020 SteamWar.de-Serverteam
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bungeecore.bot.util;
import de.steamwar.bungeecore.bot.SteamwarDiscordBot;
import de.steamwar.bungeecore.bot.config.SteamwarDiscordBotConfig;
import de.steamwar.sql.SteamwarUser;
import lombok.experimental.UtilityClass;
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.Role;
import net.dv8tion.jda.api.exceptions.ErrorResponseException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@UtilityClass
public class DiscordRanks {
public void update(SteamwarUser steamwarUser) {
if (steamwarUser.getDiscordId() == null) {
return;
}
Guild guild = SteamwarDiscordBot.instance().getJda().getGuildById(SteamwarDiscordBotConfig.GUILD);
guild.retrieveMemberById(steamwarUser.getDiscordId()).queue(member -> {
List<Role> roleList = member.getRoles();
Set<String> strings = new HashSet<>(SteamwarDiscordBotConfig.RANKS.values());
String needed = SteamwarDiscordBotConfig.RANKS.get(steamwarUser.prefix());
for (Role role : roleList) {
if (!strings.contains(role.getId())) {
continue;
}
if (role.getId().equals(needed)) {
needed = "";
continue;
}
guild.removeRoleFromMember(member, role).complete();
}
if (needed != null && !needed.isEmpty()) {
guild.addRoleToMember(member, guild.getRoleById(needed)).complete();
}
}, throwable -> {
if(throwable instanceof ErrorResponseException) {
ErrorResponseException e = (ErrorResponseException) throwable;
if(e.getErrorCode() == 10007) {
steamwarUser.setDiscordId(null);
}
}
});
}
}

Datei anzeigen

@ -1,61 +0,0 @@
/*
This file is a part of the SteamWar software.
Copyright (C) 2020 SteamWar.de-Serverteam
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bungeecore.bot.util;
import de.steamwar.bungeecore.bot.SteamwarDiscordBot;
import de.steamwar.bungeecore.bot.config.SteamwarDiscordBotConfig;
import lombok.experimental.UtilityClass;
import net.dv8tion.jda.api.MessageBuilder;
import net.dv8tion.jda.api.entities.Message;
import net.dv8tion.jda.api.entities.TextChannel;
import net.dv8tion.jda.api.interactions.components.ActionRow;
import net.dv8tion.jda.api.interactions.components.Button;
import java.util.ArrayList;
import java.util.List;
@UtilityClass
public class DiscordRolesMessage {
public void sendMessage() {
TextChannel channel = SteamwarDiscordBot.instance().getJda().getGuildById(SteamwarDiscordBotConfig.GUILD).getTextChannelById(SteamwarDiscordBotConfig.ROLES_CHANNEL);
assert channel != null;
MessageBuilder builder = new MessageBuilder();
builder.setContent(SteamwarDiscordBotConfig.ROLES_BASE_MESSAGE);
List<Button> buttons = new ArrayList<>();
SteamwarDiscordBotConfig.ROLES.forEach(discordRole -> buttons.add(discordRole.toButton()));
builder.setActionRows(ActionRow.of(buttons));
if(channel.hasLatestMessage()) {
channel.getIterableHistory().queue(messages -> {
Message message = messages.stream().filter(m -> m.getAuthor().isBot()).findFirst().orElse(null);
if (message != null) {
message.editMessage(builder.build()).queue();
} else {
channel.sendMessage(builder.build()).queue();
}
});
} else {
channel.sendMessage(builder.build()).queue();
}
}
}

Datei anzeigen

@ -1,68 +0,0 @@
/*
This file is a part of the SteamWar software.
Copyright (C) 2020 SteamWar.de-Serverteam
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bungeecore.bot.util;
import de.steamwar.bungeecore.bot.SteamwarDiscordBot;
import de.steamwar.bungeecore.bot.config.SteamwarDiscordBotConfig;
import lombok.experimental.UtilityClass;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.MessageBuilder;
import net.dv8tion.jda.api.entities.Emoji;
import net.dv8tion.jda.api.entities.Message;
import net.dv8tion.jda.api.entities.TextChannel;
import net.dv8tion.jda.api.interactions.components.ActionRow;
import net.dv8tion.jda.api.interactions.components.Button;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
@UtilityClass
public class DiscordRulesMessage {
public void sendMessage() {
TextChannel channel = SteamwarDiscordBot.instance().getJda().getGuildById(SteamwarDiscordBotConfig.GUILD).getTextChannelById(SteamwarDiscordBotConfig.RULES_CHANNEL);
assert channel != null;
Message message = null;
if(channel.hasLatestMessage()) {
message = channel.getIterableHistory().complete().stream().filter(m -> m.getAuthor().isBot()).findFirst().orElse(null);
}
EmbedBuilder builder = new EmbedBuilder();
builder.setDescription(SteamwarDiscordBotConfig.RULES_RULES.stream().reduce((s, s2) -> s + "\n" + s2).get());
builder.setColor(Color.GRAY);
builder.setAuthor("SteamWar", "https://www.steamwar.de");
builder.setTitle(SteamwarDiscordBotConfig.RULES_TITLE);
List<Button> buttons = new ArrayList<>();
SteamwarDiscordBotConfig.RULES_LINKS.forEach(discordRulesLink -> buttons.add(discordRulesLink.toButton()));
Button authButton = Button.primary("auth", Emoji.fromUnicode("U+2705")).withLabel("Minecraft verknüpfen");
MessageBuilder messageBuilder = new MessageBuilder();
messageBuilder.setEmbeds(builder.build());
messageBuilder.setActionRows(ActionRow.of(buttons), ActionRow.of(authButton));
if (message != null) {
message.editMessage(messageBuilder.build()).queue();
} else {
channel.sendMessage(messageBuilder.build()).queue();
}
}
}

Datei anzeigen

@ -1,76 +0,0 @@
/*
This file is a part of the SteamWar software.
Copyright (C) 2020 SteamWar.de-Serverteam
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bungeecore.bot.util;
import de.steamwar.bungeecore.bot.SteamwarDiscordBot;
import de.steamwar.bungeecore.bot.config.DiscordTicketType;
import de.steamwar.bungeecore.bot.config.SteamwarDiscordBotConfig;
import lombok.experimental.UtilityClass;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.MessageBuilder;
import net.dv8tion.jda.api.entities.Message;
import net.dv8tion.jda.api.entities.TextChannel;
import net.dv8tion.jda.api.interactions.components.ActionRow;
import net.dv8tion.jda.api.interactions.components.Button;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
@UtilityClass
public class DiscordTicketMessage {
public void sendMessage() {
TextChannel channel = SteamwarDiscordBot.instance().getJda().getGuildById(SteamwarDiscordBotConfig.GUILD).getTextChannelById(SteamwarDiscordBotConfig.TICKET_CHANNEL);
assert channel != null;
Message message = null;
if(channel.hasLatestMessage()) {
message = channel.getIterableHistory().complete().stream().filter(m -> m.getAuthor().isBot()).findFirst().orElse(null);
}
EmbedBuilder builder = new EmbedBuilder();
builder.setDescription(SteamwarDiscordBotConfig.TICKET_MESSAGE);
builder.setTitle("Steamwar-Tickets");
builder.setColor(Color.RED);
List<List<Button>> buttons = new ArrayList<>();
chunked(new ArrayList<>(SteamwarDiscordBotConfig.TICKET_TYPES.values()), 5).forEach(discordTicketTypes -> {
buttons.add(discordTicketTypes.stream().map(DiscordTicketType::toButton).collect(Collectors.toList()));
});
MessageBuilder messageBuilder = new MessageBuilder();
messageBuilder.setEmbeds(builder.build());
messageBuilder.setActionRows(buttons.stream().map(ActionRow::of).collect(Collectors.toList()));
if (message != null) {
message.editMessage(messageBuilder.build()).queue();
} else {
channel.sendMessage(messageBuilder.build()).queue();
}
}
private static <T> List<List<T>> chunked(List<T> list, int chunkSize) {
List<List<T>> chunks = new ArrayList<>();
for (int i = 0; i < list.size(); i += chunkSize) {
chunks.add(list.subList(i, Math.min(i + chunkSize, list.size())));
}
return chunks;
}
}

Datei anzeigen

@ -19,7 +19,7 @@
package de.steamwar.bungeecore.commands;
import de.steamwar.bungeecore.bot.SteamwarDiscordBot;
import de.steamwar.bungeecore.discord.DiscordBot;
import de.steamwar.bungeecore.listeners.ConnectionListener;
import de.steamwar.command.SWCommand;
import de.steamwar.messages.Chatter;
@ -40,8 +40,8 @@ public class AlertCommand extends SWCommand {
String s = String.join(" ", message);
Chatter.broadcast().system("ALERT", ChatColor.translateAlternateColorCodes('&', s));
if ("-discord".equals(sendToDiscord) && SteamwarDiscordBot.instance() != null) {
SteamwarDiscordBot.instance().getAnnouncementListener().announce(s);
}
if ("-discord".equals(sendToDiscord))
DiscordBot.withBot(bot -> bot.getAnnouncementChannel().send(s));
}
}

Datei anzeigen

@ -40,7 +40,7 @@ public class ArenaCommand extends SWCommand {
@Register
public void arenaJoin(PlayerChatter sender, Subserver server) {
TpCommand.teleport(sender.getPlayer(), server.getServer());
TpCommand.teleport(sender, server.getServer());
}
@ClassMapper(value = Subserver.class, local = true)

Datei anzeigen

@ -31,6 +31,7 @@ import de.steamwar.command.SWCommand;
import de.steamwar.command.TypeMapper;
import de.steamwar.command.TypeValidator;
import de.steamwar.messages.Chatter;
import de.steamwar.messages.Message;
import de.steamwar.messages.PlayerChatter;
import de.steamwar.network.packets.server.BaumemberUpdatePacket;
import de.steamwar.sql.BauweltMember;
@ -190,7 +191,7 @@ public class BauCommand extends SWCommand {
@Register("resetall")
@Register("delete")
public void delete(Chatter sender, @OptionalValue(value = "", onlyUINIG = true) ServerVersion version) {
public void delete(PlayerChatter sender, @OptionalValue(value = "", onlyUINIG = true) ServerVersion version) {
SWInventory inventory = new SWInventory(sender, 9, new Message("BAU_DELETE_GUI_NAME"));
inventory.addItem(0, new SWItem(new Message("BAU_DELETE_GUI_DELETE"), 10), click -> {
String world = version.getWorldFolder(ServerStarter.WORLDS_BASE_PATH) + (version != ServerVersion.SPIGOT_12 ? sender.user().getId() : sender.user().getUUID().toString());
@ -213,7 +214,7 @@ public class BauCommand extends SWCommand {
@Register("test")
@Register("testarena")
public void testarena(PlayerChatter sender, @Mapper("nonHistoricArenaMode") @OptionalValue("") @AllowNull ArenaMode arenaMode, @Mapper("arenaMap") @OptionalValue("") @AllowNull String map) {
FightCommand.createArena(sender.getPlayer(), "/bau testarena ", false, arenaMode, map, false, (player, mode, m) ->
FightCommand.createArena(sender, "/bau testarena ", false, arenaMode, map, false, (chatter, mode, m) ->
ProxyServer.getInstance().getScheduler().runAsync(BungeeCore.get(), () -> new ServerStarter().test(mode, m, sender.getPlayer()).start())
);
}

Datei anzeigen

@ -21,6 +21,7 @@ package de.steamwar.bungeecore.commands;
import de.steamwar.bungeecore.*;
import de.steamwar.messages.Chatter;
import de.steamwar.messages.Message;
import de.steamwar.messages.PlayerChatter;
import de.steamwar.sql.IgnoreSystem;
import de.steamwar.command.SWCommand;

Datei anzeigen

@ -20,10 +20,11 @@
package de.steamwar.bungeecore.commands;
import de.steamwar.bungeecore.*;
import de.steamwar.bungeecore.bot.util.DiscordAlert;
import de.steamwar.bungeecore.discord.util.DiscordAlert;
import de.steamwar.bungeecore.listeners.ConnectionListener;
import de.steamwar.command.SWCommand;
import de.steamwar.messages.Chatter;
import de.steamwar.messages.Message;
import de.steamwar.messages.PlayerChatter;
import de.steamwar.sql.*;
import net.md_5.bungee.api.ChatColor;

Datei anzeigen

@ -24,6 +24,7 @@ import de.steamwar.bungeecore.inventory.SWInventory;
import de.steamwar.bungeecore.inventory.SWItem;
import de.steamwar.command.SWCommand;
import de.steamwar.messages.Chatter;
import de.steamwar.messages.Message;
import de.steamwar.messages.PlayerChatter;
import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.ChatMessageType;

Datei anzeigen

@ -19,7 +19,7 @@
package de.steamwar.bungeecore.commands;
import de.steamwar.bungeecore.Message;
import de.steamwar.messages.Message;
import de.steamwar.command.SWCommand;
import de.steamwar.messages.Chatter;
import net.md_5.bungee.api.chat.ClickEvent;

Datei anzeigen

@ -19,7 +19,7 @@
package de.steamwar.bungeecore.commands;
import de.steamwar.bungeecore.Message;
import de.steamwar.messages.Message;
import de.steamwar.bungeecore.inventory.SWInventory;
import de.steamwar.bungeecore.inventory.SWItem;
import de.steamwar.bungeecore.inventory.SWListInv;

Datei anzeigen

@ -21,7 +21,7 @@ package de.steamwar.bungeecore.commands;
import com.google.gson.JsonParser;
import de.steamwar.bungeecore.BungeeCore;
import de.steamwar.bungeecore.Message;
import de.steamwar.messages.Message;
import de.steamwar.bungeecore.listeners.ConnectionListener;
import de.steamwar.bungeecore.listeners.IPSanitizer;
import de.steamwar.command.PreviousArguments;

Datei anzeigen

@ -20,7 +20,7 @@
package de.steamwar.bungeecore.commands;
import de.steamwar.command.SWCommand;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import de.steamwar.messages.PlayerChatter;
import static de.steamwar.bungeecore.Storage.lastChats;
@ -31,7 +31,7 @@ public class RCommand extends SWCommand {
}
@Register(description = "R_USAGE")
public void genericCommand(ProxiedPlayer player, @ErrorMessage(value = "R_USAGE", allowEAs = false) String... message) {
MsgCommand.msg(player, lastChats.get(player), message);
public void genericCommand(PlayerChatter sender, @ErrorMessage(value = "R_USAGE", allowEAs = false) String... message) {
MsgCommand.msg(sender, lastChats.get(sender.getPlayer()), message);
}
}

Datei anzeigen

@ -20,17 +20,13 @@
package de.steamwar.bungeecore.commands;
import de.steamwar.bungeecore.ArenaMode;
import de.steamwar.bungeecore.Message;
import de.steamwar.messages.Message;
import de.steamwar.command.SWCommand;
import de.steamwar.command.SWCommandUtils;
import de.steamwar.command.TypeMapper;
import de.steamwar.messages.Chatter;
import de.steamwar.sql.SteamwarUser;
import de.steamwar.sql.UserElo;
import net.md_5.bungee.BungeeCord;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import java.util.Optional;
import java.util.stream.Collectors;
public class RankCommand extends SWCommand {
@ -39,31 +35,30 @@ public class RankCommand extends SWCommand {
}
@Register
public void ownRank(ProxiedPlayer player) {
rank(player, SteamwarUser.get(player.getUniqueId()));
public void ownRank(Chatter sender) {
rank(sender, sender.user());
}
@Register
public void rank(ProxiedPlayer player, @ErrorMessage("RANK_PLAYER_NOT_FOUND") SteamwarUser user) {
if (!player.getName().equals(user.getUserName())) {
Message.sendPrefixless("RANK_PLAYER_FOUND", player, user.getUserName());
}
public void rank(Chatter sender, @ErrorMessage("RANK_PLAYER_NOT_FOUND") SteamwarUser user) {
if (!sender.user().equals(user))
sender.prefixless("RANK_PLAYER_FOUND", user);
for(ArenaMode mode : ArenaMode.getAllModes()) {
if (!mode.isRanked())
continue;
Optional<Integer> elo = UserElo.getElo(user.getId(), mode.getSchemType());
String eloString;
Message eloMsg;
if (elo.isPresent()) {
int placement = UserElo.getPlacement(elo.get(), mode.getSchemType());
eloString = Message.parse("RANK_PLACED", player, placement, elo.get());
eloMsg = new Message("RANK_PLACED", placement, elo.get());
} else {
eloString = Message.parse("RANK_UNPLACED", player);
eloMsg = new Message("RANK_UNPLACED");
}
Message.sendPrefixless("RANK_HEADER", player, mode.getChatName(), eloString);
Message.sendPrefixless("RANK_EMBLEM", player, UserElo.getEmblemProgression(mode.getChatName(), user.getId()));
sender.prefixless("RANK_HEADER", mode.getChatName(), eloMsg);
sender.prefixless("RANK_EMBLEM", UserElo.getEmblemProgression(mode.getChatName(), user.getId()));
}
}
}

Datei anzeigen

@ -1,42 +0,0 @@
/*
This file is a part of the SteamWar software.
Copyright (C) 2020 SteamWar.de-Serverteam
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bungeecore.commands;
import de.steamwar.bungeecore.Message;
import de.steamwar.command.SWCommand;
import net.md_5.bungee.api.chat.ClickEvent;
import net.md_5.bungee.api.connection.ProxiedPlayer;
public class RegelnCommand extends SWCommand {
public RegelnCommand() {
super("regeln", null, "rules");
}
@Register
public void genericCommand(ProxiedPlayer player) {
Message.send("REGELN_RULES", player);
Message.sendPrefixless("REGELN_AS", player, Message.parse("REGELN_AS_HOVER", player), new ClickEvent(ClickEvent.Action.OPEN_URL, Message.parse("REGELN_AS_URL", player)));
Message.sendPrefixless("REGELN_MWG", player, Message.parse("REGELN_MWG_HOVER", player), new ClickEvent(ClickEvent.Action.OPEN_URL, Message.parse("REGELN_MWG_URL", player)));
Message.sendPrefixless("REGELN_WG", player, Message.parse("REGELN_WG_HOVER", player), new ClickEvent(ClickEvent.Action.OPEN_URL, Message.parse("REGELN_WG_URL", player)));
Message.sendPrefixless("REGELN_WS", player, Message.parse("REGELN_WS_HOVER", player), new ClickEvent(ClickEvent.Action.OPEN_URL, Message.parse("REGELN_WS_URL", player)));
Message.sendPrefixless("REGELN_QG", player, Message.parse("REGELN_QG_HOVER", player), new ClickEvent(ClickEvent.Action.OPEN_URL, Message.parse("REGELN_QG_URL", player)));
Message.sendPrefixless("REGELN_CONDUCT", player, Message.parse("REGELN_CONDUCT_HOVER", player), new ClickEvent(ClickEvent.Action.OPEN_URL, Message.parse("REGELN_CONDUCT_URL", player)));
}
}

Datei anzeigen

@ -19,14 +19,15 @@
package de.steamwar.bungeecore.commands;
import de.steamwar.bungeecore.*;
import de.steamwar.bungeecore.ArenaMode;
import de.steamwar.messages.Message;
import de.steamwar.bungeecore.ServerStarter;
import de.steamwar.bungeecore.inventory.SWItem;
import de.steamwar.bungeecore.inventory.SWListInv;
import de.steamwar.bungeecore.inventory.SWStreamInv;
import de.steamwar.sql.*;
import de.steamwar.command.SWCommand;
import de.steamwar.messages.Chatter;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import de.steamwar.messages.PlayerChatter;
import de.steamwar.sql.*;
import java.util.ArrayList;
import java.util.List;
@ -39,15 +40,13 @@ public class ReplayCommand extends SWCommand {
}
@Register
public void genericCommand(ProxiedPlayer player, @OptionalValue("") String optionalMap) {
Chatter sender = Chatter.of(player);
public void genericCommand(PlayerChatter sender, @OptionalValue("") String optionalMap) {
if (PunishmentCommand.isPunishedWithMessage(sender, Punishment.PunishmentType.NoFightServer))
return;
new SWStreamInv<>(player, Message.parse("REPLAY_TITLE", player), (click, fight) -> {
SteamwarUser user = SteamwarUser.get(player.getUniqueId());
new SWStreamInv<>(sender, new Message("REPLAY_TITLE"), (click, fight) -> {
ArenaMode mode = ArenaMode.getBySchemType(fight.getSchemType());
ServerStarter starter = new ServerStarter().replay(fight.getFightID()).blueLeader(player);
ServerStarter starter = new ServerStarter().replay(fight.getFightID()).blueLeader(sender.getPlayer());
String map = mode.getRandomMap();
if (!optionalMap.equals("")) {
@ -55,27 +54,27 @@ public class ReplayCommand extends SWCommand {
if (tMap != null) map = tMap;
}
if (user.hasPerm(UserPerm.MODERATION) && click.isShiftClick() && fight.replayExists()) {
starter.test(mode, map, player).start();
if (sender.user().hasPerm(UserPerm.MODERATION) && click.isShiftClick() && fight.replayExists()) {
starter.test(mode, map, sender.getPlayer()).start();
} else if(!fight.replayAllowed()) {
sender.system("REPLAY_UNAVAILABLE");
} else {
starter.arena(mode, map).start();
}
}, page -> Fight.getPage(page, 45).stream().map(fight -> new SWListInv.SWListEntry<>(getFightItem(sender, fight), fight)).collect(Collectors.toList())).open();
}, page -> Fight.getPage(page, 45).stream().map(fight -> new SWListInv.SWListEntry<>(getFightItem(fight), fight)).collect(Collectors.toList())).open();
}
private SWItem getFightItem(Chatter sender, Fight fight) {
private SWItem getFightItem(Fight fight) {
SchematicType type = fight.getSchemType();
SWItem item = new SWItem(type != null ? type.getMaterial() : "BARRIER", parseLeader(sender, fight.getBlueLeader(), fight.getBluePlayers().size(), fight.getWin() == 1));
SWItem item = new SWItem(type != null ? type.getMaterial() : "BARRIER", parseLeader(fight.getBlueLeader(), fight.getBluePlayers().size(), fight.getWin() == 1));
List<String> lore = new ArrayList<>();
lore.add(parseLeader(sender, fight.getRedLeader(), fight.getRedPlayers().size(), fight.getWin() == 2));
lore.add(sender.parseToLegacy("REPLAY_TIME", fight.getStartTime()));
lore.add("");
lore.add(sender.parseToLegacy("REPLAY_SERVER", fight.getServer()));
List<Message> lore = new ArrayList<>();
lore.add(parseLeader(fight.getRedLeader(), fight.getRedPlayers().size(), fight.getWin() == 2));
lore.add(new Message("REPLAY_TIME", fight.getStartTime()));
lore.add(new Message("SPACER"));
lore.add(new Message("REPLAY_SERVER", fight.getServer()));
if(!fight.replayAllowed())
lore.add(sender.parseToLegacy("REPLAY_UNAVAILABLE"));
lore.add(new Message("REPLAY_UNAVAILABLE"));
item.setLore(lore);
if(fight.replayAllowed())
@ -84,7 +83,7 @@ public class ReplayCommand extends SWCommand {
return item;
}
private String parseLeader(Chatter sender, SteamwarUser leader, int players, boolean winner) {
return sender.parseToLegacy(winner ? (players > 1 ? "REPLAY_WINNER" : "REPLAY_SOLO_WINNER") : (players > 1 ? "REPLAY_LOSER" : "REPLAY_SOLO_LOSER"), leader.getUserName(), players - 1);
private Message parseLeader(SteamwarUser leader, int players, boolean winner) {
return new Message("REPLAY_" + (players > 1 ? "" : "SOLO_") + (winner ? "WINNER" : "LOSER"), leader.getUserName(), players - 1);
}
}

Datei anzeigen

@ -15,22 +15,27 @@
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
*/
package de.steamwar.bungeecore.bot.config;
package de.steamwar.bungeecore.commands;
import lombok.AllArgsConstructor;
import lombok.Data;
import net.dv8tion.jda.api.interactions.components.Button;
import de.steamwar.messages.Message;
import de.steamwar.command.SWCommand;
import de.steamwar.messages.Chatter;
import net.md_5.bungee.api.chat.ClickEvent;
@Data
@AllArgsConstructor
public class DiscordRulesLink {
import java.util.Arrays;
private String label;
private String link;
public class RulesCommand extends SWCommand {
public RulesCommand() {
super("rules", null, "regeln");
}
public Button toButton() {
return Button.link(link, label);
@Register
public void genericCommand(Chatter sender) {
sender.system("REGELN_RULES");
for(String ruleset : Arrays.asList("REGELN_AS", "REGELN_MWG", "REGELN_WG", "REGELN_WS", "REGELN_QG", "REGELN_CONDUCT"))
sender.prefixless(ruleset, new Message(ruleset + "_HOVER"), new ClickEvent(ClickEvent.Action.OPEN_URL, sender.parseToPlain(ruleset + "_URL")));
}
}

Datei anzeigen

@ -20,9 +20,9 @@
package de.steamwar.bungeecore.commands;
import de.steamwar.command.SWCommand;
import de.steamwar.messages.PlayerChatter;
import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.config.ServerInfo;
import net.md_5.bungee.api.connection.ProxiedPlayer;
public class ServerSwitchCommand extends SWCommand {
@ -34,8 +34,8 @@ public class ServerSwitchCommand extends SWCommand {
}
@Register
public void genericCommand(ProxiedPlayer player) {
public void genericCommand(PlayerChatter sender) {
ServerInfo target = ProxyServer.getInstance().getServerInfo(serverName);
player.connect(target);
sender.getPlayer().connect(target);
}
}

Datei anzeigen

@ -23,7 +23,6 @@ import de.steamwar.bungeecore.listeners.ChatListener;
import de.steamwar.bungeecore.listeners.ConnectionListener;
import de.steamwar.command.SWCommand;
import de.steamwar.messages.Chatter;
import net.md_5.bungee.api.CommandSender;
public class ServerTeamchatCommand extends SWCommand {
@ -32,7 +31,7 @@ public class ServerTeamchatCommand extends SWCommand {
}
@Register(description = "STC_USAGE")
public void genericCommand(CommandSender commandSender, @ErrorMessage(value = "STC_USAGE", allowEAs = false) String... message) {
ChatListener.sendChat(Chatter.of(commandSender), Chatter.serverteam(), "CHAT_SERVERTEAM", null, String.join(" ", message));
public void genericCommand(Chatter sender, @ErrorMessage(value = "STC_USAGE", allowEAs = false) String... message) {
ChatListener.sendChat(sender, Chatter.serverteam(), "CHAT_SERVERTEAM", null, String.join(" ", message));
}
}

Datei anzeigen

@ -23,7 +23,6 @@ import de.steamwar.bungeecore.network.NetworkSender;
import de.steamwar.command.SWCommand;
import de.steamwar.messages.Chatter;
import de.steamwar.network.packets.server.LocaleInvalidationPacket;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import java.util.Objects;
@ -34,10 +33,9 @@ public class SetLocaleCommand extends SWCommand {
}
@Register
public void genericCommand(ProxiedPlayer player) {
Chatter sender = Chatter.of(player);
sender.user().setLocale(Objects.requireNonNull(player.getLocale()), true);
NetworkSender.send(player, new LocaleInvalidationPacket(sender.user().getId()));
public void genericCommand(Chatter sender) {
sender.user().setLocale(Objects.requireNonNull(sender.getLocale()), true);
sender.withPlayer(player -> NetworkSender.send(player, new LocaleInvalidationPacket(sender.user().getId())));
sender.system("LOCK_LOCALE_CHANGED");
}
}

Datei anzeigen

@ -19,10 +19,10 @@
package de.steamwar.bungeecore.commands;
import de.steamwar.bungeecore.Message;
import de.steamwar.bungeecore.Node;
import de.steamwar.bungeecore.listeners.ConnectionListener;
import de.steamwar.command.SWCommand;
import net.md_5.bungee.api.CommandSender;
import de.steamwar.messages.Chatter;
import java.io.BufferedReader;
import java.io.InputStreamReader;
@ -32,11 +32,11 @@ import java.util.Map;
public class StatCommand extends SWCommand {
public StatCommand() {
super("stat", "bungeecore.softreload", "stats");
super("stat", ConnectionListener.SOFTRELOAD_PERMISSION, "stats");
}
@Register
public void genericCommand(CommandSender sender) {
public void genericCommand(Chatter sender) {
Map<String, Integer> serverCount = new HashMap<>();
try {
Process process = new ProcessBuilder("ps", "x").start();
@ -52,6 +52,6 @@ public class StatCommand extends SWCommand {
throw new SecurityException(e.getMessage(), e);
}
Node.forEach(node -> Message.send("STAT_SERVER", sender, node.getName(), node.belowLoadLimit(), serverCount.getOrDefault(node.getName(), 0)));
Node.forEach(node -> sender.prefixless("STAT_SERVER", node.getName(), node.belowLoadLimit(), serverCount.getOrDefault(node.getName(), 0)));
}
}

Datei anzeigen

@ -19,8 +19,9 @@
package de.steamwar.bungeecore.commands;
import de.steamwar.bungeecore.Message;
import de.steamwar.messages.Message;
import de.steamwar.bungeecore.Storage;
import de.steamwar.bungeecore.discord.DiscordBot;
import de.steamwar.bungeecore.inventory.SWItem;
import de.steamwar.bungeecore.inventory.SWListInv;
import de.steamwar.command.PreviousArguments;
@ -28,18 +29,12 @@ import de.steamwar.command.SWCommand;
import de.steamwar.command.TypeMapper;
import de.steamwar.command.TypeValidator;
import de.steamwar.messages.Chatter;
import de.steamwar.messages.PlayerChatter;
import de.steamwar.sql.*;
import net.md_5.bungee.BungeeCord;
import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.CommandSender;
import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.ServerConnectRequest;
import net.md_5.bungee.api.chat.ClickEvent;
import net.md_5.bungee.api.chat.ComponentBuilder;
import net.md_5.bungee.api.chat.HoverEvent;
import net.md_5.bungee.api.chat.TextComponent;
import net.md_5.bungee.api.*;
import net.md_5.bungee.api.chat.*;
import net.md_5.bungee.api.chat.hover.content.Text;
import net.md_5.bungee.api.config.ServerInfo;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import net.md_5.bungee.api.event.ServerConnectEvent;
import java.net.*;
@ -53,93 +48,53 @@ import static de.steamwar.bungeecore.Storage.teamInvitations;
public class TeamCommand extends SWCommand {
private static final List<SWListInv.SWListEntry<String>> COLOR_CODES = new ArrayList<>();
static {
addColor("4", 1);
addColor("c", 15);
addColor("6", 14);
addColor("e", 11);
addColor("2", 2);
addColor("a", 10);
addColor("b", 12);
addColor("3", 6);
addColor("1", 4);
addColor("9", 6);
addColor("d", 9);
addColor("5", 5);
addColor("f", 15);
addColor("7", 7);
addColor("8", 8);
addColor("0", 16);
}
private static void addColor(String color, int colorCode) {
COLOR_CODES.add(new SWListInv.SWListEntry(new SWItem("§" + color, colorCode), color));
}
public TeamCommand() {
super("team");
}
@Register(noTabComplete = true)
public void help(CommandSender sender, String... args){
Message.send("TEAM_HELP_HEADER", sender);
Message.send("TEAM_HELP_LIST", sender);
Message.send("TEAM_HELP_INFO", sender);
if(!(sender instanceof ProxiedPlayer))
return;
Message.send("TEAM_HELP_TP", sender);
public void help(Chatter sender, String... args){
helpMessages(sender, "TEAM_HELP_HEADER", "TEAM_HELP_LIST", "TEAM_HELP_INFO", "TEAM_HELP_TP");
ProxiedPlayer player = (ProxiedPlayer) sender;
SteamwarUser user = SteamwarUser.get(player.getUniqueId());
SteamwarUser user = sender.user();
if(user.getTeam() == 0) {
Message.send("TEAM_HELP_CREATE", sender);
Message.send("TEAM_HELP_JOIN", sender);
helpMessages(sender, "TEAM_HELP_CREATE", "TEAM_HELP_JOIN");
}else{
Message.send("TEAM_HELP_CHAT", sender);
Message.send("TEAM_HELP_EVENT", sender);
Message.send("TEAM_HELP_LEAVE", sender);
helpMessages(sender, "TEAM_HELP_CHAT", "TEAM_HELP_EVENT", "TEAM_HELP_LEAVE");
if(user.isLeader()){
Message.send("TEAM_HELP_INVITE", sender);
Message.send("TEAM_HELP_REMOVE", sender);
Message.send("TEAM_HELP_KUERZEL", sender);
Message.send("TEAM_HELP_NAME", sender);
Message.send("TEAM_HELP_COLOR", sender);
Message.send("TEAM_HELP_LEADER", sender);
Message.send("TEAM_HELP_STEP_BACK", sender);
Message.send("TEAM_HELP_SERVER", sender);
if(user.isLeader())
helpMessages(sender, "TEAM_HELP_INVITE", "TEAM_HELP_REMOVE", "TEAM_HELP_KUERZEL", "TEAM_HELP_NAME", "TEAM_HELP_COLOR", "TEAM_HELP_LEADER", "TEAM_HELP_STEP_BACK", "TEAM_HELP_SERVER");
}
}
private void helpMessages(Chatter sender, String... messages) {
for(String message : messages)
sender.system(message);
}
@Register(value = "create", description = "TEAM_CREATE_USAGE")
public void create(@Validator("isNotInTeam") ProxiedPlayer player, @Length(min = 2, max = 4) @ErrorMessage("TEAM_KUERZEL_LENGTH") String kuerzel, @Length(min = 4, max = 15) @ErrorMessage("TEAM_NAME_LENGTH") String name){
SteamwarUser user = SteamwarUser.get(player.getUniqueId());
public void create(@Validator("isNotInTeam") Chatter sender, @Length(min = 2, max = 4) @ErrorMessage("TEAM_KUERZEL_LENGTH") String kuerzel, @Length(min = 4, max = 15) @ErrorMessage("TEAM_NAME_LENGTH") String name){
SteamwarUser user = sender.user();
Team team = Team.get(user.getTeam());
if(checkTeamKuerzel(player, team, kuerzel))
return;
if(checkTeamName(player, team, name))
if(checkTeamKuerzel(sender, team, kuerzel) || checkTeamName(sender, team, name))
return;
Team.create(kuerzel, name);
user.setTeam(Team.get(kuerzel).getTeamId());
user.setLeader(true);
Message.send("TEAM_CREATE_CREATED", player, name);
sender.system("TEAM_CREATE_CREATED", name);
}
@Register("join")
public void join(@Validator("isNotInTeam") ProxiedPlayer player, String... args){
SteamwarUser user = SteamwarUser.get(player.getUniqueId());
public void join(@Validator("isNotInTeam") Chatter sender, String... args){
SteamwarUser user = sender.user();
if(notDuringEvent(player))
if(notDuringEvent(sender))
return;
if(!teamInvitations.containsKey(user.getId())){
Message.send("TEAM_JOIN_NO_INVITE", player);
sender.system("TEAM_JOIN_NO_INVITE");
return;
}
@ -150,13 +105,13 @@ public class TeamCommand extends SWCommand {
t = invs.get(0);
}else{
if(args.length != 1){
Message.send("TEAM_JOIN_USAGE", player);
sender.system("TEAM_JOIN_USAGE");
StringBuilder sb = new StringBuilder();
for(int inv : invs){
Team team = Team.get(inv);
sb.append(team.getTeamName()).append(" ");
}
Message.send("TEAM_JOIN_INVITED", player, sb.toString());
sender.system("TEAM_JOIN_INVITED", sb.toString());
return;
}
@ -169,48 +124,47 @@ public class TeamCommand extends SWCommand {
}
if(t == null){
Message.send("TEAM_JOIN_NOT_BY_TEAM", player);
sender.system("TEAM_JOIN_NOT_BY_TEAM");
return;
}
}
user.setTeam(t);
teamInvitations.remove(user.getId());
Message.send("TEAM_JOIN_JOINED", player, Team.get(t).getTeamName());
sender.system("TEAM_JOIN_JOINED", Team.get(t).getTeamName());
}
@Register("stepback")
public void stepBack(@Validator("isLeader") ProxiedPlayer player) {
SteamwarUser user = SteamwarUser.get(player.getUniqueId());
public void stepBack(@Validator("isLeader") Chatter sender) {
SteamwarUser user = sender.user();
Team team = Team.get(user.getTeam());
if(noRemainingLeaders(team, user)){
Message.send("TEAM_OTHER_LEADER_REQUIRED", player);
sender.system("TEAM_OTHER_LEADER_REQUIRED");
return;
}
user.setLeader(false);
Message.send("TEAM_STEP_BACK", player);
sender.system("TEAM_STEP_BACK");
}
@Register("leave")
public void leave(@Validator("isInTeam") ProxiedPlayer player){
SteamwarUser user = SteamwarUser.get(player.getUniqueId());
public void leave(@Validator("isInTeam") Chatter sender) {
SteamwarUser user = sender.user();
Team team = Team.get(user.getTeam());
int teamSize = team.size();
if(teamSize > 1 && user.isLeader() && noRemainingLeaders(team, user)) {
Message.send("TEAM_OTHER_LEADER_REQUIRED", player);
sender.system("TEAM_OTHER_LEADER_REQUIRED");
return;
}
user.setTeam(0);
if(teamSize == 1){
if(teamSize == 1)
team.disband(user);
}
Message.send("TEAM_LEAVE_LEFT", player);
sender.system("TEAM_LEAVE_LEFT");
}
private boolean noRemainingLeaders(Team team, SteamwarUser except) {
@ -219,90 +173,65 @@ public class TeamCommand extends SWCommand {
@Register(value = "invite", description = "TEAM_INVITE_USAGE")
public void invite(@Validator("isLeader") ProxiedPlayer player, @AllowNull SteamwarUser target){
SteamwarUser user = SteamwarUser.get(player.getUniqueId());
Team team = Team.get(user.getTeam());
public void invite(@Validator("isLeader") Chatter sender, @ErrorMessage("TEAM_INVITE_NO_PLAYER") SteamwarUser target){
Team team = Team.get(sender.user().getTeam());
if(notDuringEvent(player))
if(notDuringEvent(sender))
return;
if(target == null){
Message.send("TEAM_INVITE_NO_PLAYER", player);
return;
}else if(target.getTeam() != 0){
Message.send("TEAM_INVITE_IN_TEAM", player);
if(target.getTeam() != 0){
sender.system("TEAM_INVITE_IN_TEAM");
return;
}
if(!teamInvitations.containsKey(target.getId()))
teamInvitations.put(target.getId(), new LinkedList<>());
if(teamInvitations.get(target.getId()).contains(team.getTeamId())){
Message.send("TEAM_INVITE_ALREADY_INVITED", player);
List<Integer> invitations = teamInvitations.computeIfAbsent(target.getId(), id -> new ArrayList<>());
if(invitations.contains(team.getTeamId())){
sender.system("TEAM_INVITE_ALREADY_INVITED");
return;
}
teamInvitations.get(target.getId()).add(team.getTeamId());
Message.send("TEAM_INVITE_INVITED", player, target.getUserName());
ProxiedPlayer p = ProxyServer.getInstance().getPlayer(target.getUUID());
if(p != null)
Message.send("TEAM_INVITE_INVITED_TARGET", p, team.getTeamColor(), team.getTeamName());
invitations.add(team.getTeamId());
sender.system("TEAM_INVITE_INVITED", target.getUserName());
Chatter.of(target).system("TEAM_INVITE_INVITED_TARGET", team.getTeamColor(), team.getTeamName());
}
@Register(value = "remove", description = "TEAM_REMOVE_USAGE")
public void remove(@Validator("isLeader") ProxiedPlayer player, @AllowNull @Mapper("memberList") SteamwarUser target){
SteamwarUser user = SteamwarUser.get(player.getUniqueId());
Team team = Team.get(user.getTeam());
if(target == null){
Message.send("TEAM_REMOVE_NOT_PLAYER", player);
return;
}
public void remove(@Validator("isLeader") Chatter sender, @ErrorMessage("TEAM_REMOVE_NOT_PLAYER") @Mapper("memberList") SteamwarUser target){
Team team = Team.get(sender.user().getTeam());
if (target.isLeader()) {
Message.send("TEAM_REMOVE_NOT_LEADER", player);
sender.system("TEAM_REMOVE_NOT_LEADER");
return;
}
if(teamInvitations.containsKey(target.getId())){
if(teamInvitations.get(target.getId()).remove((Integer) team.getTeamId())){
Message.send("TEAM_REMOVE_INVITE", player);
if(teamInvitations.get(target.getId()).isEmpty())
teamInvitations.remove(target.getId());
}else{
Message.send("TEAM_REMOVE_NO_INVITE", player);
}
List<Integer> invitations = teamInvitations.get(target.getId());
if(invitations != null) {
sender.system(invitations.remove((Integer) team.getTeamId()) ? "TEAM_REMOVE_INVITE" : "TEAM_REMOVE_NO_INVITE");
return;
}
if(target.getTeam() != user.getTeam()){
Message.send("TEAM_REMOVE_NOT_IN_TEAM", player);
if(target.getTeam() != team.getTeamId()) {
sender.system("TEAM_REMOVE_NOT_IN_TEAM");
return;
}
target.setTeam(0);
Message.send("TEAM_REMOVE_REMOVED", player);
ProxiedPlayer p = ProxyServer.getInstance().getPlayer(target.getUUID());
if(p != null)
Message.send("TEAM_REMOVE_REMOVED_TARGET", player);
sender.system("TEAM_REMOVE_REMOVED");
Chatter.of(target).system("TEAM_REMOVE_REMOVED_TARGET");
}
@Mapper(value = "memberList", local = true)
public TypeMapper<SteamwarUser> memberList() {
return new TypeMapper<SteamwarUser>() {
@Override
public SteamwarUser map(CommandSender commandSender, String[] previousArguments, String s) {
public SteamwarUser map(Chatter sender, PreviousArguments previousArguments, String s) {
return SteamwarUser.get(s);
}
@Override
public Collection<String> tabCompletes(CommandSender sender, PreviousArguments previousArguments, String s) {
if (!(sender instanceof ProxiedPlayer)) return Collections.emptyList();
ProxiedPlayer player = (ProxiedPlayer) sender;
Team team = Team.get(SteamwarUser.get(player.getUniqueId()).getTeam());
return team.getMembers().stream()
public Collection<String> tabCompletes(Chatter sender, PreviousArguments previousArguments, String s) {
return Team.get(sender.user().getTeam()).getMembers().stream()
.map(SteamwarUser::get)
.map(SteamwarUser::getUserName)
.collect(Collectors.toList());
@ -311,187 +240,164 @@ public class TeamCommand extends SWCommand {
}
@Register(value = "changekurzel", description = "TEAM_KUERZEL_USAGE")
public void changekuerzel(@Validator("isLeader") ProxiedPlayer player, @Length(min = 2, max = 4) @ErrorMessage("TEAM_KUERZEL_LENGTH") String kuerzel){
SteamwarUser user = SteamwarUser.get(player.getUniqueId());
Team team = Team.get(user.getTeam());
public void changekuerzel(@Validator("isLeader") Chatter sender, @Length(min = 2, max = 4) @ErrorMessage("TEAM_KUERZEL_LENGTH") String kuerzel){
Team team = Team.get(sender.user().getTeam());
if(notDuringEvent(player))
if(notDuringEvent(sender))
return;
if(checkTeamKuerzel(player, team, kuerzel))
if(checkTeamKuerzel(sender, team, kuerzel))
return;
team.setTeamKuerzel(kuerzel);
Message.send("TEAM_KUERZEL_CHANGED", player);
sender.system("TEAM_KUERZEL_CHANGED");
}
@Register(value = "changename", description = "TEAM_NAME_USAGE")
public void changename(@Validator("isLeader") ProxiedPlayer player, @Length(min = 4, max = 15) @ErrorMessage("TEAM_NAME_LENGTH") String name){
SteamwarUser user = SteamwarUser.get(player.getUniqueId());
Team team = Team.get(user.getTeam());
public void changename(@Validator("isLeader") Chatter sender, @Length(min = 4, max = 15) @ErrorMessage("TEAM_NAME_LENGTH") String name){
Team team = Team.get(sender.user().getTeam());
if(notDuringEvent(player))
if(notDuringEvent(sender))
return;
if(checkTeamName(player, team, name))
if(checkTeamName(sender, team, name))
return;
team.setTeamName(name);
Message.send("TEAM_NAME_CHANGED", player);
sender.system("TEAM_NAME_CHANGED");
}
@Register(value = "promote", description = "TEAM_LEADER_USAGE")
public void promote(@Validator("isLeader") ProxiedPlayer player, @AllowNull @Mapper("memberList") SteamwarUser target){
SteamwarUser user = SteamwarUser.get(player.getUniqueId());
if(notDuringEvent(player))
public void promote(@Validator("isLeader") Chatter sender, @ErrorMessage("TEAM_LEADER_NOT_USER") @Mapper("memberList") SteamwarUser target){
if(notDuringEvent(sender))
return;
if(target == null){
Message.send("TEAM_LEADER_NOT_USER", player);
return;
}
if(target.getTeam() != user.getTeam()){
Message.send("TEAM_LEADER_NOT_MEMBER", player);
if (target.getTeam() != sender.user().getTeam()) {
sender.system("TEAM_LEADER_NOT_MEMBER");
return;
}
target.setLeader(true);
Message.send("TEAM_LEADER_PROMOTED", player, target.getUserName());
}
private String playerName(SteamwarUser user){
return ProxyServer.getInstance().getPlayer(user.getUUID()) != null ? "§a" + user.getUserName() : "§e" + user.getUserName();
sender.system("TEAM_LEADER_PROMOTED", target);
}
@Register("info")
public void info(@Validator("isInTeam") ProxiedPlayer player){
SteamwarUser user = SteamwarUser.get(player.getUniqueId());
Team team = Team.get(user.getTeam());
info(player, team);
public void info(@Validator("isInTeam") Chatter sender){
info(sender, Team.get(sender.user().getTeam()));
}
@Register(value = "info", description = "TEAM_INFO_USAGE")
public void info(ProxiedPlayer player, @ErrorMessage("UNKNOWN_TEAM") Team team){
SteamwarUser user = SteamwarUser.get(player.getUniqueId());
Message.sendPrefixless("TEAM_INFO_TEAM", player, team.getTeamName(), team.getTeamColor(), team.getTeamKuerzel());
public void info(Chatter sender, @ErrorMessage("UNKNOWN_TEAM") Team team){
List<SteamwarUser> users = team.getMembers().stream().map(SteamwarUser::get).collect(Collectors.toList());
Message.sendPrefixless("TEAM_INFO_LEADER", player, users.stream().filter(SteamwarUser::isLeader).count(), getMemberList(users, true));
sender.system("TEAM_INFO_TEAM", team.getTeamName(), team.getTeamColor(), team.getTeamKuerzel());
sender.prefixless("TEAM_INFO_LEADER", users.stream().filter(SteamwarUser::isLeader).count(), getMemberList(users, true));
String members = getMemberList(users, false);
if(members.length() > 0) {
Message.sendPrefixless("TEAM_INFO_MEMBER", player, users.stream().filter(u -> !u.isLeader()).count(), members);
}
if(!members.isEmpty())
sender.prefixless("TEAM_INFO_MEMBER", users.stream().filter(u -> !u.isLeader()).count(), members);
Set<Event> events = TeamTeilnahme.getEvents(team.getTeamId());
if(!events.isEmpty()){
Message.sendPrefixless("TEAM_INFO_EVENTS", player, events.stream().map(Event::getEventName).collect(Collectors.joining(", ")));
sender.prefixless("TEAM_INFO_EVENTS", events.stream().map(Event::getEventName).collect(Collectors.joining(", ")));
}
}
private String getMemberList(List<SteamwarUser> users, boolean leaders) {
StringBuilder sb = new StringBuilder();
for(SteamwarUser user : users) {
if(user.isLeader() == leaders) {
sb.append(playerName(user)).append(" ");
}
}
return sb.toString();
return users.stream()
.filter(user -> user.isLeader() == leaders)
.map(user -> (ProxyServer.getInstance().getPlayer(user.getUUID()) != null ? "§a" : "§e") + user.getUserName())
.collect(Collectors.joining(" "));
}
@Register("list")
public void list(ProxiedPlayer player, @Min(intValue = 1) @OptionalValue("1") @ErrorMessage("TEAM_LIST_NOT_PAGE") int page){
public void list(Chatter sender, @Min(intValue = 1) @OptionalValue("1") @ErrorMessage("TEAM_LIST_NOT_PAGE") int page){
final int TEAMS_PER_PAGE = 10;
List<Team> all = Team.getAll();
final int lastPage = ((all.size() - 1) / 10) + 1;
if(page < 1 || page > lastPage){
Message.send("TEAM_LIST_UNKNOWN_PAGE", player);
sender.system("TEAM_LIST_UNKNOWN_PAGE");
return;
}
Message.sendPrefixless("TEAM_LIST_HEADER", player, page, lastPage);
sender.system("TEAM_LIST_HEADER", page, lastPage);
for(int i = (page-1) * TEAMS_PER_PAGE; i < (page-1) * TEAMS_PER_PAGE + TEAMS_PER_PAGE && i < all.size(); i++){
Team tm = all.get(i);
Message.sendPrefixless("TEAM_LIST_TEAM", player, Message.parse("TEAM_LIST_TEAM_HOVER", player),
sender.prefixless("TEAM_LIST_TEAM", new Message("TEAM_LIST_TEAM_HOVER"),
new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/team info " + tm.getTeamKuerzel()), tm.getTeamColor(), tm.getTeamKuerzel(), tm.getTeamName());
}
TextComponent beforePage = new TextComponent("««");
BaseComponent beforePage = new TextComponent("«« ");
if(page > 1){
beforePage.setColor(ChatColor.YELLOW);
beforePage.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder(Message.parse("TEAM_LIST_PREV", player)).create()));
beforePage.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new Text(sender.parse("TEAM_LIST_PREV"))));
beforePage.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/team list " + (page - 1)));
}else
beforePage.setColor(ChatColor.DARK_GRAY);
TextComponent nextPage = new TextComponent(" " + Message.parse("TEAM_LIST_PAGE", player) +" »»");
BaseComponent nextPage = sender.parse("TEAM_LIST_PAGE");
if(page < lastPage){
nextPage.setColor(ChatColor.YELLOW);
nextPage.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder(Message.parse("TEAM_LIST_NEXT", player)).create()));
nextPage.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new Text(sender.parse("TEAM_LIST_NEXT"))));
nextPage.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/team list " + (page + 1)));
}else
nextPage.setColor(ChatColor.DARK_GRAY);
beforePage.addExtra(nextPage);
player.sendMessage(beforePage);
sender.sendMessage(ChatMessageType.SYSTEM, beforePage);
}
@Register("event")
public void event(@Validator("isInTeam") ProxiedPlayer player) {
SteamwarUser user = SteamwarUser.get(player.getUniqueId());
Team team = Team.get(user.getTeam());
public void event(@Validator("isInTeam") Chatter sender) {
Team team = Team.get(sender.user().getTeam());
Message.send("TEAM_EVENT_USAGE", player);
sender.system("TEAM_EVENT_USAGE");
Set<Event> events = TeamTeilnahme.getEvents(team.getTeamId());
if(!events.isEmpty()){
Message.send("TEAM_EVENT_HEADER", player);
DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern(Message.parse("EVENT_DATE_FORMAT", player));
sender.system("TEAM_EVENT_HEADER");
DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern(sender.parseToPlain("EVENT_DATE_FORMAT"));
for(Event e : events)
Message.sendPrefixless("TEAM_EVENT_EVENT", player, e.getStart().toLocalDateTime().format(dateFormat), e.getEventName());
sender.prefixless("TEAM_EVENT_EVENT", e.getStart().toLocalDateTime().format(dateFormat), e.getEventName());
}
}
@Register("event")
public void event(@Validator("isLeader") ProxiedPlayer player, Event event){
SteamwarUser user = SteamwarUser.get(player.getUniqueId());
Team team = Team.get(user.getTeam());
public void event(@Validator("isLeader") Chatter sender, Event event){
Team team = Team.get(sender.user().getTeam());
if(notDuringEvent(player))
if(notDuringEvent(sender))
return;
if(Instant.now().isAfter(event.getDeadline().toInstant())){
Message.send("TEAM_EVENT_OVER", player);
sender.system("TEAM_EVENT_OVER");
return;
}
if(TeamTeilnahme.nimmtTeil(team.getTeamId(), event.getEventID())){
TeamTeilnahme.notTeilnehmen(team.getTeamId(), event.getEventID());
Message.send("TEAM_EVENT_LEFT", player);
sender.system("TEAM_EVENT_LEFT");
}else{
TeamTeilnahme.teilnehmen(team.getTeamId(), event.getEventID());
Message.send("TEAM_EVENT_JOINED", player, event.getEventName());
Message.sendPrefixless("TEAM_EVENT_HOW_TO_LEAVE", player);
sender.system("TEAM_EVENT_JOINED", event.getEventName());
sender.prefixless("TEAM_EVENT_HOW_TO_LEAVE");
}
DiscordBot.withBot(bot -> bot.getEventChannel().update());
}
@Register("tp")
public void tp(@Validator("isInTeam") ProxiedPlayer player) {
SteamwarUser user = SteamwarUser.get(player.getUniqueId());
Team team = Team.get(user.getTeam());
tp(player, team);
public void tp(@Validator("isInTeam") PlayerChatter sender) {
Team team = Team.get(sender.user().getTeam());
tp(sender, team);
}
@Register("tp")
public void tp(ProxiedPlayer player, @ErrorMessage("TEAM_TP_NO_TEAM") Team targetTeam) {
public void tp(PlayerChatter sender, @ErrorMessage("TEAM_TP_NO_TEAM") Team targetTeam) {
if (targetTeam.getAddress() == null || targetTeam.getAddress().isEmpty()) {
Message.send("TEAM_NO_ADDRESS", player);
sender.system("TEAM_NO_ADDRESS");
return;
}
@ -505,52 +411,41 @@ public class TeamCommand extends SWCommand {
if (!address.equals(serverInfo.getSocketAddress())) {
serverInfo = Storage.teamServers.remove(targetTeam.getTeamId());
ProxyServer.getInstance().getServers().remove(serverInfo.getName());
tp(player, targetTeam);
tp(sender, targetTeam);
return;
}
player.connect(ServerConnectRequest.builder()
sender.getPlayer().connect(ServerConnectRequest.builder()
.target(serverInfo)
.connectTimeout(BungeeCord.getInstance().getConfig().getServerConnectTimeout())
.retry(false)
.reason(ServerConnectEvent.Reason.PLUGIN)
.callback((success, error) -> {
if (error != null) {
Message.send("TEAM_OFFLINE", player);
}
if (error != null)
sender.system("TEAM_OFFLINE");
})
.build());
/*
((UserConnection) player).connect(serverInfo, (success, error) -> {
if (error != null) {
Message.send("TEAM_OFFLINE", player);
}
}, false, ServerConnectEvent.Reason.PLUGIN, BungeeCord.getInstance().getConfig().getServerConnectTimeout(), false);
*/
}
@Register(value = "server", description = "TEAM_SERVER_USAGE")
public void server(@Validator("isLeader") ProxiedPlayer player, String server, @Min(intValue = 1) @Max(intValue = 65535) @ErrorMessage("TEAM_SERVER_PORT_INVALID") int port){
SteamwarUser user = SteamwarUser.get(player.getUniqueId());
Team team = Team.get(user.getTeam());
if (PunishmentCommand.isPunishedWithMessage(Chatter.of(player), Punishment.PunishmentType.NoTeamServer)) {
public void server(@Validator("isLeader") Chatter sender, String server, @Min(intValue = 1) @Max(intValue = 65535) @ErrorMessage("TEAM_SERVER_PORT_INVALID") int port){
Team team = Team.get(sender.user().getTeam());
if (PunishmentCommand.isPunishedWithMessage(sender, Punishment.PunishmentType.NoTeamServer)) {
return;
}
try {
if (isLocalhost(InetAddress.getByName(server))) {
Message.send("TEAM_SERVER_ADDRESS_INVALID", player);
sender.system("TEAM_SERVER_ADDRESS_INVALID");
return;
}
} catch (UnknownHostException e) {
Message.send("TEAM_SERVER_ADDRESS_INVALID", player);
sender.system("TEAM_SERVER_ADDRESS_INVALID");
return;
}
team.setAddress(server);
team.setPort(port);
Storage.teamServers.remove(team.getTeamId());
Message.send("TEAM_SERVER_SET", player);
sender.system("TEAM_SERVER_SET");
}
public static boolean isLocalhost(InetAddress addr) {
@ -566,22 +461,35 @@ public class TeamCommand extends SWCommand {
}
}
@Register("color")
public void changeColor(@Validator("isLeader") ProxiedPlayer player) {
SteamwarUser user = SteamwarUser.get(player.getUniqueId());
Team team = Team.get(user.getTeam());
private static final Map<String, Integer> COLOR_CODES = new HashMap<>();
if(notDuringEvent(player))
static {
COLOR_CODES.put("4", 1);
COLOR_CODES.put("c", 15);
COLOR_CODES.put("6", 14);
COLOR_CODES.put("e", 11);
COLOR_CODES.put("2", 2);
COLOR_CODES.put("a", 10);
COLOR_CODES.put("b", 12);
COLOR_CODES.put("3", 6);
COLOR_CODES.put("1", 4);
COLOR_CODES.put("9", 6);
COLOR_CODES.put("d", 9);
COLOR_CODES.put("5", 5);
COLOR_CODES.put("f", 15);
COLOR_CODES.put("7", 7);
COLOR_CODES.put("8", 8);
COLOR_CODES.put("0", 16);
}
@Register("color")
public void changeColor(@Validator("isLeader") PlayerChatter sender) {
Team team = Team.get(sender.user().getTeam());
if(notDuringEvent(sender))
return;
List<SWListInv.SWListEntry<String>> colors = new ArrayList<>();
COLOR_CODES.forEach(stringSWListEntry -> {
SWItem item = stringSWListEntry.getItem().clone();
item.setName(stringSWListEntry.getItem().getTitle() + Team.get(user.getTeam()).getTeamKuerzel());
colors.add(new SWListInv.SWListEntry<>(item, stringSWListEntry.getObject()));
});
SWListInv<String> inv = new SWListInv<>(player, Message.parse("TEAM_COLOR_TITLE", player), colors, (click, element) -> {});
SWListInv<String> inv = new SWListInv<>(sender, new Message("TEAM_COLOR_TITLE"), COLOR_CODES.entrySet().stream().map(entry -> new SWListInv.SWListEntry<>(new SWItem(new Message("PLAIN_STRING", "§" + entry.getKey() + team.getTeamKuerzel()), entry.getValue()), entry.getKey())).collect(Collectors.toList()), (click, element) -> {});
inv.setCallback((click, element) -> {
inv.close();
team.setTeamColor(element);
@ -593,14 +501,14 @@ public class TeamCommand extends SWCommand {
public TypeMapper<Event> eventTypeMapper() {
return new TypeMapper<Event>() {
@Override
public Event map(CommandSender commandSender, String[] previousArguments, String s) {
public Event map(Chatter sender, PreviousArguments previousArguments, String s) {
return Event.get(s);
}
@Override
public boolean validate(CommandSender sender, Event value, MessageSender messageSender) {
public boolean validate(Chatter sender, Event value, MessageSender messageSender) {
if (value == null) {
messageSender.send("TEAM_EVENT_NO_EVENT", sender);
sender.system("TEAM_EVENT_NO_EVENT");
return false;
} else {
return true;
@ -608,20 +516,17 @@ public class TeamCommand extends SWCommand {
}
@Override
public Collection<String> tabCompletes(CommandSender sender, PreviousArguments previousArguments, String s) {
public Collection<String> tabCompletes(Chatter sender, PreviousArguments previousArguments, String s) {
return Event.getComing().stream().map(Event::getEventName).collect(Collectors.toList());
}
};
}
@Validator(value = "isNotInTeam", local = true)
public TypeValidator<ProxiedPlayer> isNotInTeamValidator() {
public TypeValidator<Chatter> isNotInTeamValidator() {
return (sender, value, messageSender) -> {
if (!(sender instanceof ProxiedPlayer)) return false;
ProxiedPlayer player = (ProxiedPlayer) sender;
SteamwarUser steamwarUser = SteamwarUser.get(player.getUniqueId());
if (steamwarUser.getTeam() != 0) {
messageSender.send("TEAM_IN_TEAM");
if (sender.user().getTeam() != 0) {
sender.system("TEAM_IN_TEAM");
return false;
}
return true;
@ -629,13 +534,10 @@ public class TeamCommand extends SWCommand {
}
@Validator(value = "isInTeam", local = true)
public TypeValidator<ProxiedPlayer> isInTeamValidator() {
public TypeValidator<Chatter> isInTeamValidator() {
return (sender, value, messageSender) -> {
if (!(sender instanceof ProxiedPlayer)) return false;
ProxiedPlayer player = (ProxiedPlayer) sender;
SteamwarUser steamwarUser = SteamwarUser.get(player.getUniqueId());
if (steamwarUser.getTeam() == 0) {
messageSender.send("TEAM_NOT_IN_TEAM");
if (sender.user().getTeam() == 0) {
sender.system("TEAM_NOT_IN_TEAM");
return false;
}
return true;
@ -643,17 +545,15 @@ public class TeamCommand extends SWCommand {
}
@Validator(value = "isLeader", local = true)
public TypeValidator<ProxiedPlayer> isLeaderValidator() {
public TypeValidator<Chatter> isLeaderValidator() {
return (sender, value, messageSender) -> {
if (!(sender instanceof ProxiedPlayer)) return false;
ProxiedPlayer player = (ProxiedPlayer) sender;
SteamwarUser steamwarUser = SteamwarUser.get(player.getUniqueId());
if (steamwarUser.getTeam() == 0) {
messageSender.send("TEAM_NOT_IN_TEAM");
SteamwarUser user = sender.user();
if (user.getTeam() == 0) {
sender.system("TEAM_NOT_IN_TEAM");
return false;
}
if (!steamwarUser.isLeader()) {
messageSender.send("TEAM_NOT_LEADER");
if (!user.isLeader()) {
sender.system("TEAM_NOT_LEADER");
return false;
}
return true;
@ -665,12 +565,12 @@ public class TeamCommand extends SWCommand {
public TypeMapper<Team> team() {
return new TypeMapper<Team>() {
@Override
public Team map(CommandSender commandSender, String[] previousArguments, String s) {
public Team map(Chatter sender, PreviousArguments previousArguments, String s) {
return Team.get(s);
}
@Override
public Collection<String> tabCompletes(CommandSender sender, PreviousArguments previousArguments, String s) {
public Collection<String> tabCompletes(Chatter sender, PreviousArguments previousArguments, String s) {
return Team.getAll().stream()
.flatMap(team -> Stream.of(team.getTeamName(), team.getTeamKuerzel()))
.collect(Collectors.toList());
@ -678,27 +578,27 @@ public class TeamCommand extends SWCommand {
};
}
private boolean checkTeamName(ProxiedPlayer player, Team team, String arg){
private boolean checkTeamName(Chatter sender, Team team, String arg){
Team t = Team.get(arg);
if(t != null && t.getTeamId() != team.getTeamId()){
Message.send("TEAM_NAME_TAKEN", player);
sender.system("TEAM_NAME_TAKEN");
return true;
}
return false;
}
private boolean checkTeamKuerzel(ProxiedPlayer player, Team team, String arg){
private boolean checkTeamKuerzel(Chatter sender, Team team, String arg){
Team t = Team.get(arg);
if(t != null && (team == null || t.getTeamId() != team.getTeamId())){
Message.send("TEAM_KUERZEL_TAKEN", player);
sender.system("TEAM_KUERZEL_TAKEN");
return true;
}
return false;
}
private boolean notDuringEvent(ProxiedPlayer player){
private boolean notDuringEvent(Chatter sender){
if(Event.get() != null){
Message.send("TEAM_NOT_IN_EVENT", player);
sender.system("TEAM_NOT_IN_EVENT");
return true;
}
return false;

Datei anzeigen

@ -24,7 +24,6 @@ import de.steamwar.command.SWCommand;
import de.steamwar.messages.Chatter;
import de.steamwar.messages.ChatterGroup;
import de.steamwar.sql.SteamwarUser;
import net.md_5.bungee.api.connection.ProxiedPlayer;
public class TeamchatCommand extends SWCommand {
@ -33,8 +32,7 @@ public class TeamchatCommand extends SWCommand {
}
@Register(description = "TC_USAGE")
public void genericCommand(ProxiedPlayer player, @ErrorMessage(value = "TC_USAGE", allowEAs = false) String... args) {
Chatter sender = Chatter.of(player);
public void genericCommand(Chatter sender, @ErrorMessage(value = "TC_USAGE", allowEAs = false) String... args) {
SteamwarUser user = sender.user();
if(user.getTeam() == 0){

Datei anzeigen

@ -20,19 +20,23 @@
package de.steamwar.bungeecore.commands;
import de.steamwar.bungeecore.*;
import de.steamwar.sql.*;
import de.steamwar.bungeecore.util.BauLock;
import de.steamwar.bungeecore.util.Chat19;
import de.steamwar.command.PreviousArguments;
import de.steamwar.command.SWCommand;
import de.steamwar.command.TypeMapper;
import de.steamwar.messages.Chatter;
import de.steamwar.messages.PlayerChatter;
import de.steamwar.sql.*;
import net.md_5.bungee.BungeeCord;
import net.md_5.bungee.api.CommandSender;
import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.config.ServerInfo;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import java.util.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
public class TpCommand extends SWCommand {
@ -41,15 +45,16 @@ public class TpCommand extends SWCommand {
}
@Register
public void genericCommand(ProxiedPlayer p) {
Chatter.of(p).system(Event.get() == null ? "TP_USAGE" : "TP_USAGE_EVENT");
public void genericCommand(Chatter sender) {
sender.system(Event.get() == null ? "TP_USAGE" : "TP_USAGE_EVENT");
}
@Register
public void teleportCommand(ProxiedPlayer p, @Mapper("to") String to, String... rest) {
public void teleportCommand(PlayerChatter sender, @Mapper("to") String to, String... rest) {
ServerInfo server = getTarget(to);
//Give control of teleport command to server
ProxiedPlayer p = sender.getPlayer();
if (server == p.getServer().getInfo() || server == null) {
if (rest.length == 0) {
Chat19.chat(p, "/tp " + to);
@ -59,7 +64,7 @@ public class TpCommand extends SWCommand {
return;
}
teleport(p, server);
teleport(sender, server);
}
@Mapper("to")
@ -67,12 +72,12 @@ public class TpCommand extends SWCommand {
public TypeMapper<String> tabCompleter() {
return new TypeMapper<String>() {
@Override
public String map(CommandSender commandSender, String[] previousArguments, String s) {
public String map(Chatter sender, PreviousArguments previousArguments, String s) {
return s;
}
@Override
public Collection<String> tabCompletes(CommandSender sender, String[] previousArguments, String s) {
public Collection<String> tabCompletes(Chatter sender, PreviousArguments previousArguments, String s) {
List<String> list = new ArrayList<>();
for (ProxiedPlayer player : BungeeCord.getInstance().getPlayers()) {
list.add(player.getName());
@ -84,26 +89,23 @@ public class TpCommand extends SWCommand {
list.add(team.getTeamKuerzel());
});
}
if (Storage.teamServers.containsValue(((ProxiedPlayer) sender).getServer().getInfo())) {
Storage.directTabItems.getOrDefault((ProxiedPlayer) sender, Collections.emptyMap()).forEach((uuid, item) -> {
list.add(item.getUsername());
});
if (Storage.teamServers.containsValue(sender.getPlayer().getServer().getInfo())) {
Storage.directTabItems.getOrDefault(sender.getPlayer(), Collections.emptyMap()).forEach((uuid, item) -> list.add(item.getUsername()));
}
return list;
}
};
}
public static void teleport(ProxiedPlayer player, ServerInfo server) {
Chatter sender = Chatter.of(player);
if(CheckCommand.isChecking(player)){
public static void teleport(PlayerChatter sender, ServerInfo server) {
if(CheckCommand.isChecking(sender.getPlayer())){
sender.system("CHECK_CHECKING");
return;
}
Subserver subserver = Subserver.getSubserver(server);
if(subserver == null) {
player.connect(server);
sender.getPlayer().connect(server);
return;
}
@ -121,10 +123,10 @@ public class TpCommand extends SWCommand {
sender.system("JOIN_PLAYER_BLOCK");
return;
}
} else if (BauLock.checkNotifyLocked(SteamwarUser.get(bauserver.getOwner()), player)) {
} else if (BauLock.checkNotifyLocked(SteamwarUser.get(bauserver.getOwner()), sender)) {
return;
} else if (!bauserver.getOwner().equals(player.getUniqueId()) && BauweltMember.getBauMember(bauserver.getOwner(), player.getUniqueId()) == null) {
SubserverSystem.sendDeniedMessage(player, bauserver.getOwner());
} else if (!bauserver.getOwner().equals(sender.user().getUUID()) && BauweltMember.getBauMember(bauserver.getOwner(), sender.user().getUUID()) == null) {
SubserverSystem.sendDeniedMessage(sender, bauserver.getOwner());
sender.system("JOIN_PLAYER_BLOCK");
return;
}
@ -138,7 +140,7 @@ public class TpCommand extends SWCommand {
break;
}
SubserverSystem.sendPlayer(subserver, player);
SubserverSystem.sendPlayer(subserver, sender.getPlayer());
}
private static ServerInfo getTarget(String arg) {

Datei anzeigen

@ -28,16 +28,15 @@ import de.steamwar.bungeecore.util.Chat19;
import de.steamwar.command.SWCommand;
import de.steamwar.command.TypeValidator;
import de.steamwar.messages.Chatter;
import de.steamwar.messages.Message;
import de.steamwar.messages.PlayerChatter;
import de.steamwar.sql.SteamwarUser;
import de.steamwar.sql.Tutorial;
import de.steamwar.sql.UserPerm;
import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
@ -48,82 +47,79 @@ public class TutorialCommand extends SWCommand {
}
@Register
public void genericCommand(ProxiedPlayer player) {
openInventory(player, true, false);
public void genericCommand(PlayerChatter sender) {
openInventory(sender, true, false);
}
@Register("rate")
public void rate(ProxiedPlayer player) {
Chat19.chat(player, "/tutorial rate");
public void rate(PlayerChatter sender) {
Chat19.chat(sender.getPlayer(), "/tutorial rate");
}
@Register("rate")
public void rate(ProxiedPlayer player, int id) {
public void rate(PlayerChatter sender, int id) {
Tutorial tutorial = Tutorial.get(id);
if(tutorial == null) {
Chat19.chat(player, "/tutorial rate"); // Catch players manually entering numbers
Chat19.chat(sender.getPlayer(), "/tutorial rate"); // Catch players manually entering numbers
return;
}
rate(player, tutorial);
rate(sender, tutorial);
}
@Register(value = "create", description = "TUTORIAL_CREATE_HELP")
public void create(ProxiedPlayer player, String material, String... name) {
create(player, String.join(" ", name), material.toUpperCase());
public void create(PlayerChatter sender, String material, String... name) {
create(sender, String.join(" ", name), material.toUpperCase());
}
@Register("own")
public void own(ProxiedPlayer player) {
openInventory(player, false, true);
public void own(PlayerChatter sender) {
openInventory(sender, false, true);
}
@Register("unreleased")
public void unreleased(@Validator("unreleased") ProxiedPlayer player) {
openInventory(player, false, false);
public void unreleased(@Validator("unreleased") PlayerChatter sender) {
openInventory(sender, false, false);
}
@Validator("unreleased")
public TypeValidator<ProxiedPlayer> unreleasedChecker() {
return (sender, value, messageSender) -> (SteamwarUser.get((value).getUniqueId()).hasPerm(UserPerm.TEAM));
public TypeValidator<Chatter> unreleasedChecker() {
return (sender, value, messageSender) -> sender.user().hasPerm(UserPerm.TEAM);
}
private void openInventory(ProxiedPlayer player, boolean released, boolean own) {
SteamwarUser user = SteamwarUser.get(player.getUniqueId());
private void openInventory(PlayerChatter sender, boolean released, boolean own) {
SteamwarUser user = sender.user();
new SWStreamInv<>(
player,
Message.parse("TUTORIAL_TITLE", player),
sender,
new Message("TUTORIAL_TITLE"),
(click, tutorial) -> {
if(!released && click.isShiftClick() && user.hasPerm(UserPerm.TEAM) && user.getId() != tutorial.getCreator()) {
tutorial.release();
openInventory(player, released, own);
openInventory(sender, released, own);
return;
} else if(own && click.isShiftClick() && click.isRightClick()) {
tutorial.delete();
SubserverSystem.deleteFolder(BungeeCore.local, world(tutorial).getPath());
openInventory(player, released, own);
openInventory(sender, released, own);
return;
}
new ServerStarter().tutorial(player, tutorial).start();
new ServerStarter().tutorial(sender.getPlayer(), tutorial).start();
},
page -> (own ? Tutorial.getOwn(user.getId(), page, 45) : Tutorial.getPage(page, 45, released)).stream().map(tutorial -> new SWListInv.SWListEntry<>(getTutorialItem(player, tutorial, own), tutorial)).collect(Collectors.toList())
page -> (own ? Tutorial.getOwn(user.getId(), page, 45) : Tutorial.getPage(page, 45, released)).stream().map(tutorial -> new SWListInv.SWListEntry<>(getTutorialItem(tutorial, own), tutorial)).collect(Collectors.toList())
).open();
}
private SWItem getTutorialItem(ProxiedPlayer player, Tutorial tutorial, boolean personalHighlights) {
SWItem item = new SWItem(tutorial.getItem(), Message.parse("TUTORIAL_NAME", player, tutorial.getName()));
private SWItem getTutorialItem(Tutorial tutorial, boolean personalHighlights) {
SWItem item = new SWItem(tutorial.getItem(), new Message("TUTORIAL_NAME", tutorial.getName()));
item.setHideAttributes(true);
List<String> lore = new ArrayList<>();
lore.add(Message.parse("TUTORIAL_BY", player, SteamwarUser.get(tutorial.getCreator()).getUserName()));
lore.add(Message.parse("TUTORIAL_STARS", player, String.format("%.1f", tutorial.getStars())));
item.addLore(new Message("TUTORIAL_BY", SteamwarUser.get(tutorial.getCreator()).getUserName()));
item.addLore(new Message("TUTORIAL_STARS", String.format("%.1f", tutorial.getStars())));
if (personalHighlights)
lore.add(Message.parse("TUTORIAL_DELETE", player));
item.setLore(lore);
item.addLore(new Message("TUTORIAL_DELETE"));
if (personalHighlights && tutorial.isReleased())
item.setEnchanted(true);
@ -131,23 +127,22 @@ public class TutorialCommand extends SWCommand {
return item;
}
private void rate(ProxiedPlayer player, Tutorial tutorial) {
Chatter chatter = Chatter.of(player);
private void rate(PlayerChatter sender, Tutorial tutorial) {
int[] rates = new int[]{1, 2, 3, 4, 5};
new SWListInv<>(player, Message.parse("TUTORIAL_RATE_TITLE", player), Arrays.stream(rates).mapToObj(rate -> new SWListInv.SWListEntry<>(new SWItem("NETHER_STAR", Message.parse("TUTORIAL_RATE", player, rate)), rate)).collect(Collectors.toList()), (click, rate) -> {
tutorial.rate(chatter.user().getId(), rate);
SWInventory.close(chatter);
new SWListInv<>(sender, new Message("TUTORIAL_RATE_TITLE"), Arrays.stream(rates).mapToObj(rate -> new SWListInv.SWListEntry<>(new SWItem("NETHER_STAR", new Message("TUTORIAL_RATE", rate)), rate)).collect(Collectors.toList()), (click, rate) -> {
tutorial.rate(sender.user().getId(), rate);
SWInventory.close(sender);
}).open();
}
private void create(ProxiedPlayer player, String name, String item) {
Subserver subserver = Subserver.getSubserver(player);
SteamwarUser user = SteamwarUser.get(player.getUniqueId());
private void create(PlayerChatter sender, String name, String item) {
Subserver subserver = Subserver.getSubserver(sender.getPlayer());
SteamwarUser user = sender.user();
File tempWorld = new File(ServerStarter.TEMP_WORLD_PATH, ServerStarter.serverToWorldName(ServerStarter.bauServerName(user)));
if(subserver == null || !subserver.hasStarted() || subserver.getType() != Servertype.BAUSERVER || !tempWorld.exists()) {
Message.send("TUTORIAL_CREATE_MISSING", player);
if(subserver == null || !subserver.isStarted() || subserver.getType() != Servertype.BAUSERVER || !tempWorld.exists()) {
sender.system("TUTORIAL_CREATE_MISSING");
return;
}
@ -159,7 +154,7 @@ public class TutorialCommand extends SWCommand {
if (tutorialWorld.exists())
SubserverSystem.deleteFolder(BungeeCore.local, tutorialWorld.getPath());
ServerStarter.copyWorld(BungeeCore.local, tempWorld.getPath(), tutorialWorld.getPath());
Message.send("TUTORIAL_CREATED", player);
sender.system("TUTORIAL_CREATED");
}, 1, TimeUnit.SECONDS);
}

Datei anzeigen

@ -20,6 +20,7 @@
package de.steamwar.bungeecore.commands;
import de.steamwar.bungeecore.ArenaMode;
import de.steamwar.command.PreviousArguments;
import de.steamwar.command.SWCommandUtils;
import de.steamwar.command.TypeMapper;
import de.steamwar.command.TypeValidator;
@ -27,8 +28,6 @@ import de.steamwar.messages.Chatter;
import de.steamwar.messages.PlayerChatter;
import de.steamwar.sql.Punishment;
import lombok.experimental.UtilityClass;
import net.md_5.bungee.api.CommandSender;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import java.util.Collection;
@ -49,12 +48,12 @@ public class TypeMappers {
private static TypeMapper<ArenaMode> arenaModeTypeMapper(boolean historic) {
return new TypeMapper<ArenaMode>() {
@Override
public ArenaMode map(CommandSender commandSender, String[] previousArguments, String s) {
public ArenaMode map(Chatter sender, PreviousArguments previousArguments, String s) {
return ArenaMode.getByChat(s);
}
@Override
public Collection<String> tabCompletes(CommandSender sender, String[] previousArguments, String s) {
public Collection<String> tabCompletes(Chatter sender, PreviousArguments previousArguments, String s) {
return ArenaMode.getAllChatNames(historic);
}
};
@ -63,15 +62,15 @@ public class TypeMappers {
private static TypeMapper<String> arenaMapTypeMapper() {
return new TypeMapper<String>() {
@Override
public String map(CommandSender commandSender, String[] previousArguments, String s) {
if (previousArguments.length == 0) return null;
return ArenaMode.getByChat(previousArguments[previousArguments.length - 1]).convertToRealMapName(s);
public String map(Chatter sender, PreviousArguments previousArguments, String s) {
if (previousArguments.userArgs.length == 0) return null;
return ArenaMode.getByChat(previousArguments.userArgs[previousArguments.userArgs.length - 1]).convertToRealMapName(s);
}
@Override
public Collection<String> tabCompletes(CommandSender sender, String[] previousArguments, String s) {
if (previousArguments.length == 0) return null;
ArenaMode arenaMode = ArenaMode.getByChat(previousArguments[previousArguments.length - 1]);
public Collection<String> tabCompletes(Chatter sender, PreviousArguments previousArguments, String s) {
if (previousArguments.userArgs.length == 0) return null;
ArenaMode arenaMode = ArenaMode.getByChat(previousArguments.userArgs[previousArguments.userArgs.length - 1]);
if (arenaMode == null) return null;
return arenaMode.getMaps();
}

Datei anzeigen

@ -19,11 +19,10 @@
package de.steamwar.bungeecore.commands;
import de.steamwar.bungeecore.Message;
import de.steamwar.command.SWCommand;
import de.steamwar.messages.Chatter;
import de.steamwar.sql.IgnoreSystem;
import de.steamwar.sql.SteamwarUser;
import de.steamwar.command.SWCommand;
import net.md_5.bungee.api.connection.ProxiedPlayer;
public class UnIgnoreCommand extends SWCommand {
@ -32,19 +31,15 @@ public class UnIgnoreCommand extends SWCommand {
}
@Register(description = "UNIGNORE_USAGE")
public void genericCommand(ProxiedPlayer p, String toUnIgnore) {
SteamwarUser user = SteamwarUser.get(p.getUniqueId());
public void genericCommand(Chatter sender, @ErrorMessage("UNIGNORE_NOT_PLAYER") SteamwarUser target) {
SteamwarUser user = sender.user();
SteamwarUser target = SteamwarUser.get(toUnIgnore);
if(target == null){
Message.send("UNIGNORE_NOT_PLAYER", p);
return;
}else if(!IgnoreSystem.isIgnored(user, target)){
Message.send("UNIGNORE_NOT_IGNORED", p);
if(!IgnoreSystem.isIgnored(user, target)){
sender.system("UNIGNORE_NOT_IGNORED");
return;
}
IgnoreSystem.unIgnore(user, target);
Message.send("UNIGNORE_UNIGNORED", p, target.getUserName());
sender.system("UNIGNORE_UNIGNORED", target.getUserName());
}
}

Datei anzeigen

@ -20,14 +20,13 @@
package de.steamwar.bungeecore.commands;
import de.steamwar.bungeecore.BungeeCore;
import de.steamwar.bungeecore.Message;
import de.steamwar.bungeecore.bot.AuthManager;
import de.steamwar.sql.SteamwarUser;
import de.steamwar.bungeecore.discord.util.AuthManager;
import de.steamwar.command.SWCommand;
import net.dv8tion.jda.api.entities.Member;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import de.steamwar.messages.Chatter;
import net.dv8tion.jda.api.entities.User;
import java.util.Base64;
import java.util.logging.Level;
public class VerifyCommand extends SWCommand {
@ -36,29 +35,26 @@ public class VerifyCommand extends SWCommand {
}
@Register(description = "VERIFY_USAGE")
public void genericCommand(ProxiedPlayer sender, String code) {
public void genericCommand(Chatter sender, String code) {
byte[] bytes;
try {
bytes = Base64.getDecoder().decode(code);
} catch (IllegalArgumentException e) {
Message.send("VERIFY_INVALID", sender);
sender.system("VERIFY_INVALID");
return;
}
if(bytes.length != 16) {
Message.send("VERIFY_INVALID", sender);
sender.system("VERIFY_INVALID");
return;
}
if(bytes[0] == 'D' && bytes[1] == 'C') {
Member member = AuthManager.connectAuth(SteamwarUser.get(sender.getName()), code);
if(member != null) {
BungeeCore.log(sender.getName() + " Verified with Discorduser: " + member.getIdLong());
Message.send("VERIFY_SUCCESS", sender, member.getUser().getAsTag());
User user = AuthManager.connectAuth(sender.user(), code);
if(user != null) {
BungeeCore.get().getLogger().log(Level.INFO, sender.user().getUserName() + " Verified with Discorduser: " + user.getIdLong());
sender.system("VERIFY_SUCCESS", user.getAsTag());
} else {
Message.send("VERIFY_INVALID", sender);
}
} else {
Message.send("VERIFY_INVALID", sender);
sender.system("VERIFY_INVALID");
}
}
}

Datei anzeigen

@ -21,7 +21,6 @@ package de.steamwar.bungeecore.commands;
import de.steamwar.command.SWCommand;
import de.steamwar.messages.Chatter;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import java.io.BufferedReader;
import java.io.IOException;
@ -35,13 +34,13 @@ public class WebpasswordCommand extends SWCommand {
@Register(description = "WEB_USAGE")
public void genericCommand(ProxiedPlayer player, String password) {
public void genericCommand(Chatter sender, String password) {
if(password.length() < 8) {
Chatter.of(player).system("WEB_PASSWORD_LENGTH");
sender.system("WEB_PASSWORD_LENGTH");
return;
}
ProcessBuilder pb = new ProcessBuilder("php", "/var/www/register.php", player.getName(), password);
ProcessBuilder pb = new ProcessBuilder("php", "/var/www/register.php", sender.user().getUserName(), password);
pb.redirectErrorStream(true);
try {
Process regProcess = pb.start();
@ -49,14 +48,14 @@ public class WebpasswordCommand extends SWCommand {
String errorLine;
if((errorLine = reader.readLine()) != null) {
if ("updated".equals(errorLine)) {
Chatter.of(player).system("WEB_UPDATED");
sender.system("WEB_UPDATED");
return;
} else {
throw new SecurityException("Could not create webaccount " + errorLine);
}
}
Chatter.of(player).system("WEB_CREATED");
sender.system("WEB_CREATED");
} catch (IOException e) {
throw new SecurityException("Could not create webaccount", e);
}

Datei anzeigen

@ -19,23 +19,24 @@
package de.steamwar.bungeecore.commands;
import de.steamwar.bungeecore.Message;
import de.steamwar.messages.Message;
import de.steamwar.bungeecore.Storage;
import de.steamwar.bungeecore.mods.ModUtils;
import de.steamwar.command.PreviousArguments;
import de.steamwar.command.SWCommand;
import de.steamwar.command.SWCommandUtils;
import de.steamwar.command.TypeMapper;
import de.steamwar.messages.Chatter;
import de.steamwar.sql.*;
import lombok.AllArgsConstructor;
import lombok.Getter;
import net.md_5.bungee.BungeeCord;
import net.md_5.bungee.api.CommandSender;
import net.md_5.bungee.api.chat.ClickEvent;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.time.Instant;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@ -47,43 +48,20 @@ public class WhoisCommand extends SWCommand {
}
@Register(description = "WHOIS_USAGE")
public void genericCommand(ProxiedPlayer player, @Mapper("player") String target, WhoisParameterTypes... parameters) {
Chatter sender = Chatter.of(player);
SteamwarUser user = SteamwarUser.get(target);
if (sender.user().hasPerm(UserPerm.ADMINISTRATION)) {
if (user == null) {
try {
int id = Integer.parseInt(target);
user = SteamwarUser.get(id);
} catch (NumberFormatException ignored) {
// Ignored
}
}
if (user == null) {
try {
long id = Long.parseLong(target);
user = SteamwarUser.get(id);
} catch (NumberFormatException ignored) {
// Ignored
}
}
}
if (user == null) {
public void whois(Chatter sender, long id, WhoisParameterTypes... parameters) {
if(!sender.user().hasPerm(UserPerm.ADMINISTRATION)) {
sender.system("UNKNOWN_PLAYER");
} else {
EnumSet<WhoisParameterTypes> set = parameters.length == 0 ? EnumSet.noneOf(WhoisParameterTypes.class) : EnumSet.copyOf(Arrays.asList(parameters));
sendUserinfo(sender, user, set);
}
return;
}
@Mapper(value = "player", local = true)
public TypeMapper<String> playerTypeMapper() {
return SWCommandUtils.createMapper(s -> s, s -> BungeeCord.getInstance().getPlayers().stream().map(ProxiedPlayer::getName).collect(Collectors.toList()));
// SW ID or Discord ID
whois(sender, id < Integer.MAX_VALUE ? SteamwarUser.get((int) id) : SteamwarUser.get(id), parameters);
}
private static void sendUserinfo(Chatter sender, SteamwarUser user, EnumSet<WhoisParameterTypes> parameterTypes) {
@Register(description = "WHOIS_USAGE")
public void whois(Chatter sender, SteamwarUser user, WhoisParameterTypes... parameters) {
EnumSet<WhoisParameterTypes> parameterTypes = parameters.length == 0 ? EnumSet.noneOf(WhoisParameterTypes.class) : EnumSet.copyOf(Arrays.asList(parameters));
Team team = Team.get(user.getTeam());
sender.system("WHOIS_USERNAME", user.getUserName());
@ -145,7 +123,7 @@ public class WhoisCommand extends SWCommand {
if (!all && !punishment.isCurrent()) {
continue;
}
sender.prefixless("WHOIS_PUNISHMENT", SteamwarUser.get(punishment.getPunisher()).getUserName(), punishment.getType().name(), punishment.getBantime(punishment.getStartTime(), false), punishment.getBantime(punishment.getEndTime(), punishment.isPerma()), punishment.getReason());
sender.prefixless("WHOIS_PUNISHMENT", SteamwarUser.get(punishment.getPunisher()), punishment.getType().name(), duration(sender, punishment.getStartTime(), false), duration(sender, punishment.getEndTime(), punishment.isPerma()), punishment.getReason());
isPunished = true;
}
if (!isPunished) {
@ -153,14 +131,21 @@ public class WhoisCommand extends SWCommand {
}
}
private Message duration(Chatter sender, Timestamp timestamp, boolean perma) {
if(perma)
return new Message("PUNISHMENT_PERMA");
else
return new Message("PLAIN_STRING", timestamp.toLocalDateTime().format(DateTimeFormatter.ofPattern(sender.parseToPlain("TIMEFORMAT"))));
}
@ClassMapper(value = WhoisParameterTypes.class, local = true)
public TypeMapper<WhoisParameterTypes> argumentTypeMapper() {
WhoisParameterTypes[] values = WhoisParameterTypes.values();
return new TypeMapper<WhoisParameterTypes>() {
@Override
public WhoisParameterTypes map(CommandSender commandSender, String[] previousArguments, String s) {
SteamwarUser user = SteamwarUser.get(((ProxiedPlayer) commandSender).getUniqueId());
public WhoisParameterTypes map(Chatter sender, PreviousArguments previousArguments, String s) {
SteamwarUser user = sender.user();
return Stream.of(values)
.filter(p -> user.hasPerm(p.perm))
.filter(p -> p.getTabCompletes().contains(s))
@ -169,8 +154,8 @@ public class WhoisCommand extends SWCommand {
}
@Override
public Collection<String> tabCompletes(CommandSender commandSender, String[] previousArguments, String s) {
SteamwarUser user = SteamwarUser.get(((ProxiedPlayer) commandSender).getUniqueId());
public Collection<String> tabCompletes(Chatter sender, PreviousArguments previousArguments, String s) {
SteamwarUser user = sender.user();
return Stream.of(values)
.filter(p -> user.hasPerm(p.perm))
.flatMap(p -> p.getTabCompletes().stream())
@ -179,19 +164,13 @@ public class WhoisCommand extends SWCommand {
};
}
private enum WhoisParameterTypes {
@AllArgsConstructor
public enum WhoisParameterTypes {
ALL(Arrays.asList("-a", "-all"), UserPerm.TEAM),
MOD(Arrays.asList("-m", "-mod", "-mods"), UserPerm.MODERATION);
private final UserPerm perm;
@Getter
private List<String> tabCompletes;
WhoisParameterTypes(List<String> tabCompletes, UserPerm perm) {
this.perm = perm;
this.tabCompletes = tabCompletes;
}
private final List<String> tabCompletes;
private final UserPerm perm;
}
}

Datei anzeigen

@ -0,0 +1,208 @@
/*
This file is a part of the SteamWar software.
Copyright (C) 2020 SteamWar.de-Serverteam
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bungeecore.discord;
import de.steamwar.bungeecore.BungeeCore;
import de.steamwar.bungeecore.discord.channels.*;
import de.steamwar.bungeecore.discord.config.DiscordConfig;
import de.steamwar.bungeecore.discord.config.DiscordRole;
import de.steamwar.bungeecore.discord.config.DiscordTicketType;
import de.steamwar.bungeecore.discord.listeners.DiscordSchemUpload;
import de.steamwar.bungeecore.discord.listeners.DiscordTeamEvent;
import de.steamwar.bungeecore.discord.listeners.DiscordTicketHandler;
import de.steamwar.bungeecore.discord.listeners.ChannelListener;
import de.steamwar.bungeecore.discord.util.AuthManager;
import de.steamwar.command.SWCommand;
import de.steamwar.messages.Chatter;
import de.steamwar.sql.Event;
import lombok.Getter;
import net.dv8tion.jda.api.*;
import net.dv8tion.jda.api.entities.*;
import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent;
import net.dv8tion.jda.api.exceptions.ErrorResponseException;
import net.dv8tion.jda.api.interactions.commands.Command;
import net.dv8tion.jda.api.interactions.commands.OptionType;
import net.dv8tion.jda.api.interactions.commands.build.CommandData;
import net.dv8tion.jda.api.interactions.commands.build.OptionData;
import net.dv8tion.jda.api.interactions.components.ActionRow;
import net.dv8tion.jda.api.interactions.components.Button;
import net.dv8tion.jda.api.requests.RestAction;
import net.dv8tion.jda.api.requests.restaction.CommandListUpdateAction;
import net.dv8tion.jda.api.utils.MemberCachePolicy;
import net.md_5.bungee.api.ProxyServer;
import javax.security.auth.login.LoginException;
import java.awt.*;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.logging.Level;
public class DiscordBot {
public static final String ARGUMENT_NAME = "arguments";
@Getter
private static DiscordBot instance;
@Getter
private static final Map<String, SWCommand> commands = new HashMap<>();
public static void withBot(Consumer<DiscordBot> consumer) {
if(instance != null)
consumer.accept(instance);
}
public static Guild getGuild() {
return instance.jda.getGuildById(DiscordConfig.GUILD);
}
@Getter
private volatile DiscordChannel announcementChannel;
@Getter
private volatile DiscordChatRoom ingameChat;
@Getter
private volatile DiscordChatRoom serverTeamChat;
@Getter
private StaticMessageChannel eventChannel;
@Getter
private final JDA jda;
public DiscordBot() {
instance = this;
try {
jda = JDABuilder
.createDefault(DiscordConfig.TOKEN)
.setStatus(OnlineStatus.ONLINE)
.setMemberCachePolicy(MemberCachePolicy.ONLINE)
.build();
} catch (LoginException e) {
throw new SecurityException("Could not Login: " + DiscordConfig.TOKEN, e);
}
ProxyServer.getInstance().getScheduler().runAsync(BungeeCore.get(), this::asyncInit);
}
private void asyncInit() {
try {
jda.awaitReady();
} catch (InterruptedException e) {
BungeeCore.get().getLogger().log(Level.SEVERE, "Interrupted during JDA ready wait", e);
return;
}
activity();
new StaticMessageChannel(DiscordConfig.ROLES_CHANNEL, () -> new MessageBuilder()
.setContent(DiscordConfig.ROLES_BASE_MESSAGE)
.setActionRows(ActionRow.of(DiscordConfig.ROLES.stream().map(DiscordRole::toButton).toArray(Button[]::new))), event -> InteractionReply.reply(event, reply -> {
Member member = event.getMember();
Guild guild = event.getGuild();
Role role = guild.getRoleById(event.getComponentId());
if (member.getRoles().stream().anyMatch(role::equals)) {
guild.removeRoleFromMember(member, role).queue();
reply.system("DC_ROLE_REMOVED", role.getAsMention());
} else {
guild.addRoleToMember(member, role).queue();
reply.system("DC_ROLE_ADDED", role.getAsMention());
}
}));
new StaticMessageChannel(DiscordConfig.RULES_CHANNEL, () -> new MessageBuilder()
.setEmbeds(new EmbedBuilder()
.setDescription(String.join("\n", DiscordConfig.RULES_RULES))
.setColor(Color.GRAY)
.setAuthor("SteamWar", "https://steamwar.de")
.setTitle(DiscordConfig.RULES_TITLE)
.build())
.setActionRows(
ActionRow.of(Button.link("https://steamwar.de", "Website"), Button.link("https://steamwar.de/youtube", "YouTube")),
ActionRow.of(Button.primary("auth", Emoji.fromUnicode("U+2705")).withLabel("Minecraft verknüpfen"))
), event -> {
if(event.getComponentId().equals("auth"))
event.reply("Gebe innerhalb der nächsten 10 Minuten ``/verify " + AuthManager.createDiscordAuthToken(event.getUser()) + "`` auf dem Minecraft Server ein").setEphemeral(true).queue();
});
new StaticMessageChannel(DiscordConfig.TICKET_CHANNEL, () -> new MessageBuilder()
.setEmbeds(new EmbedBuilder()
.setDescription(DiscordConfig.TICKET_MESSAGE)
.setTitle("SteamWar Tickets")
.setColor(Color.RED)
.build())
.setActionRows(ActionRow.of(Arrays.stream(DiscordTicketType.values()).map(DiscordTicketType::toButton).toArray(Button[]::new))), DiscordTicketHandler::openTicket);
eventChannel = new StaticMessageChannel(DiscordConfig.EVENTS_CHANNEL, EventChannel::get);
StaticMessageChannel checklistChannel = new StaticMessageChannel(DiscordConfig.SCHEMATICS_CHANNEL, ChecklistChannel::get);
announcementChannel = new DiscordChannel(DiscordConfig.ANNOUNCEMENTS_CHANNEL) {
@Override
public void received(GuildMessageReceivedEvent event) {
Chatter.broadcast().system("ALERT", event.getMessage().getContentDisplay());
}
};
ingameChat = new DiscordChatRoom(DiscordConfig.INGAME_CHANNEL, "CHAT_DISCORD_GLOBAL", Chatter::broadcast);
serverTeamChat = new DiscordChatRoom(DiscordConfig.SERVER_TEAM_CHANNEL, "CHAT_SERVERTEAM", Chatter::serverteam);
ProxyServer.getInstance().getScheduler().schedule(BungeeCore.get(), () -> {
try {
activity();
eventChannel.update();
checklistChannel.update();
} catch (ErrorResponseException e) {
//ignored
}
}, 30, 30, TimeUnit.SECONDS);
Guild guild = getGuild();
commandSetup(jda.retrieveCommands(), jda.updateCommands());
commandSetup(guild.retrieveCommands(), guild.updateCommands());
jda.addEventListener(
new DiscordTicketHandler(),
new DiscordTeamEvent(),
new ChannelListener(),
new DiscordSchemUpload()
);
}
private void commandSetup(RestAction<List<Command>> existingCommands, CommandListUpdateAction updateCommands) {
existingCommands.complete().forEach(command -> command.delete().complete());
updateCommands
.addCommands(getCommands()
.keySet().stream()
.map(swCommand -> new CommandData(swCommand, "SteamWar Command").addOptions(new OptionData(OptionType.STRING, ARGUMENT_NAME, "SteamWar arguments", false)))
.toArray(CommandData[]::new))
.complete();
}
private boolean activityToggle = false;
private void activity() {
if(activityToggle) {
Event event = Event.get();
jda.getPresence().setActivity(event != null ? Activity.competing("dem Event " + event.getEventName()) : Activity.playing("auf SteamWar.de"));
} else {
int count = ProxyServer.getInstance().getOnlineCount();
jda.getPresence().setActivity(Activity.playing(count == 1 ? "mit 1 Spieler" : ("mit " + count + " Spielern")));
}
activityToggle = !activityToggle;
}
}

Datei anzeigen

@ -17,39 +17,24 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bungeecore.bot.events;
package de.steamwar.bungeecore.discord.channels;
import de.steamwar.bungeecore.bot.SteamwarDiscordBot;
import de.steamwar.bungeecore.bot.config.SteamwarDiscordBotConfig;
import de.steamwar.bungeecore.commands.CheckCommand;
import de.steamwar.sql.SteamwarUser;
import lombok.experimental.UtilityClass;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.MessageBuilder;
import net.dv8tion.jda.api.entities.Message;
import net.dv8tion.jda.api.entities.TextChannel;
import java.awt.*;
@UtilityClass
public class SchematicsManager {
public class ChecklistChannel {
private Message message;
private TextChannel textChannel;
static {
textChannel = SteamwarDiscordBot.instance().getJda().getGuildById(SteamwarDiscordBotConfig.GUILD).getTextChannelById(SteamwarDiscordBotConfig.SCHEMATICS_CHANNEL);
assert textChannel != null;
if(textChannel.hasLatestMessage()) {
message = textChannel.getIterableHistory().complete().stream().filter(m -> m.getAuthor().isBot()).findFirst().orElse(null);
}
}
public void update() {
EmbedBuilder embedBuilder = new EmbedBuilder();
embedBuilder.setColor(Color.GRAY);
embedBuilder.setTitle("Check List");
embedBuilder.setAuthor("SteamWar", "https://www.steamwar.de");
public MessageBuilder get() {
EmbedBuilder embedBuilder = new EmbedBuilder()
.setColor(Color.GRAY)
.setTitle("Check List")
.setAuthor("SteamWar", "https://www.steamwar.de");
CheckCommand.getSchemsToCheck().forEach(schematic -> {
StringBuilder st = new StringBuilder();
@ -62,12 +47,6 @@ public class SchematicsManager {
embedBuilder.addField(schematic.getName(), st.toString(), true);
});
MessageBuilder messageBuilder = new MessageBuilder();
messageBuilder.setEmbeds(embedBuilder.build());
if (message == null) {
textChannel.sendMessage(messageBuilder.build()).queue(message1 -> message = message1);
} else {
message.editMessage(messageBuilder.build()).queue();
}
return StaticMessageChannel.toMessageBuilder(embedBuilder);
}
}

Datei anzeigen

@ -0,0 +1,103 @@
/*
* This file is a part of the SteamWar software.
*
* Copyright (C) 2024 SteamWar.de-Serverteam
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bungeecore.discord.channels;
import de.steamwar.messages.Message;
import de.steamwar.bungeecore.discord.DiscordBot;
import de.steamwar.bungeecore.discord.listeners.ChannelListener;
import de.steamwar.messages.Chatter;
import de.steamwar.sql.SteamwarUser;
import lombok.AllArgsConstructor;
import lombok.Getter;
import net.dv8tion.jda.api.MessageBuilder;
import net.dv8tion.jda.api.entities.MessageChannel;
import net.dv8tion.jda.api.entities.User;
import net.dv8tion.jda.api.events.interaction.GenericComponentInteractionCreateEvent;
import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent;
import net.md_5.bungee.api.ChatMessageType;
import net.md_5.bungee.api.chat.BaseComponent;
@AllArgsConstructor
public class DiscordChannel extends Chatter.PlayerlessChatter {
public static SteamwarUser userOrPublic(User dcUser) {
SteamwarUser user = SteamwarUser.get(dcUser.getIdLong());
return user != null ? user : SteamwarUser.get(0);
}
private final SteamwarUser user;
@Getter
private final MessageChannel channel;
public DiscordChannel(User user) {
this(userOrPublic(user), user.openPrivateChannel().complete());
}
public DiscordChannel(SteamwarUser user) {
this(user, DiscordBot.getInstance().getJda().getUserById(user.getDiscordId()).openPrivateChannel().complete());
}
public DiscordChannel(String channel) {
this(SteamwarUser.get(-1), DiscordBot.getGuild().getTextChannelById(channel));
ChannelListener.getChannels().put(this.channel, this);
}
public void send(String message) {
send(new MessageBuilder()
.append(message
.replace("&", "")
.replace("@everyone", "`@everyone`")
.replace("@here", "`@here`")
.replaceAll("<[@#]!?\\d+>", "`$0`")));
}
public void send(MessageBuilder builder) {
channel.sendMessage(builder.build()).queue();
}
public void received(GuildMessageReceivedEvent event) {
event.getMessage().delete().queue();
}
public void received(GenericComponentInteractionCreateEvent event) {
//ignored
}
@Override
public SteamwarUser user() {
return user;
}
@Override
public boolean chatShown() {
return true;
}
@Override
public BaseComponent parse(boolean prefixed, Message message) {
return super.parse(false, message);
}
@Override
public void sendMessage(ChatMessageType type, BaseComponent msg) {
send(msg.toPlainText());
}
}

Datei anzeigen

@ -0,0 +1,53 @@
/*
* This file is a part of the SteamWar software.
*
* Copyright (C) 2024 SteamWar.de-Serverteam
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bungeecore.discord.channels;
import de.steamwar.bungeecore.listeners.ChatListener;
import de.steamwar.messages.Chatter;
import de.steamwar.messages.ChatterGroup;
import de.steamwar.sql.Punishment;
import de.steamwar.sql.SteamwarUser;
import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent;
import java.util.function.Supplier;
public class DiscordChatRoom extends DiscordChannel {
private final String format;
private final Supplier<ChatterGroup> target;
public DiscordChatRoom(String channel, String format, Supplier<ChatterGroup> target) {
super(channel);
this.format = format;
this.target = target;
}
@Override
public void received(GuildMessageReceivedEvent event) {
SteamwarUser user = SteamwarUser.get(event.getAuthor().getIdLong());
if (user == null || event.getMessage().getContentRaw().length() > 250 || user.isPunished(Punishment.PunishmentType.Ban) || user.isPunished(Punishment.PunishmentType.Mute)) {
event.getMessage().delete().queue();
return;
}
ChatListener.sendChat(Chatter.of(user), target.get(), format, null, event.getMessage().getContentDisplay().replace('§', '&').replace('\n', ' '));
event.getMessage().delete().queue();
}
}

Datei anzeigen

@ -17,20 +17,16 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bungeecore.bot.events;
package de.steamwar.bungeecore.discord.channels;
import de.steamwar.bungeecore.bot.SteamwarDiscordBot;
import de.steamwar.bungeecore.bot.config.SteamwarDiscordBotConfig;
import de.steamwar.sql.Event;
import de.steamwar.sql.EventFight;
import de.steamwar.sql.Team;
import de.steamwar.sql.TeamTeilnahme;
import de.steamwar.sql.Event;
import lombok.experimental.UtilityClass;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.MessageBuilder;
import net.dv8tion.jda.api.entities.Emoji;
import net.dv8tion.jda.api.entities.Message;
import net.dv8tion.jda.api.entities.TextChannel;
import net.dv8tion.jda.api.interactions.components.ActionRow;
import net.dv8tion.jda.api.interactions.components.selections.SelectionMenu;
@ -42,38 +38,28 @@ import java.util.List;
import java.util.stream.Collectors;
@UtilityClass
public class EventManager {
public class EventChannel {
private Message message;
private TextChannel textChannel;
public MessageBuilder get() {
if (Event.get() == null)
return updateComing();
static {
textChannel = SteamwarDiscordBot.instance().getJda().getGuildById(SteamwarDiscordBotConfig.GUILD).getTextChannelById(SteamwarDiscordBotConfig.EVENTS_CHANNEL);
assert textChannel != null;
if(textChannel.hasLatestMessage()) {
message = textChannel.getIterableHistory().complete().stream().filter(m -> m.getAuthor().isBot()).findFirst().orElse(null);
}
return updateCurrent();
}
public void update() {
if (Event.get() == null) {
updateComing();
} else {
updateCurrent();
}
}
private MessageBuilder updateComing() {
EmbedBuilder embedBuilder = new EmbedBuilder()
.setColor(Color.GRAY)
.setTitle("Zukünftige Events")
.setAuthor("SteamWar", "https://www.steamwar.de");
private void updateComing() {
EmbedBuilder embedBuilder = new EmbedBuilder();
embedBuilder.setColor(Color.GRAY);
embedBuilder.setTitle("Zukünftige Events");
embedBuilder.setAuthor("SteamWar", "https://www.steamwar.de");
Timestamp now = Timestamp.from(Instant.now());
SelectionMenu.Builder menuBuilder = SelectionMenu.create("eventName");
menuBuilder.setPlaceholder("Wähle ein Event aus!")
SelectionMenu.Builder menuBuilder = SelectionMenu.create("eventName")
.setPlaceholder("Wähle ein Event aus!")
.setMinValues(1)
.setMaxValues(1);
Timestamp now = Timestamp.from(Instant.now());
List<Event> events = Event.getComing();
events.forEach(event -> {
StringBuilder st = new StringBuilder();
@ -91,25 +77,21 @@ public class EventManager {
}
});
MessageBuilder messageBuilder = new MessageBuilder();
messageBuilder.setEmbeds(embedBuilder.build());
MessageBuilder messageBuilder = new MessageBuilder()
.setEmbeds(embedBuilder.build());
if(events.stream().anyMatch(event -> event.getDeadline().after(Timestamp.from(Instant.now())))) {
messageBuilder.setActionRows(ActionRow.of(menuBuilder.build()));
}
if (message == null) {
message = textChannel.sendMessage(messageBuilder.build()).complete();
} else {
message.editMessage(messageBuilder.build()).complete();
}
return messageBuilder;
}
private void updateCurrent() {
private MessageBuilder updateCurrent() {
Event event = Event.get();
if (event == null) return;
EmbedBuilder embedBuilder = new EmbedBuilder();
embedBuilder.setColor(Color.GRAY);
embedBuilder.setTitle("Event: " + event.getEventName());
embedBuilder.setAuthor("SteamWar", "https://www.steamwar.de");
EmbedBuilder embedBuilder = new EmbedBuilder()
.setColor(Color.GRAY)
.setTitle("Event: " + event.getEventName())
.setAuthor("SteamWar", "https://www.steamwar.de");
Instant now = Instant.now();
EventFight.getEvent(event.getEventID()).forEach(eventFight -> {
@ -131,13 +113,7 @@ public class EventManager {
embedBuilder.addField(teamBlue.getTeamKuerzel() + " vs. " + teamRed.getTeamKuerzel(), st.toString(), true);
});
MessageBuilder messageBuilder = new MessageBuilder();
messageBuilder.setEmbeds(embedBuilder.build());
if (message == null) {
textChannel.sendMessage(messageBuilder.build()).queue(message1 -> message = message1);
} else {
message.editMessage(messageBuilder.build()).complete();
}
return StaticMessageChannel.toMessageBuilder(embedBuilder);
}
}

Datei anzeigen

@ -0,0 +1,65 @@
/*
* This file is a part of the SteamWar software.
*
* Copyright (C) 2024 SteamWar.de-Serverteam
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bungeecore.discord.channels;
import net.dv8tion.jda.api.interactions.Interaction;
import net.md_5.bungee.api.ChatMessageType;
import net.md_5.bungee.api.chat.BaseComponent;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
public class InteractionReply extends DiscordChannel {
public static void reply(Interaction interaction, Consumer<InteractionReply> consumer) {
InteractionReply reply = new InteractionReply(interaction);
consumer.accept(reply);
reply.submit();
}
private final Interaction interaction;
private boolean replied = false;
private final List<String> messages = new ArrayList<>();
private InteractionReply(Interaction interaction) {
super(interaction.getUser());
this.interaction = interaction;
}
@Override
public void sendMessage(ChatMessageType type, BaseComponent msg) {
if(replied) {
super.sendMessage(type, msg);
return;
}
messages.add(msg.toPlainText());
}
public void submit() {
(messages.isEmpty() ?
interaction.deferReply() :
interaction.reply(String.join("\n", messages))
).setEphemeral(true).queue();
replied = true;
}
}

Datei anzeigen

@ -0,0 +1,69 @@
/*
* This file is a part of the SteamWar software.
*
* Copyright (C) 2024 SteamWar.de-Serverteam
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bungeecore.discord.channels;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.MessageBuilder;
import net.dv8tion.jda.api.entities.Message;
import net.dv8tion.jda.api.events.interaction.GenericComponentInteractionCreateEvent;
import java.util.function.Consumer;
import java.util.function.Supplier;
public class StaticMessageChannel extends DiscordChannel {
public static MessageBuilder toMessageBuilder(EmbedBuilder embedBuilder) {
MessageBuilder messageBuilder = new MessageBuilder();
messageBuilder.setEmbeds(embedBuilder.build());
return messageBuilder;
}
private Message message;
private final Supplier<MessageBuilder> supplier;
private final Consumer<GenericComponentInteractionCreateEvent> interaction;
public StaticMessageChannel(String channel, Supplier<MessageBuilder> supplier) {
this(channel, supplier, event -> {});
}
public StaticMessageChannel(String channel, Supplier<MessageBuilder> supplier, Consumer<GenericComponentInteractionCreateEvent> interaction) {
super(channel);
this.supplier = supplier;
this.interaction = interaction;
if(getChannel().hasLatestMessage())
message = getChannel().getIterableHistory().complete().stream().filter(m -> m.getAuthor().isBot()).findFirst().orElse(null);
update();
}
public void update() {
if (message == null) {
getChannel().sendMessage(supplier.get().build()).queue(m -> message = m);
} else {
message.editMessage(supplier.get().build()).queue();
}
}
@Override
public void received(GenericComponentInteractionCreateEvent event) {
interaction.accept(event);
}
}

Datei anzeigen

@ -17,17 +17,24 @@
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bungeecore.bot.config;
package de.steamwar.bungeecore.discord.config;
import de.steamwar.bungeecore.BungeeCore;
import de.steamwar.sql.UserPerm;
import lombok.experimental.UtilityClass;
import net.md_5.bungee.config.Configuration;
import net.md_5.bungee.config.ConfigurationProvider;
import net.md_5.bungee.config.YamlConfiguration;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class SteamwarDiscordBotConfig {
@UtilityClass
public class DiscordConfig {
public static boolean loaded = false;
public static String TOKEN;
@ -39,20 +46,26 @@ public class SteamwarDiscordBotConfig {
public static String SCHEMATICS_CHANNEL;
public static String ROLES_CHANNEL;
public static String ROLES_BASE_MESSAGE;
public static String ROLES_ADDED;
public static String ROLES_REMOVED;
public static List<DiscordRole> ROLES;
public static final List<DiscordRole> ROLES = new ArrayList<>();
public static String RULES_CHANNEL;
public static String RULES_TITLE;
public static List<String> RULES_RULES;
public static List<DiscordRulesLink> RULES_LINKS;
public static String TICKET_CATEGORY;
public static String TICKET_CHANNEL;
public static String TICKET_MESSAGE;
public static String TICKET_CREATED;
public static String TICKET_LOG;
public static Map<String, DiscordTicketType> TICKET_TYPES;
public static Map<UserPerm, String> RANKS;
public static final Map<UserPerm, String> RANKS = new HashMap<>();
static {
File file = new File(System.getProperty("user.home"), "discord.yml");
if(file.exists() && !BungeeCore.EVENT_MODE) {
try {
DiscordConfig.loadConfig(ConfigurationProvider.getProvider(YamlConfiguration.class).load(file));
} catch (IOException e) {
throw new SecurityException("Could not load discord bot configuration", e);
}
}
}
public static void loadConfig(Configuration config) {
TOKEN = config.getString("token");
@ -65,9 +78,6 @@ public class SteamwarDiscordBotConfig {
Configuration rolesSection = config.getSection("roles-claim");
ROLES_CHANNEL = rolesSection.getString("channel");
ROLES_BASE_MESSAGE = rolesSection.getString("base");
ROLES_ADDED = rolesSection.getString("added");
ROLES_REMOVED = rolesSection.getString("removed");
ROLES = new ArrayList<>();
for (String roles : rolesSection.getSection("roles").getKeys()) {
Configuration role = rolesSection.getSection("roles").getSection(roles);
@ -81,32 +91,12 @@ public class SteamwarDiscordBotConfig {
RULES_TITLE = rulesSection.getString("title");
RULES_RULES = rulesSection.getStringList("rules");
RULES_LINKS = new ArrayList<>();
for (String links : rulesSection.getSection("links").getKeys()) {
Configuration link = rulesSection.getSection("links").getSection(links);
RULES_LINKS.add(new DiscordRulesLink(link.getString("label"),
link.getString("url")));
}
Configuration ticketSection = config.getSection("tickets");
TICKET_CATEGORY = ticketSection.getString("category");
TICKET_CHANNEL = ticketSection.getString("channel");
TICKET_MESSAGE = ticketSection.getString("message");
TICKET_CREATED = ticketSection.getString("created");
TICKET_LOG = ticketSection.getString("log");
TICKET_TYPES = new HashMap<>();
for (String types : ticketSection.getSection("types").getKeys()) {
Configuration type = ticketSection.getSection("types").getSection(types);
TICKET_TYPES.put(types, new DiscordTicketType(types,
type.getString("emoji"),
type.getString("label"),
type.getString("color"),
type.getString("pre")));
}
RANKS = new HashMap<>();
Configuration ranksSections = config.getSection("ranks");
for (String type : ranksSections.getKeys()) {
RANKS.put(UserPerm.valueOf(type.toUpperCase()), ranksSections.getString(type));

Datei anzeigen

@ -17,7 +17,7 @@
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bungeecore.bot.config;
package de.steamwar.bungeecore.discord.config;
import lombok.AllArgsConstructor;
import lombok.Data;

Datei anzeigen

@ -17,25 +17,30 @@
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bungeecore.bot.config;
package de.steamwar.bungeecore.discord.config;
import lombok.AllArgsConstructor;
import lombok.Data;
import net.dv8tion.jda.api.entities.Emoji;
import net.dv8tion.jda.api.interactions.components.Button;
import net.dv8tion.jda.api.interactions.components.ButtonStyle;
@Data
@AllArgsConstructor
public class DiscordTicketType {
public enum DiscordTicketType {
REPORT("U+1F46E", "Spieler melden", ButtonStyle.DANGER),
IDEA("U+1F4A1", "Feature vorschlagen", ButtonStyle.SUCCESS),
BUG("U+1F41B", "Bug melden", ButtonStyle.SECONDARY),
QUESTION("U+2753", "Fragen", ButtonStyle.PRIMARY),
APPEAL("U+1F528", "Entbannungsantrag", ButtonStyle.SECONDARY);
private String key;
private String emoji;
private String label;
private String color;
private String preMessage;
private final String emoji;
private final String label;
private final ButtonStyle style;
public Button toButton() {
return Button.of(ButtonStyle.valueOf(color), key, Emoji.fromUnicode(emoji)).withLabel(label);
return Button.of(style, name().toLowerCase(), Emoji.fromUnicode(emoji)).withLabel(label);
}
public String introduction() {
return "DC_TICKETINTRO_" + name();
}
}

Datei anzeigen

@ -0,0 +1,83 @@
/*
* This file is a part of the SteamWar software.
* <p>
* Copyright (C) 2021 SteamWar.de-Serverteam
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* <p>
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
* <p>
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bungeecore.discord.listeners;
import de.steamwar.bungeecore.discord.DiscordBot;
import de.steamwar.bungeecore.discord.channels.DiscordChannel;
import de.steamwar.bungeecore.discord.channels.InteractionReply;
import de.steamwar.bungeecore.listeners.ConnectionListener;
import de.steamwar.command.SWCommand;
import lombok.Getter;
import net.dv8tion.jda.api.entities.ChannelType;
import net.dv8tion.jda.api.entities.MessageChannel;
import net.dv8tion.jda.api.events.interaction.GenericComponentInteractionCreateEvent;
import net.dv8tion.jda.api.events.interaction.SlashCommandEvent;
import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
import net.dv8tion.jda.api.interactions.InteractionType;
import org.jetbrains.annotations.NotNull;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class ChannelListener extends ListenerAdapter {
@Getter
private static final Map<MessageChannel, DiscordChannel> channels = new HashMap<>();
@Override
public void onGuildMessageReceived(@NotNull GuildMessageReceivedEvent event) {
if(event.getAuthor().isBot())
return;
DiscordChannel channel = channels.get(event.getChannel());
if(channel != null)
channel.received(event);
}
@Override
public void onGenericComponentInteractionCreate(@NotNull GenericComponentInteractionCreateEvent event) {
if(event.getType() != InteractionType.COMPONENT)
return;
DiscordChannel channel = channels.get(event.getChannel());
if(channel != null) {
channel.received(event);
return;
}
if(event.getChannelType() == ChannelType.PRIVATE && event.getComponentId().equals("tada"))
event.reply(":tada:").queue();
}
@Override
public void onSlashCommand(@NotNull SlashCommandEvent event) {
InteractionReply.reply(event, sender -> {
if(sender.user().getDiscordId() == null)
return;
SWCommand command = DiscordBot.getCommands().get(event.getName());
String permission = command.getPermission();
if(permission != null && sender.user().perms().stream().noneMatch(perm -> Arrays.asList(ConnectionListener.getCommandPermissions().getOrDefault(perm, new String[0])).contains(permission)))
return;
command.execute(sender, event.getOption(DiscordBot.ARGUMENT_NAME).getAsString().split(" "));
});
}
}

Datei anzeigen

@ -0,0 +1,90 @@
/*
* This file is a part of the SteamWar software.
*
* Copyright (C) 2024 SteamWar.de-Serverteam
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bungeecore.discord.listeners;
import de.steamwar.bungeecore.BungeeCore;
import de.steamwar.bungeecore.discord.channels.DiscordChannel;
import de.steamwar.sql.NodeData;
import de.steamwar.sql.Punishment;
import de.steamwar.sql.SchematicNode;
import de.steamwar.sql.SteamwarUser;
import net.dv8tion.jda.api.entities.Message;
import net.dv8tion.jda.api.events.message.priv.PrivateMessageReceivedEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.logging.Level;
public class DiscordSchemUpload extends ListenerAdapter {
private static final List<String> SCHEM_FILE_ENDINGS = Arrays.asList(".schem", ".schematic");
@Override
public void onPrivateMessageReceived(PrivateMessageReceivedEvent event) {
Message message = event.getMessage();
if(message.getAttachments().isEmpty())
return;
DiscordChannel sender = new DiscordChannel(event.getAuthor());
SteamwarUser user = sender.user();
if(user.getId() == 0) {
sender.system("DC_UNLINKED");
return;
}
if(user.isPunished(Punishment.PunishmentType.NoSchemReceiving)) {
sender.system("DC_SCHEMUPLOAD_NOPERM");
return;
}
for (Message.Attachment attachment : message.getAttachments()) {
String fileName = attachment.getFileName();
int dot = fileName.lastIndexOf('.');
if(dot == -1 || !SCHEM_FILE_ENDINGS.contains(fileName.substring(dot).toLowerCase())) {
sender.system("DC_SCHEMUPLOAD_IGNORED", attachment.getFileName());
continue;
}
String name = fileName.substring(0, dot);
if(SchematicNode.invalidSchemName(new String[] {name})) {
sender.system("DC_SCHEMUPLOAD_INVCHAR", name);
continue;
}
SchematicNode node = SchematicNode.getSchematicNode(user.getId(), name, (Integer) null);
if(node == null)
node = SchematicNode.createSchematic(user.getId(), name, null);
try (InputStream in = attachment.retrieveInputStream().get()) {
NodeData.get(node).saveFromStream(in, fileName.substring(dot).equalsIgnoreCase(".schem"));
sender.system("DC_SCHEMUPLOAD_SUCCESS", name);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} catch (ExecutionException | IOException e) {
BungeeCore.get().getLogger().log(Level.SEVERE, "Could not upload schem \"" + name + "\" for user \"" + user.getUserName() + "\"", e);
sender.system("DC_SCHEMUPLOAD_ERROR", name);
}
}
}
}

Datei anzeigen

@ -0,0 +1,65 @@
/*
This file is a part of the SteamWar software.
Copyright (C) 2020 SteamWar.de-Serverteam
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bungeecore.discord.listeners;
import de.steamwar.bungeecore.BungeeCore;
import de.steamwar.bungeecore.discord.channels.InteractionReply;
import de.steamwar.bungeecore.discord.config.DiscordConfig;
import de.steamwar.sql.Event;
import net.dv8tion.jda.api.events.interaction.SelectionMenuEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
import org.jetbrains.annotations.NotNull;
public class DiscordTeamEvent extends ListenerAdapter {
@Override
public void onSelectionMenu(@NotNull SelectionMenuEvent event) {
if(!event.getChannel().getId().equals(DiscordConfig.EVENTS_CHANNEL))
return;
if(event.getSelectedOptions().isEmpty()) {
event.deferReply(true).queue();
return;
}
InteractionReply.reply(event, reply -> {
int eventId;
try {
eventId = Integer.parseInt(event.getSelectedOptions().get(0).getValue());
} catch (NumberFormatException e) {
reply.system("UNKNOWN_EVENT");
return;
}
if(reply.user().getId() == 0) {
reply.system("DC_UNLINKED");
return;
}
Event tournament = Event.get(eventId);
if(tournament == null){
reply.system("UNKNOWN_EVENT");
return;
}
BungeeCore.get().getTeamCommand().event(reply, tournament);
});
}
}

Datei anzeigen

@ -0,0 +1,157 @@
/*
This file is a part of the SteamWar software.
Copyright (C) 2020 SteamWar.de-Serverteam
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bungeecore.discord.listeners;
import de.steamwar.messages.Message;
import de.steamwar.bungeecore.discord.channels.DiscordChannel;
import de.steamwar.bungeecore.discord.channels.InteractionReply;
import de.steamwar.bungeecore.discord.config.DiscordConfig;
import de.steamwar.bungeecore.discord.config.DiscordTicketType;
import de.steamwar.messages.Chatter;
import de.steamwar.messages.ChatterGroup;
import de.steamwar.sql.SteamwarUser;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.MessageBuilder;
import net.dv8tion.jda.api.Permission;
import net.dv8tion.jda.api.entities.Emoji;
import net.dv8tion.jda.api.entities.TextChannel;
import net.dv8tion.jda.api.entities.User;
import net.dv8tion.jda.api.events.interaction.GenericComponentInteractionCreateEvent;
import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
import net.dv8tion.jda.api.interactions.components.ActionRow;
import net.dv8tion.jda.api.interactions.components.Button;
import net.md_5.bungee.api.chat.ClickEvent;
import org.jetbrains.annotations.NotNull;
import java.awt.*;
import java.time.Instant;
import java.util.LinkedList;
import java.util.stream.Collectors;
public class DiscordTicketHandler extends ListenerAdapter {
public static void openTicket(GenericComponentInteractionCreateEvent event) {
DiscordTicketType ticketType = DiscordTicketType.valueOf(event.getComponentId().toUpperCase());
SteamwarUser user = SteamwarUser.get(event.getUser().getIdLong());
TextChannel ticketChannel = event.getGuild().getCategoryById(DiscordConfig.TICKET_CATEGORY).createTextChannel((user == null ? event.getUser().getName() : user.getUserName()) + "-" + event.getComponentId() + "-" + System.currentTimeMillis() % 1000).complete();
ticketChannel.createPermissionOverride(event.getMember()).setAllow(
Permission.VIEW_CHANNEL,
Permission.MESSAGE_WRITE,
Permission.MESSAGE_ATTACH_FILES,
Permission.MESSAGE_ADD_REACTION,
Permission.MESSAGE_READ,
Permission.MESSAGE_EMBED_LINKS,
Permission.MESSAGE_HISTORY).complete();
ticketChannel.getManager().setTopic(event.getUser().getId()).complete();
DiscordChannel channel = new DiscordChannel(DiscordChannel.userOrPublic(event.getUser()), ticketChannel);
channel.send(new MessageBuilder()
.setEmbeds(new EmbedBuilder()
.setTitle(channel.parseToPlain("DC_TICKET_TITLE"))
.setDescription(channel.parseToPlain(ticketType.introduction()))
.setColor(Color.GREEN)
.build())
.setActionRows(ActionRow.of(Button.danger("close-" + ticketChannel.getName(), channel.parseToPlain("DC_TICKET_CLOSE")).withEmoji(Emoji.fromUnicode("U+26A0")))));
InteractionReply.reply(event, reply -> reply.system("DC_TICKET_CREATED", ticketChannel.getAsMention()));
Chatter.serverteam().prefixless("DISCORD_TICKET_NEW", ticketChannel.getName());
}
@Override
public void onGenericComponentInteractionCreate(@NotNull GenericComponentInteractionCreateEvent event) {
TextChannel channel = event.getTextChannel();
if(channel.getParent() != null && channel.getParent().getId().equals(DiscordConfig.TICKET_CATEGORY) && event.getComponentId().startsWith("close-")) {
LinkedList<StringBuilder> messages = channel.getIterableHistory().complete().stream()
.filter(message -> !message.getAuthor().isSystem() && !message.getAuthor().isBot())
.map(message -> {
StringBuilder stringBuilder = new StringBuilder()
.append("<t:").append(message.getTimeCreated().toInstant().getEpochSecond()).append("> ")
.append("**").append(message.getAuthor().getName()).append("**: ")
.append(message.getContentRaw())
.append("\n");
if(!message.getAttachments().isEmpty()) {
message.getAttachments().forEach(attachment -> stringBuilder.append(attachment.getUrl()));
stringBuilder.append("\n");
}
return stringBuilder;
})
.collect(Collectors.toCollection(LinkedList::new));
messages.add(new StringBuilder().append("<t:").append(Instant.now().getEpochSecond()).append("> **").append(event.getUser().getName()).append("**: Ticket closed"));
LinkedList<StringBuilder> messageBuilders = new LinkedList<>();
messageBuilders.add(new StringBuilder());
messages.descendingIterator()
.forEachRemaining(stringBuilder -> {
if(stringBuilder.length() >= 4096) {
messageBuilders.getLast().append(stringBuilder.substring(0, 4090));
messageBuilders.add(new StringBuilder(stringBuilder.substring(4090, stringBuilder.length() - 1)));
} else if (stringBuilder.length() + messageBuilders.getLast().length() >= 4096) {
messageBuilders.add(new StringBuilder(stringBuilder.toString()));
} else {
messageBuilders.getLast().append(stringBuilder);
}
});
EmbedBuilder embedBuilder = new EmbedBuilder()
.setColor(Color.GREEN)
.setTimestamp(Instant.now())
.setTitle(event.getTextChannel().getName());
if(channel.getTopic() != null && !channel.getTopic().isEmpty()) {
User user = event.getJDA().retrieveUserById(channel.getTopic()).complete();
embedBuilder.setAuthor(user.getName(), null, user.getAvatarUrl());
}
TextChannel logChannel = event.getGuild().getTextChannelById(DiscordConfig.TICKET_LOG);
messageBuilders.forEach(stringBuilder -> logChannel.sendMessage(new MessageBuilder().setEmbeds(embedBuilder.setDescription(stringBuilder.toString()).build()).build()).queue());
Chatter.serverteam().prefixless("DISCORD_TICKET_CLOSED", channel.getName());
channel.delete().reason("Closed").queue();
}
}
@Override
public void onGuildMessageReceived(@NotNull GuildMessageReceivedEvent event) {
TextChannel channel = event.getChannel();
if(
channel.getParent() != null &&
channel.getParent().getId().equals(DiscordConfig.TICKET_CATEGORY) &&
!channel.getId().equals(DiscordConfig.TICKET_CHANNEL) &&
!channel.getId().equals(DiscordConfig.TICKET_LOG)
) {
if(event.getAuthor().isBot())
return;
ChatterGroup receivers = Chatter.serverteam();
try {
receivers = new ChatterGroup(receivers, Chatter.of(SteamwarUser.get(Long.parseLong(channel.getTopic()))));
} catch(NumberFormatException e) {
//ignored
}
receivers.system("DISCORD_TICKET_MESSAGE", new Message("DISCORD_TICKET_HOVER"), new ClickEvent(ClickEvent.Action.OPEN_URL, event.getMessage().getJumpUrl()), event.getChannel().getName(), event.getAuthor().getName(), event.getMessage().getContentRaw());
}
}
}

Datei anzeigen

@ -0,0 +1,72 @@
/*
* This file is a part of the SteamWar software.
*
* Copyright (C) 2024 SteamWar.de-Serverteam
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bungeecore.discord.util;
import de.steamwar.bungeecore.BungeeCore;
import de.steamwar.bungeecore.discord.channels.DiscordChannel;
import de.steamwar.sql.SteamwarUser;
import lombok.experimental.UtilityClass;
import net.dv8tion.jda.api.MessageBuilder;
import net.dv8tion.jda.api.entities.Emoji;
import net.dv8tion.jda.api.entities.User;
import net.dv8tion.jda.api.interactions.components.ActionRow;
import net.dv8tion.jda.api.interactions.components.Button;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
@UtilityClass
public class AuthManager {
private final Map<String, User> TOKENS = new HashMap<>();
private final Random rand = new Random();
public String createDiscordAuthToken(User user) {
TOKENS.values().removeIf(user::equals);
byte[] randBytes = new byte[16];
rand.nextBytes(randBytes);
String code = Base64.getEncoder().encodeToString(randBytes);
TOKENS.put(code, user);
BungeeCore.get().getLogger().log(Level.INFO, "Created Discord Auth-Token: " + code + " for: " + user.getAsTag());
BungeeCore.get().getProxy().getScheduler().schedule(BungeeCore.get(), () -> TOKENS.remove(code), 10, TimeUnit.MINUTES);
return code;
}
public User connectAuth(SteamwarUser user, String code) {
User dcUser = TOKENS.remove(code);
if(dcUser == null)
return null;
user.setDiscordId(dcUser.getIdLong());
DiscordChannel channel = new DiscordChannel(dcUser);
channel.send(new MessageBuilder()
.setContent(channel.parseToPlain("DC_AUTH_SUCCESS", user))
.setActionRows(ActionRow.of(Button.success("tada", Emoji.fromUnicode("U+1F389")))));
return dcUser;
}
}

Datei anzeigen

@ -17,16 +17,16 @@
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bungeecore.bot.util;
package de.steamwar.bungeecore.discord.util;
import de.steamwar.bungeecore.Message;
import de.steamwar.bungeecore.bot.SteamwarDiscordBot;
import de.steamwar.messages.Message;
import de.steamwar.bungeecore.discord.DiscordBot;
import de.steamwar.bungeecore.discord.channels.DiscordChannel;
import de.steamwar.messages.Chatter;
import lombok.experimental.UtilityClass;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.MessageBuilder;
import net.dv8tion.jda.api.entities.Emoji;
import net.dv8tion.jda.api.entities.User;
import net.dv8tion.jda.api.interactions.components.ActionRow;
import net.dv8tion.jda.api.interactions.components.Button;
@ -38,26 +38,20 @@ public class DiscordAlert {
public static void send(Chatter player, Color color, Message title, Message description, boolean success) {
Long discordId = player.user().getDiscordId();
if(SteamwarDiscordBot.instance() == null || discordId == null)
if(DiscordBot.getInstance() == null || discordId == null)
return;
User dcUser = SteamwarDiscordBot.instance().getJda().retrieveUserById(discordId).complete();
EmbedBuilder builder = new EmbedBuilder();
builder.setAuthor("SteamWar", "https://steamwar.de", "https://cdn.discordapp.com/app-icons/869606970099904562/60c884000407c02671d91d8e7182b8a1.png");
builder.setColor(color);
builder.setTitle(player.parseToPlain(title));
builder.setDescription(player.parseToPlain(description));
builder.setTimestamp(Instant.now());
MessageBuilder messageBuilder = new MessageBuilder();
messageBuilder.setEmbeds(builder.build());
MessageBuilder builder = new MessageBuilder()
.setEmbeds(new EmbedBuilder()
.setAuthor("SteamWar", "https://steamwar.de", "https://cdn.discordapp.com/app-icons/869606970099904562/60c884000407c02671d91d8e7182b8a1.png")
.setColor(color)
.setTitle(player.parseToPlain(title))
.setDescription(player.parseToPlain(description))
.setTimestamp(Instant.now())
.build());
if(success)
messageBuilder.setActionRows(ActionRow.of(Button.success("tada", Emoji.fromUnicode("U+1F389"))));
builder.setActionRows(ActionRow.of(Button.success("tada", Emoji.fromUnicode("U+1F389"))));
try {
dcUser.openPrivateChannel().complete().sendMessage(messageBuilder.build()).queue();
} catch (Exception e) {
// Ignored
}
new DiscordChannel(player.user()).send(builder);
}
}

Datei anzeigen

@ -0,0 +1,56 @@
/*
* This file is a part of the SteamWar software.
*
* Copyright (C) 2020 SteamWar.de-Serverteam
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bungeecore.discord.util;
import de.steamwar.bungeecore.discord.DiscordBot;
import de.steamwar.bungeecore.discord.config.DiscordConfig;
import de.steamwar.sql.SteamwarUser;
import lombok.experimental.UtilityClass;
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.exceptions.ErrorResponseException;
import java.util.HashSet;
import java.util.Set;
@UtilityClass
public class DiscordRanks {
public void update(SteamwarUser user) {
if (user.getDiscordId() == null)
return;
Set<String> swRoles = new HashSet<>(DiscordConfig.RANKS.values());
Guild guild = DiscordBot.getGuild();
guild.retrieveMemberById(user.getDiscordId()).queue(member -> {
String prefixRole = DiscordConfig.RANKS.get(user.prefix());
member.getRoles().stream()
.filter(role -> swRoles.contains(role.getId()))
.filter(role -> !role.getId().equals(prefixRole))
.forEach(role -> guild.removeRoleFromMember(member, role).queue());
if (member.getRoles().stream().noneMatch(role -> role.getId().equals(prefixRole)))
guild.addRoleToMember(member, guild.getRoleById(prefixRole)).queue();
}, e -> {
if(e instanceof ErrorResponseException && ((ErrorResponseException) e).getErrorCode() == 10007)
user.setDiscordId(null);
});
}
}

Datei anzeigen

@ -23,7 +23,7 @@ public interface InvCallback {
void clicked(ClickType click);
public static enum ClickType {
enum ClickType {
LEFT,
SHIFT_LEFT,
RIGHT,

Datei anzeigen

@ -19,19 +19,17 @@
package de.steamwar.bungeecore.inventory;
import de.steamwar.bungeecore.Message;
import de.steamwar.messages.Message;
import de.steamwar.bungeecore.network.NetworkSender;
import de.steamwar.bungeecore.network.handlers.InventoryCallbackHandler;
import de.steamwar.messages.Chatter;
import de.steamwar.messages.PlayerChatter;
import de.steamwar.network.packets.server.CloseInventoryPacket;
import de.steamwar.network.packets.server.InventoryPacket;
import lombok.Getter;
import lombok.Setter;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.BiFunction;
@ -50,12 +48,7 @@ public class SWInventory {
private final AtomicBoolean processingClick = new AtomicBoolean();
@Deprecated
public SWInventory(ProxiedPlayer proxiedPlayer, int size, String title) {
this(Chatter.of(proxiedPlayer), size, new Message("PLAIN_STRING", title));
}
public SWInventory(Chatter player, int size, Message title) {
public SWInventory(PlayerChatter player, int size, Message title) {
InventoryCallbackHandler.inventoryHashMap.put(player.user().getId(), this);
this.player = player;
this.size = size;
@ -63,14 +56,8 @@ public class SWInventory {
}
public void addItem(int pos, SWItem item, InvCallback callback) {
addItem(pos, item, new ArrayList<>(), callback);
}
@Deprecated
public void addItem(int pos, SWItem item, List<String> lore, InvCallback callback) {
item.setCallback(callback);
item.setLore(lore);
itemMap.put(pos, item);
addItem(pos, item);
}
public void addItem(int pos, SWItem item) {

Datei anzeigen

@ -21,7 +21,7 @@ package de.steamwar.bungeecore.inventory;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import de.steamwar.bungeecore.Message;
import de.steamwar.messages.Message;
import de.steamwar.messages.Chatter;
import lombok.Getter;
import lombok.Setter;
@ -43,43 +43,22 @@ public class SWItem {
private InvCallback callback;
private int color = 0;
@Deprecated
public SWItem(String material, String title) {
this(material, new Message("PLAIN_STRING", title));
}
public SWItem(String material, Message title) {
this.material = material.toUpperCase();
this.title = title;
}
@Deprecated
public SWItem(String title, int color) {
this(new Message("PLAIN_STRING", title), color);
}
public SWItem(Message title, int color) {
this.title = title;
this.color = color;
}
public static SWItem getSkull(String skullOwner) {
SWItem item = new SWItem("SKULL", skullOwner);
SWItem item = new SWItem("SKULL", new Message("PLAIN_STRING", skullOwner));
item.setSkullOwner(skullOwner);
return item;
}
@Deprecated
public SWItem setName(String name) {
title = new Message("PLAIN_STRING", name);
return this;
}
@Deprecated
public void addLore(String lore) {
addLore(new Message("PLAIN_STRING", lore));
}
public SWItem addLore(Message lore) {
this.lore.add(lore);
return this;
@ -108,36 +87,4 @@ public class SWItem {
return object;
}
@Override
public boolean equals(Object o) {
if(!(o instanceof SWItem))
return false;
SWItem item = (SWItem) o;
if(item.enchanted != enchanted)
return false;
if(item.hideAttributes != hideAttributes)
return false;
if(!item.material.equals(material))
return false;
if(!item.lore.equals(lore))
return false;
if(!item.skullOwner.equals(skullOwner))
return false;
return true;
}
public SWItem clone() {
SWItem item;
if(color != 0) {
item = new SWItem(title, color);
}else {
item = new SWItem(material, title);
}
item.setLore(lore);
item.setCallback(callback);
item.setEnchanted(enchanted);
item.setHideAttributes(hideAttributes);
return item;
}
}

Datei anzeigen

@ -19,17 +19,23 @@
package de.steamwar.bungeecore.inventory;
import de.steamwar.messages.Message;
import de.steamwar.messages.PlayerChatter;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import net.md_5.bungee.BungeeCord;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import java.util.*;
public class SWListInv<T> extends SWInventory {
@Setter
private ListCallback<T> callback;
private List<SWListEntry<T>> elements;
private final List<SWListEntry<T>> elements;
private int page;
public SWListInv(ProxiedPlayer p, String t, List<SWListEntry<T>> l, ListCallback<T> c){
public SWListInv(PlayerChatter p, Message t, List<SWListEntry<T>> l, ListCallback<T> c){
super(p, (l.size()>45) ? 54 : (l.size() + 9-l.size()%9), t);
callback = c;
elements = l;
@ -40,19 +46,19 @@ public class SWListInv<T> extends SWInventory {
public void open(){
if(elements.size() > 54){
if(page != 0)
addItem(45, new SWItem("§eSeite zurück", 10), (InvCallback.ClickType click) -> {
addItem(45, new SWItem(new Message("INV_PAGE_BACK", "e"), 10), (InvCallback.ClickType click) -> {
page--;
open();
});
else
addItem(45, new SWItem("§7Seite zurück", 8), (InvCallback.ClickType click) -> {});
addItem(45, new SWItem(new Message("INV_PAGE_BACK", "7"), 8), (InvCallback.ClickType click) -> {});
if(page < elements.size()/45)
addItem(53, new SWItem("§eSeite vor", 10), (InvCallback.ClickType click) -> {
addItem(53, new SWItem(new Message("INV_PAGE_NEXT", "e"), 10), (InvCallback.ClickType click) -> {
page++;
open();
});
else
addItem(53, new SWItem("§eSeite vor", 8), (InvCallback.ClickType click) -> {});
addItem(53, new SWItem(new Message("INV_PAGE_NEXT", "7"), 8), (InvCallback.ClickType click) -> {});
}
int ipageLimit = elements.size() - page*45;
@ -71,10 +77,6 @@ public class SWListInv<T> extends SWInventory {
super.open();
}
public void setCallback(ListCallback<T> c){
callback = c;
}
public interface ListCallback<T>{
void clicked(InvCallback.ClickType click, T element);
}
@ -101,21 +103,10 @@ public class SWListInv<T> extends SWInventory {
return onlinePlayers;
}
public static class SWListEntry<T>{
@Getter
@AllArgsConstructor
public static class SWListEntry<T> {
final SWItem item;
final T object;
public SWListEntry(SWItem item, T object){
this.item = item;
this.object = object;
}
public SWItem getItem(){
return item;
}
public T getObject(){
return object;
}
}
}

Datei anzeigen

@ -1,8 +1,7 @@
package de.steamwar.bungeecore.inventory;
import de.steamwar.bungeecore.Message;
import de.steamwar.messages.Chatter;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import de.steamwar.messages.Message;
import de.steamwar.messages.PlayerChatter;
import java.util.List;
import java.util.function.Function;
@ -12,40 +11,32 @@ public class SWStreamInv<T> extends SWInventory {
private final Function<Integer, List<SWListInv.SWListEntry<T>>> constructor;
private int page;
public SWStreamInv(Chatter chatter, Message title, SWListInv.ListCallback<T> callback, Function<Integer, List<SWListInv.SWListEntry<T>>> constructor) {
public SWStreamInv(PlayerChatter chatter, Message title, SWListInv.ListCallback<T> callback, Function<Integer, List<SWListInv.SWListEntry<T>>> constructor) {
super(chatter, 54, title);
this.callback = callback;
this.constructor = constructor;
page = 0;
}
@Deprecated
public SWStreamInv(ProxiedPlayer proxiedPlayer, String title, SWListInv.ListCallback<T> callback, Function<Integer, List<SWListInv.SWListEntry<T>>> constructor) {
super(proxiedPlayer, 54, title);
this.callback = callback;
this.constructor = constructor;
page = 0;
}
@Override
public void open(){
List<SWListInv.SWListEntry<T>> entries = constructor.apply(page);
if(page != 0)
addItem(45, new SWItem("§eSeite zurück", 10), (InvCallback.ClickType click) -> {
addItem(45, new SWItem(new Message("INV_PAGE_BACK", "e"), 10), (InvCallback.ClickType click) -> {
page--;
open();
});
else
addItem(45, new SWItem("§7Seite zurück", 8), (InvCallback.ClickType click) -> {});
addItem(45, new SWItem(new Message("INV_PAGE_BACK", "7"), 8), (InvCallback.ClickType click) -> {});
if(entries.size() == 45)
addItem(53, new SWItem("§eSeite vor", 10), (InvCallback.ClickType click) -> {
addItem(53, new SWItem(new Message("INV_PAGE_NEXT", "e"), 10), (InvCallback.ClickType click) -> {
page++;
open();
});
else
addItem(53, new SWItem("§7Seite vor", 8), (InvCallback.ClickType click) -> {});
addItem(53, new SWItem(new Message("INV_PAGE_NEXT", "7"), 8), (InvCallback.ClickType click) -> {});
for(int i = 0; i < entries.size(); i++) {
SWListInv.SWListEntry<T> item = entries.get(i);

Datei anzeigen

@ -20,10 +20,10 @@
package de.steamwar.bungeecore.listeners;
import de.steamwar.bungeecore.BungeeCore;
import de.steamwar.bungeecore.Message;
import de.steamwar.bungeecore.commands.PunishmentCommand;
import de.steamwar.bungeecore.commands.WebpasswordCommand;
import de.steamwar.messages.Chatter;
import de.steamwar.messages.Message;
import de.steamwar.sql.BannedUserIPs;
import de.steamwar.sql.Punishment;
import de.steamwar.sql.SteamwarUser;
@ -36,6 +36,7 @@ import net.md_5.bungee.event.EventHandler;
import java.sql.Timestamp;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
public class BanListener extends BasicListener {
@ -80,11 +81,11 @@ public class BanListener extends BasicListener {
new Message("BAN_AVOIDING_BAN_HOVER"),
clickEvent,
user.getUserName(),
ips.stream().map(banned -> {
(Function<Chatter, String>) ((Chatter sender) -> ips.stream().map(banned -> {
SteamwarUser bannedUser = SteamwarUser.get(banned.getUserID());
return sender.parseToLegacy("BAN_AVOIDING_LIST", bannedUser.getUserName(),
banned.getTimestamp().toLocalDateTime().format(DateTimeFormatter.ofPattern(sender.parseToPlain("TIMEFORMAT"))));
}).collect(Collectors.joining(" "))
}).collect(Collectors.joining(" ")))
);
}

Datei anzeigen

@ -25,7 +25,7 @@ import net.md_5.bungee.api.plugin.Listener;
public abstract class BasicListener implements Listener {
public BasicListener(){
protected BasicListener(){
ProxyServer.getInstance().getPluginManager().registerListener(BungeeCore.get(), this);
}
}

Datei anzeigen

@ -19,18 +19,21 @@
package de.steamwar.bungeecore.listeners;
import de.steamwar.bungeecore.*;
import de.steamwar.bungeecore.bot.SteamwarDiscordBot;
import de.steamwar.bungeecore.ArenaMode;
import de.steamwar.bungeecore.BungeeCore;
import de.steamwar.bungeecore.Servertype;
import de.steamwar.bungeecore.Subserver;
import de.steamwar.bungeecore.commands.PunishmentCommand;
import de.steamwar.bungeecore.discord.DiscordBot;
import de.steamwar.bungeecore.network.NetworkSender;
import de.steamwar.bungeecore.util.Chat19;
import de.steamwar.messages.Chatter;
import de.steamwar.messages.ChatterGroup;
import de.steamwar.messages.Message;
import de.steamwar.messages.PlayerChatter;
import de.steamwar.network.packets.server.PingPacket;
import de.steamwar.sql.*;
import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.CommandSender;
import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import net.md_5.bungee.api.event.ChatEvent;
@ -60,7 +63,7 @@ public class ChatListener extends BasicListener {
if (message.contains("jndi:ldap")) {
SteamwarUser user = SteamwarUser.get(player.getUniqueId());
PunishmentCommand.ban(user, Punishment.PERMA_TIME, "Versuchte Exploit-Ausnutzung", SteamwarUser.get(-1), true);
BungeeCore.log(Level.SEVERE, user.getUserName() + " " + user.getId() + " wurde automatisch wegen jndi:ldap gebannt.");
BungeeCore.get().getLogger().log(Level.SEVERE, user.getUserName() + " " + user.getId() + " wurde automatisch wegen jndi:ldap gebannt.");
return;
}
@ -69,9 +72,9 @@ public class ChatListener extends BasicListener {
Subserver subserver = Subserver.getSubserver(player);
if(subserver != null && subserver.getType() == Servertype.ARENA && subserver.getServer() == player.getServer().getInfo()) {
localChat(player, message);
localChat(Chatter.of(player), message);
} else if (message.startsWith("+")) {
localChat(player, message.substring(1));
localChat(Chatter.of(player), message.substring(1));
} else {
sendChat(Chatter.of(player), Chatter.globalChat(), "CHAT_GLOBAL", null, message);
}
@ -85,7 +88,7 @@ public class ChatListener extends BasicListener {
command = "/" + command.substring(1);
message = "/" + command;
if(filteredCommand(player, message))
if(filteredCommand(Chatter.of(player), message))
return true;
Chat19.chat(player, message);
@ -113,23 +116,21 @@ public class ChatListener extends BasicListener {
chatToReciever(Chatter.console(), msgReceiver, user, format, coloredMessage);
if(format.equals("CHAT_GLOBAL")) {
if (SteamwarDiscordBot.instance() != null)
chatToReciever(Chatter.discordChannel(SteamwarDiscordBot.instance().getIngameChatListener()), msgReceiver, user, format, coloredMessage);
DiscordBot.withBot(bot -> chatToReciever(bot.getIngameChat(), msgReceiver, user, format, coloredMessage));
} else if (format.equals("CHAT_SERVERTEAM")) {
if (SteamwarDiscordBot.instance() != null)
chatToReciever(Chatter.discordChannel(SteamwarDiscordBot.instance().getServerTeamChatListener()), msgReceiver, user, format, coloredMessage);
DiscordBot.withBot(bot -> chatToReciever(bot.getServerTeamChat(), msgReceiver, user, format, coloredMessage));
} else if (noReceiver) {
sender.system("CHAT_NO_RECEIVER");
}
}
public static void localChat(PlayerChatter sender, String message) {
if(message.length() == 0){
if(message.isEmpty()){
sender.system("CHAT_BC_USAGE");
return;
}
if(ChatListener.filteredCommand(sender.getPlayer(), message))
if(ChatListener.filteredCommand(sender, message))
return;
if(!message.startsWith("/") && chatFilter(sender, message))
@ -182,10 +183,10 @@ public class ChatListener extends BasicListener {
chatColorCode));
}
private static boolean filteredCommand(CommandSender sender, String message) {
private static boolean filteredCommand(Chatter sender, String message) {
String command = message.split(" ", 2)[0];
if(command.startsWith("/") && command.contains(":")) {
Message.send("UNKNOWN_COMMAND", sender);
sender.system("UNKNOWN_COMMAND");
return true;
}
return false;

Datei anzeigen

@ -19,35 +19,36 @@
package de.steamwar.bungeecore.listeners;
import de.steamwar.bungeecore.*;
import de.steamwar.bungeecore.Bauserver;
import de.steamwar.bungeecore.Servertype;
import de.steamwar.bungeecore.Subserver;
import de.steamwar.bungeecore.commands.CheckCommand;
import de.steamwar.messages.Chatter;
import de.steamwar.sql.SchematicNode;
import de.steamwar.sql.SchematicType;
import de.steamwar.sql.SteamwarUser;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import net.md_5.bungee.api.event.PlayerDisconnectEvent;
import net.md_5.bungee.api.event.PostLoginEvent;
import net.md_5.bungee.api.event.ServerSwitchEvent;
import net.md_5.bungee.event.EventHandler;
import java.util.LinkedList;
import java.util.ArrayList;
import java.util.List;
public class CheckListener extends BasicListener {
@EventHandler
public void onPlayerJoin(PostLoginEvent e){
ProxiedPlayer player = e.getPlayer();
SteamwarUser user = SteamwarUser.get(player.getUniqueId());
Chatter sender = Chatter.of(e.getPlayer());
List<SchematicNode> uncheckedSchematics = new LinkedList<>();
List<SchematicNode> uncheckedSchematics = new ArrayList<>();
for(SchematicType type : SchematicType.values()){
if(type.check())
uncheckedSchematics.addAll(SchematicNode.getAllSchematicsOfType(user.getId(), type.toDB()));
uncheckedSchematics.addAll(SchematicNode.getAllSchematicsOfType(sender.user().getId(), type.toDB()));
}
if(!uncheckedSchematics.isEmpty())
Message.send("CHECK_UNCHECKED", player, uncheckedSchematics.size());
sender.system("CHECK_UNCHECKED", uncheckedSchematics.size());
}
@EventHandler

Datei anzeigen

@ -20,19 +20,20 @@
package de.steamwar.bungeecore.listeners;
import de.steamwar.bungeecore.BungeeCore;
import de.steamwar.bungeecore.Message;
import de.steamwar.messages.Message;
import de.steamwar.bungeecore.Servertype;
import de.steamwar.bungeecore.Subserver;
import de.steamwar.bungeecore.bot.config.SteamwarDiscordBotConfig;
import de.steamwar.bungeecore.bot.util.DiscordRanks;
import de.steamwar.bungeecore.commands.ChallengeCommand;
import de.steamwar.bungeecore.commands.CheckCommand;
import de.steamwar.bungeecore.commands.ModCommand;
import de.steamwar.bungeecore.commands.MsgCommand;
import de.steamwar.bungeecore.discord.DiscordBot;
import de.steamwar.bungeecore.discord.util.DiscordRanks;
import de.steamwar.bungeecore.mods.ModUtils;
import de.steamwar.messages.Chatter;
import de.steamwar.sql.SteamwarUser;
import de.steamwar.sql.UserPerm;
import lombok.Getter;
import net.md_5.bungee.api.AbstractReconnectHandler;
import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.chat.ClickEvent;
@ -43,10 +44,7 @@ import net.md_5.bungee.api.event.PostLoginEvent;
import net.md_5.bungee.api.event.ServerKickEvent;
import net.md_5.bungee.event.EventHandler;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.UUID;
import java.util.*;
public class ConnectionListener extends BasicListener {
@ -61,6 +59,37 @@ public class ConnectionListener extends BasicListener {
public static final String TEAMCHAT_PERMISSION = "bungeecore.teamchat";
public static final String MOD_PERMISSION = "bungeecore.mod";
@Getter
private static final Map<UserPerm, String[]> commandPermissions = new EnumMap<>(UserPerm.class);
static {
commandPermissions.put(UserPerm.ADMINISTRATION, new String[]{
"bungeecord.command.end",
"bungeecord.command.reload",
"bungeecord.command.ip",
SOFTRELOAD_PERMISSION
});
commandPermissions.put(UserPerm.MODERATION, new String[]{
ALERT_PERMISSION,
KICK_PERMISSION,
POLLRESULT_PERMISSION,
EVENTRELOAD_PERMISSION,
MOD_PERMISSION
});
commandPermissions.put(UserPerm.TEAM, new String[]{
"bungeecord.command.list",
"bungeecord.command.send",
"bungeecord.command.server",
TEAMCHAT_PERMISSION,
BAN_PERMISSION
});
commandPermissions.put(UserPerm.CHECK, new String[]{
CHECK_PERMISSION
});
commandPermissions.put(UserPerm.BUILD, new String[]{
BUILDERCLOUD_PERMISSION
});
}
private static final Set<UUID> newPlayers = new HashSet<>();
public static void newPlayer(UUID player){
@ -73,45 +102,17 @@ public class ConnectionListener extends BasicListener {
SteamwarUser user = SteamwarUser.get(player.getUniqueId());
Chatter chatter = Chatter.of(player);
if(user.hasPerm(UserPerm.ADMINISTRATION)) {
player.setPermission("bungeecord.command.end", true);
player.setPermission("bungeecord.command.reload", true);
player.setPermission("bungeecord.command.ip", true);
player.setPermission(SOFTRELOAD_PERMISSION, true);
}
user.perms().forEach(perm -> {
for(String permission : commandPermissions.getOrDefault(perm, new String[0]))
player.setPermission(permission, true);
});
if(user.hasPerm(UserPerm.MODERATION)) {
player.setPermission(ALERT_PERMISSION, true);
player.setPermission(KICK_PERMISSION, true);
player.setPermission(POLLRESULT_PERMISSION, true);
player.setPermission(EVENTRELOAD_PERMISSION, true);
player.setPermission(MOD_PERMISSION, true);
}
if(user.hasPerm(UserPerm.TEAM)) {
player.setPermission("bungeecord.command.list", true);
player.setPermission("bungeecord.command.send", true);
player.setPermission("bungeecord.command.server", true);
player.setPermission(TEAMCHAT_PERMISSION, true);
player.setPermission(BAN_PERMISSION, true);
}
if(user.hasPerm(UserPerm.CHECK)) {
if(user.hasPerm(UserPerm.CHECK))
CheckCommand.sendReminder(chatter);
player.setPermission(CHECK_PERMISSION, true);
}
if(user.hasPerm(UserPerm.BUILD)) {
player.setPermission(BUILDERCLOUD_PERMISSION, true);
}
for(Subserver subserver : Subserver.getServerList()){
if(subserver.getType() == Servertype.ARENA){
Iterator<ProxiedPlayer> it = subserver.getServer().getPlayers().iterator();
if(it.hasNext()){
Message.send("JOIN_ARENA", player, Message.parse("JOIN_ARENA_HOVER", player),
new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/join " + it.next().getName()), subserver.getServer().getName());
}
for(Subserver subserver : Subserver.getServerList()) {
if(subserver.getType() == Servertype.ARENA) {
chatter.system("JOIN_ARENA", new Message("JOIN_ARENA_HOVER"), new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/arena " + subserver.getServer().getName()), subserver.getServer().getName());
}
}
@ -120,8 +121,7 @@ public class ConnectionListener extends BasicListener {
newPlayers.remove(player.getUniqueId());
}
if(SteamwarDiscordBotConfig.loaded)
DiscordRanks.update(user);
DiscordBot.withBot(bot -> DiscordRanks.update(user));
}
/** To redirect players to the lobby in case of server closure. */

Datei anzeigen

@ -1,8 +1,9 @@
package de.steamwar.bungeecore.listeners;
import de.steamwar.bungeecore.Message;
import de.steamwar.sql.*;
import net.md_5.bungee.api.chat.TextComponent;
import de.steamwar.messages.Chatter;
import de.steamwar.sql.Event;
import de.steamwar.sql.Referee;
import de.steamwar.sql.TeamTeilnahme;
import net.md_5.bungee.api.event.PostLoginEvent;
import net.md_5.bungee.event.EventHandler;
@ -10,20 +11,20 @@ public class EventModeListener extends BasicListener {
@EventHandler
public void onPostLogin(PostLoginEvent e) {
SteamwarUser user = SteamwarUser.get(e.getPlayer().getUniqueId());
Chatter sender = Chatter.disconnect(e.getPlayer());
Event event = Event.get();
if(event == null){
e.getPlayer().disconnect(TextComponent.fromLegacyText(Message.parse("EVENTMODE_KICK", e.getPlayer())));
if(event == null) {
sender.system("EVENTMODE_KICK");
return;
}
if(TeamTeilnahme.nimmtTeil(user.getTeam(), event.getEventID()))
if(TeamTeilnahme.nimmtTeil(sender.user().getTeam(), event.getEventID()))
return;
if(Referee.get(event.getEventID()).contains(user.getId()))
if(Referee.get(event.getEventID()).contains(sender.user().getId()))
return;
e.getPlayer().disconnect(TextComponent.fromLegacyText(Message.parse("EVENTMODE_KICK", e.getPlayer())));
sender.system("EVENTMODE_KICK");
}
}

Datei anzeigen

@ -21,7 +21,7 @@ package de.steamwar.bungeecore.listeners;
import com.lunarclient.apollo.ApolloManager;
import de.steamwar.bungeecore.BungeeCore;
import de.steamwar.bungeecore.Message;
import de.steamwar.messages.Message;
import de.steamwar.bungeecore.commands.TeamCommand;
import de.steamwar.bungeecore.mods.*;
import de.steamwar.bungeecore.network.ServerMetaInfo;

Datei anzeigen

@ -19,7 +19,7 @@
package de.steamwar.bungeecore.listeners;
import de.steamwar.bungeecore.Message;
import de.steamwar.messages.Message;
import de.steamwar.command.TypeValidator;
import de.steamwar.messages.Chatter;
import de.steamwar.sql.PollAnswer;

Datei anzeigen

@ -21,6 +21,7 @@ package de.steamwar.bungeecore.mods;
import de.steamwar.bungeecore.BungeeCore;
import de.steamwar.bungeecore.listeners.BasicListener;
import de.steamwar.messages.Chatter;
import de.steamwar.sql.Mod;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
@ -86,7 +87,7 @@ public class FML extends BasicListener {
synchronized (unlocked) {
unlocked.add(p.getUniqueId());
}
p.disconnect(BungeeCore.stringToText("§7Deine installierten Mods wurden überprüft\n§aDu kannst nun §eSteam§8War §abetreten"));
Chatter.disconnect(p).system("MODS_CHECKED");
ProxyServer.getInstance().getScheduler().schedule(BungeeCore.get(), () -> {
synchronized (unlocked) {
unlocked.remove(p.getUniqueId());

Datei anzeigen

@ -20,12 +20,11 @@
package de.steamwar.bungeecore.mods;
import de.steamwar.bungeecore.BungeeCore;
import de.steamwar.bungeecore.Message;
import de.steamwar.bungeecore.commands.PunishmentCommand;
import de.steamwar.sql.SteamwarUser;
import de.steamwar.messages.Chatter;
import de.steamwar.sql.Mod;
import de.steamwar.sql.Mod.ModType;
import de.steamwar.sql.SteamwarUser;
import de.steamwar.sql.UserPerm;
import lombok.Getter;
import lombok.experimental.UtilityClass;
@ -52,7 +51,8 @@ public class ModUtils {
}
public static boolean handleMods(UUID uuid, Locale locale, Consumer<BaseComponent> disconnect, List<Mod> mods){
SteamwarUser user = SteamwarUser.get(uuid);
Chatter sender = Chatter.of(uuid);
SteamwarUser user = sender.user();
playerModMap.put(uuid,new ArrayList<>(mods));
BungeeCore.get().getLogger().log(Level.INFO, user.getUserName() + " declares mods: " + mods.stream().map(mod -> mod.getPlatform() + ":" + mod.getModName()).collect(Collectors.joining(" ")));
@ -76,14 +76,14 @@ public class ModUtils {
String message;
if(mods.size() == 1) {
message = Message.parse(max == ModType.RED ? "MOD_RED_SING" : "MOD_YELLOW_SING", locale, modList);
message = sender.parseToLegacy(max == ModType.RED ? "MOD_RED_SING" : "MOD_YELLOW_SING", locale, modList);
} else {
message = Message.parse(max == ModType.RED ? "MOD_RED_PLUR" : "MOD_YELLOW_PLUR", locale, modList);
message = sender.parseToLegacy(max == ModType.RED ? "MOD_RED_PLUR" : "MOD_YELLOW_PLUR", locale, modList);
}
if(max == ModType.RED) {
PunishmentCommand.ban(user, Timestamp.from(Instant.now().plus(7, ChronoUnit.DAYS)), message, SteamwarUser.get(-1), false);
BungeeCore.log(Level.SEVERE, user.getUserName() + " " + user.getId() + " wurde automatisch wegen der Mods " + modList + " gebannt.");
BungeeCore.get().getLogger().log(Level.SEVERE, user.getUserName() + " " + user.getId() + " wurde automatisch wegen der Mods " + modList + " gebannt.");
}
disconnect.accept(TextComponent.fromLegacy(message));

Datei anzeigen

@ -1,36 +0,0 @@
/*
* This file is a part of the SteamWar software.
*
* Copyright (C) 2022 SteamWar.de-Serverteam
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.bungeecore.network;
import de.steamwar.bungeecore.network.handlers.*;
import lombok.experimental.UtilityClass;
@UtilityClass
public class BungeeNetworkHandler {
public static void register() {
new EloPlayerHandler().register();
new EloSchemHandler().register();
new ExecuteCommandHandler().register();
new FightInfoHandler().register();
new ImALobbyHandler().register();
new InventoryCallbackHandler().register();
new PrepareSchemHandler().register();
}
}

Datei anzeigen

@ -21,9 +21,11 @@ package de.steamwar.bungeecore.network;
import de.steamwar.network.packets.NetworkPacket;
import lombok.SneakyThrows;
import lombok.experimental.UtilityClass;
import net.md_5.bungee.api.config.ServerInfo;
import net.md_5.bungee.api.connection.ProxiedPlayer;
@UtilityClass
public class NetworkSender {
@SneakyThrows

Datei anzeigen

@ -20,17 +20,13 @@
package de.steamwar.bungeecore.network;
import de.steamwar.network.packets.MetaInfos;
import lombok.AllArgsConstructor;
import lombok.Getter;
import net.md_5.bungee.api.config.ServerInfo;
@Getter
@AllArgsConstructor
public class ServerMetaInfo implements MetaInfos {
private ServerInfo sender;
public ServerMetaInfo(ServerInfo sender) {
this.sender = sender;
}
public ServerInfo getSender() {
return sender;
}
private final ServerInfo sender;
}

Datei anzeigen

@ -23,7 +23,6 @@ import de.steamwar.bungeecore.ArenaMode;
import de.steamwar.bungeecore.BungeeCore;
import de.steamwar.network.packets.PacketHandler;
import de.steamwar.network.packets.common.FightEndsPacket;
import de.steamwar.sql.SchematicNode;
import de.steamwar.sql.SchematicType;
import de.steamwar.sql.SteamwarUser;
import de.steamwar.sql.UserElo;
@ -45,9 +44,9 @@ public class EloPlayerHandler extends PacketHandler {
private static final int MEDIAN_ELO_GAIN = 40;
private static final int MEDIAN_ELO_LOSE = 20;
private static final long REMATCH_LIFETIME = 1L * 60 * 60 * 1000;
private static final long REMATCH_LIFETIME = (long) 60 * 60 * 1000;
private Map<String, LinkedList<Game>> gameModeGames = new HashMap<>();
private final Map<String, LinkedList<Game>> gameModeGames = new HashMap<>();
/**
* {@link FightEndsPacket#getWin()} == 1 -> Blue won
@ -55,16 +54,11 @@ public class EloPlayerHandler extends PacketHandler {
*/
@Handler
public void handle(FightEndsPacket fightEndsPacket) {
if (!ArenaMode.getBySchemType(SchematicType.fromDB(fightEndsPacket.getGameMode())).isRanked()) {
if (!ArenaMode.getBySchemType(SchematicType.fromDB(fightEndsPacket.getGameMode())).isRanked())
return;
}
boolean bluePublic = SchematicNode.getSchematicNode(fightEndsPacket.getBlueSchem()).getOwner() == 0;
boolean redPublic = SchematicNode.getSchematicNode(fightEndsPacket.getRedSchem()).getOwner() == 0;
if (bluePublic ^ redPublic) {
if (EloSchemHandler.publicVsPrivate(fightEndsPacket))
return;
}
// Die nächsten Zeilen filtern ein Fight innerhalb eines Teams nicht gewertet wird, bzw auch wenn nur Teile beider Teams im
// gleichen Team sind dieser ungewertet ist.
@ -76,12 +70,6 @@ public class EloPlayerHandler extends PacketHandler {
}
}
int blueRank = SchematicNode.getSchematicNode(fightEndsPacket.getBlueSchem()).getRank();
int redRank = SchematicNode.getSchematicNode(fightEndsPacket.getRedSchem()).getRank();
double blueRankFactor = blueRank > redRank ? (fightEndsPacket.getWin() == 1 ? 0.9 : 1.0) : (fightEndsPacket.getWin() == 1 ? 1.5 : 1.0);
double redRankFactor = redRank > blueRank ? (fightEndsPacket.getWin() == 2 ? 0.9 : 1.0) : (fightEndsPacket.getWin() == 2 ? 1.5 : 1.0);
// Get sizes of both teams
int blueTeamSize = fightEndsPacket.getBluePlayers().size();
int redTeamSize = fightEndsPacket.getRedPlayers().size();
@ -120,7 +108,7 @@ public class EloPlayerHandler extends PacketHandler {
}
// Calculate the elo factor
double blueEloFactor = ((fightEndsPacket.getWin() == 1 ? 1 : 0) - 1 / (1 + Math.pow(10, (redTeamElo - blueTeamElo) / 600.0))) * (1 / (1 + Math.exp(-Math.abs(blueTeamElo - redTeamElo) / 1200))) * 4;
double blueEloFactor = ((fightEndsPacket.getWin() == 1 ? 1 : 0) - 1 / (1 + Math.pow(10, (redTeamElo - blueTeamElo) / 600.0))) * (1 / (1 + Math.exp(-Math.abs(blueTeamElo - redTeamElo) / 1200.0))) * 4;
double redEloFactor = blueEloFactor * -1;
// Calculate favoured team on draw
@ -135,8 +123,8 @@ public class EloPlayerHandler extends PacketHandler {
if (Math.abs(blueEloFactor) > 1) {
// Do nothing
} else if (Math.abs(blueEloFactor) < 1) {
blueEloFactor = ((fightEndsPacket.getWin() == 1 ? 1 : 0) - 1 / (1 + Math.pow(10, (blueTeamElo - redTeamElo) / 600.0))) * (1 / (1 + Math.exp(-Math.abs(redTeamElo - blueTeamElo) / 1200))) * -4;
redEloFactor = blueEloFactor * -1;
blueEloFactor = -blueEloFactor;
redEloFactor = -blueEloFactor;
} else {
blueEloFactor = 0;
redEloFactor = 0;
@ -154,8 +142,8 @@ public class EloPlayerHandler extends PacketHandler {
// Calculate division factor
double divisionFactor = 1D / Math.max(blueTeamSize, redTeamSize);
double blueFactor = blueRankFactor * bluePlayerFactor * timeFactor * blueEloFactor * rematchFactor * blueWinFactor * divisionFactor;
double redFactor = redRankFactor * redPlayerFactor * timeFactor * redEloFactor * rematchFactor * redWinFactor * divisionFactor;
double blueFactor = bluePlayerFactor * timeFactor * blueEloFactor * rematchFactor * blueWinFactor * divisionFactor;
double redFactor = redPlayerFactor * timeFactor * redEloFactor * rematchFactor * redWinFactor * divisionFactor;
// Calculate the elo gain for each player
int blueEloGain = (int) Math.round((blueFactor < 0 ? MEDIAN_ELO_LOSE : MEDIAN_ELO_GAIN) * blueFactor) + blueTeamEloBonus;
@ -201,12 +189,12 @@ public class EloPlayerHandler extends PacketHandler {
TaskScheduler scheduler = ProxyServer.getInstance().getScheduler();
double eloStep = eloGain / 40.0;
for (int i = 0; i < 40; i++) {
BaseComponent[] eloGainComponent = TextComponent.fromLegacyText(color + (int) (eloStep * (i + 1)));
BaseComponent eloGainComponent = TextComponent.fromLegacy(color + (int) (eloStep * (i + 1)));
int finalI = i;
scheduler.schedule(BungeeCore.get(), () -> {
if (player == null) return;
if (!player.isConnected()) return;
Title title = new BungeeTitle().title(TextComponent.fromLegacyText(getRankup.apply(finalI))).subTitle(eloGainComponent).fadeIn(finalI == 0 ? 5 : 0).stay(40).fadeOut(finalI == 39 ? 5 : 0);
Title title = new BungeeTitle().title(TextComponent.fromLegacy(getRankup.apply(finalI))).subTitle(eloGainComponent).fadeIn(finalI == 0 ? 5 : 0).stay(40).fadeOut(finalI == 39 ? 5 : 0);
title.send(player);
}, i * 50L, TimeUnit.MILLISECONDS);
}

Datei anzeigen

@ -28,7 +28,13 @@ import de.steamwar.sql.SchematicType;
public class EloSchemHandler extends PacketHandler {
private final int K = 20;
private static final int K = 20;
public static boolean publicVsPrivate(FightEndsPacket packet) {
SchematicNode blueSchem = SchematicNode.getSchematicNode(packet.getBlueSchem());
SchematicNode redSchem = SchematicNode.getSchematicNode(packet.getRedSchem());
return (blueSchem.getOwner() == 0) != (redSchem.getOwner() == 0);
}
@Handler
public void handle(FightEndsPacket fightEndsPacket) {
@ -36,12 +42,8 @@ public class EloSchemHandler extends PacketHandler {
return;
}
boolean bluePublic = SchematicNode.getSchematicNode(fightEndsPacket.getBlueSchem()).getOwner() == 0;
boolean redPublic = SchematicNode.getSchematicNode(fightEndsPacket.getRedSchem()).getOwner() == 0;
if (bluePublic ^ redPublic) {
if (publicVsPrivate(fightEndsPacket))
return;
}
calcSchemElo(fightEndsPacket);
}

Datei anzeigen

@ -19,16 +19,15 @@
package de.steamwar.bungeecore.network.handlers;
import de.steamwar.bungeecore.BungeeCore;
import de.steamwar.bungeecore.inventory.InvCallback;
import de.steamwar.bungeecore.inventory.SWInventory;
import de.steamwar.bungeecore.network.NetworkSender;
import de.steamwar.bungeecore.network.ServerMetaInfo;
import de.steamwar.sql.SteamwarUser;
import de.steamwar.messages.Chatter;
import de.steamwar.network.packets.PacketHandler;
import de.steamwar.network.packets.client.InventoryCallbackPacket;
import de.steamwar.network.packets.server.CloseInventoryPacket;
import net.md_5.bungee.api.ProxyServer;
import de.steamwar.sql.SteamwarUser;
import java.util.HashMap;
import java.util.Map;
@ -42,7 +41,7 @@ public class InventoryCallbackHandler extends PacketHandler {
SteamwarUser owner = SteamwarUser.get(packet.getOwner());
InventoryCallbackPacket.CallbackType type = packet.getType();
if(!inventoryHashMap.containsKey(owner.getId())) {
BungeeCore.send(ProxyServer.getInstance().getPlayer(owner.getUUID()), BungeeCore.CHAT_PREFIX + "§cBitte erneut versuchen. Durch ein Softwareupdate konnte die übliche Aktion nicht durchgeführt werden.");
Chatter.of(owner).system("UPDATE_INTERRUPTION");
if(type == InventoryCallbackPacket.CallbackType.CLICK) {
NetworkSender.send(((ServerMetaInfo) packet.getMetaInfos()).getSender(), new CloseInventoryPacket(owner.getId()));
}

Datei anzeigen

@ -344,7 +344,7 @@ public class Tablist extends MessageToMessageDecoder<PacketWrapper> {
}
}
private BaseComponent[] header(Chatter p, int seconds) {
private BaseComponent header(Chatter p, int seconds) {
int phase = (seconds % 10) / 5;
if (phase == 0)
return p.parse(false, "TABLIST_PHASE_DISCORD");

Datei anzeigen

@ -84,7 +84,7 @@ interface TablistPart {
}
private BaseComponent reformat(String string) {
return TextComponent.fromArray(TextComponent.fromLegacyText(string));
return TextComponent.fromLegacy(string);
}
}
}

Datei anzeigen

@ -20,8 +20,10 @@
package de.steamwar.command;
import de.steamwar.bungeecore.BungeeCore;
import de.steamwar.bungeecore.Message;
import de.steamwar.messages.Message;
import de.steamwar.bungeecore.discord.DiscordBot;
import de.steamwar.messages.Chatter;
import lombok.Getter;
import net.md_5.bungee.api.CommandSender;
import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.chat.ClickEvent;
@ -41,6 +43,7 @@ public class SWCommand extends AbstractSWCommand<Chatter> {
TypeUtils.init();
}
@Getter
private final String permission;
private Command command;
@ -63,6 +66,10 @@ public class SWCommand extends AbstractSWCommand<Chatter> {
register();
}
public void execute(Chatter sender, String[] args) {
execute(sender, null, args);
}
private boolean create = false;
@Override
@ -91,12 +98,20 @@ public class SWCommand extends AbstractSWCommand<Chatter> {
public void unregister() {
if (command == null) return;
ProxyServer.getInstance().getPluginManager().unregisterCommand(this.command);
DiscordBot.getCommands().remove(command.getName());
for(String alias : command.getAliases())
DiscordBot.getCommands().remove(alias);
}
@Override
public void register() {
if (command == null) return;
ProxyServer.getInstance().getPluginManager().registerCommand(BungeeCore.get(), this.command);
DiscordBot.getCommands().put(command.getName(), this);
for(String alias : command.getAliases())
DiscordBot.getCommands().put(alias, this);
}
@Override

Datei anzeigen

@ -9,6 +9,7 @@ PLAIN_STRING={0}
UNKNOWN_COMMAND=§cUnknown command.
UNKNOWN_PLAYER=§cUnknown player.
UNKNOWN_TEAM=§cUnknown team.
UNKNOWN_EVENT=$cUnknown event.
INVALID_TIME=§cInvalid time.
STEAMWAR_BRAND=§eSteam§8War.de §7({0}) §r<- §e{1} §7({2})§r
@ -19,6 +20,7 @@ DEV_UNKNOWN_SERVER=§cPlease specify a dev server.
DISABLED=§cCurrently disabled.
SERVER_START_OVERLOAD=§cServer start cancelled due to overload. Please try again later.
UPDATE_INTERRUPTION=§cPlease try again. A software update has interrupted this action.
#Help command
HELP_LOBBY=§7Return from anywhere to the lobby using §8/§el§7!
@ -114,6 +116,7 @@ MOD_RED_SING=Attempted use of mod {0}
MOD_RED_PLUR=Attempted use of mods:\n{0}
MOD_YELLOW_SING=§7Deactivate the mod §e{0}§7 to continue playing on §eSteam§8War§7.
MOD_YELLOW_PLUR=§7Deactivate the mods\n§e{0}\n§7to continue playing on §eSteam§8War§7.
MODS_CHECKED=§7Your Mods have been checked.\n§aYou can join §eSteam§8War §anow§8.
#Various commands
ALERT=§f{0}
@ -482,7 +485,7 @@ TEAM_LIST_UNKNOWN_PAGE=§cInvalid page entered
TEAM_LIST_HEADER=§7§lTeam list §7{0}§8/§7{1}
TEAM_LIST_TEAM=§{0}{1} §e{2}
TEAM_LIST_TEAM_HOVER=§7Team info
TEAM_LIST_PAGE=Page
TEAM_LIST_PAGE=Page »»
TEAM_LIST_NEXT=§eNext page
TEAM_LIST_PREV=§ePrevious page
@ -494,7 +497,7 @@ TEAM_EVENT_NO_EVENT=§cThis event does not exist
TEAM_EVENT_OVER=§cThe registration period for this event is already over
TEAM_EVENT_LEFT=§7Your team no longer takes part in this event
TEAM_EVENT_JOINED=§7Your team now takes part in the event §e{0}§7!
TEAM_EVENT_HOW_TO_LEAVE=§7To cancel the participation, repeat the command
TEAM_EVENT_HOW_TO_LEAVE=§7To cancel the participation repeat the command.
#Team Color
TEAM_COLOR_TITLE=Choose color
@ -621,6 +624,7 @@ VERIFY_INVALID=§cInvalid Code
VERIFY_SUCCESS=§7Successfully linked to the Discord account §e{0}
#Discord
DISCORD_TICKET_HOVER=§eTo the message
DISCORD_TICKET_MESSAGE=§7Ticket §e{0}§7» §f§l{1}: §7{2}
DISCORD_TICKET_NEW=§7Ticket §e{0}§7» §aTicket was created!
DISCORD_TICKET_CLOSED=§7Ticket §e{0}§7» §cTicket was closed!
@ -699,7 +703,30 @@ MOD_AUTOBAN=§cAutoban
MOD_YT=§5YT Only
MOD_ITEM_BACK=§7Back
#StreamInv
INV_PAGE_BACK=§{0}Seite zurück
INV_PAGE_NEXT=§{0}Seite vor
#Discord
DC_UNLINKED=For this action your Discord account has to be linked to your Minecraft account. To link your accounts go onto the SteamWar Discord to the `regeln-infos` Channel and click on `Minecraft Verknüpfen`.
DC_TITLE_SCHEMINFO=Schematic Info
DC_SCHEM_ACCEPT=Your schematic **{0}** has been accepted.
DC_SCHEM_DECLINE=Your schematic **{0}** has been declined.\n**Reason:**{1}
DC_AUTH_SUCCESS=:white_check_mark: You're Discord account has been linked with **{0}**.
DC_ROLE_ADDED=:tada: You're getting {0} now.
DC_ROLE_REMOVED=You're not getting {0} anymore.
DC_TICKET_CREATED=You're Ticket {0} has been created.
DC_TICKET_TITLE=SteamWar Ticket
DC_TICKETINTRO_REPORT=Please answer for the punishment of the misconduct the following questions as accurately as possible and attach evidence whenever possible:\n - Which player(s)?\n - On which Server?\n - At what time?\n - Type and nature of the misconduct?
DC_TICKETINTRO_IDEA=Describe your idea as detailed as possible. Hereto belongs: What, Why, How, Where?
DC_TICKETINTRO_BUG=Please describe the observed unexpected or incorrect behaviour of our software. If necessary describe steps to reproduce the error.
DC_TICKETINTRO_QUESTION=Please ask your question. A staff member will address the question soon.
DC_TICKETINTRO_APPEAL=Asking creates wonders.
DC_TICKET_CLOSE=Close
DC_SCHEMUPLOAD_NOPERM=You're not allowed to upload schematics.
DC_SCHEMUPLOAD_IGNORED=Skipping `{0}`, not a schematic file.
DC_SCHEMUPLOAD_INVCHAR=`{0}` has invalid characters in its name.
DC_SCHEMUPLOAD_SUCCESS=`{0}` was uploaded successfully.
DC_SCHEMUPLOAD_ERROR=An error has occured during the upload of `{0}`. For more information ask a Developer.

Datei anzeigen

@ -7,6 +7,7 @@ TIMEFORMAT=dd.MM.yyyy HH:mm
UNKNOWN_COMMAND=§cUnbekannter Befehl.
UNKNOWN_PLAYER=§cDiesen Spieler gibt es nicht.
UNKNOWN_TEAM=§cDieses Team gibt es nicht.
UNKNOWN_EVENT=$cDieses Event gibt es nicht.
INVALID_TIME=§cUngültige Zeitangabe.
DEV_NO_SERVER=§cDer Server ist derzeit nicht erreichbar.
@ -15,6 +16,7 @@ DEV_UNKNOWN_SERVER=§cBitte gib einen DevServer an.
DISABLED=§cDerzeit deaktiviert.
SERVER_START_OVERLOAD=§cDer Serverstart wurde aufgrund von Überlastung abgebrochen. Versuche es später erneut.
UPDATE_INTERRUPTION=§cBitte erneut versuchen. Ein Softwareupdate hat die Aktion unterbrochen.
#Help command
HELP_LOBBY=§7Kehre von überall mit §8/§el §7zur Lobby zurück!
@ -99,6 +101,7 @@ MOD_RED_SING=Versuchte Benutzung des Mods {0}
MOD_RED_PLUR=Versuchte Benutzung der Mods:\n{0}
MOD_YELLOW_SING=§7Deaktiviere den Mod §e{0}§7, um weiter auf §eSteam§8War §7spielen zu können.
MOD_YELLOW_PLUR=§7Deaktiviere die Mods\n§e{0}\n§7um weiter auf §eSteam§8War §7spielen zu können.
MODS_CHECKED=§7Deine installierten Mods wurden überprüft.\n§aDu kannst nun §eSteam§8War §abetreten§8.
#Various commands
STAT_SERVER=§7Server §e{0}§8: §7Startfähig §e{1} §7Serveranzahl §e{2}
@ -457,7 +460,7 @@ TEAM_LIST_UNKNOWN_PAGE=§cUngültige Seitenzahl angegeben
TEAM_LIST_HEADER=§7§lTeamliste §7{0}§8/§7{1}
TEAM_LIST_TEAM=§{0}{1} §e{2}
TEAM_LIST_TEAM_HOVER=§7Teaminfo
TEAM_LIST_PAGE=Seite
TEAM_LIST_PAGE=Seite »»
TEAM_LIST_NEXT=§eNächste Seite
TEAM_LIST_PREV=§eVorherige Seite
@ -469,7 +472,7 @@ TEAM_EVENT_NO_EVENT=§cDieses Event gibt es nicht
TEAM_EVENT_OVER=§cDie Anmeldephase für dieses Event ist bereits vorbei
TEAM_EVENT_LEFT=§7Dein Team nimmt nicht mehr am Event teil
TEAM_EVENT_JOINED=§7Dein Team nimmt nun am Event §e{0} §7 teil!
TEAM_EVENT_HOW_TO_LEAVE=§7Um die Teilnahme abzusagen, wiederhole den Befehl
TEAM_EVENT_HOW_TO_LEAVE=§7Um die Teilnahme abzusagen, wiederhole den Befehl.
#Team Color
TEAM_COLOR_TITLE=Farbe wählen
@ -596,6 +599,7 @@ VERIFY_INVALID=§cInvalider Code
VERIFY_SUCCESS=§7Erfolgreich mit dem Discord Account §e{0} §7verknüpft
#Discord
DISCORD_TICKET_HOVER=§eZur Nachricht
DISCORD_TICKET_MESSAGE=§7Ticket §e{0}§7» §f§l{1}: §7{2}
DISCORD_TICKET_NEW=§7Ticket §e{0}§7» §aTicket wurde geöffnet!
DISCORD_TICKET_CLOSED=§7Ticket §e{0}§7» §cTicket wurde geschlossen!
@ -652,7 +656,29 @@ ADVENT_CALENDAR_MESSAGE=§eHast du heute schon dein Geschenk geholt?
ADVENT_CALENDAR_MESSAGE_HOVER=§eKlicken zum öffnen!
ADVENT_CALENDAR_OPEN=§7Du hast §e{0}§7 aus dem Adventskalender erhalten!
#StreamInv
INV_PAGE_BACK=§{0}Page back
INV_PAGE_NEXT=§{0}Next page
#Discord
DC_UNLINKED=Für diese Aktion muss dein Minecraftaccount mit deinem Discordaccount verknüpft sein, gehe dazu auf dem SteamWar-Discord in den `regeln-infos` Channel und Klicke auf `Minecraft Verknüpfen`.
DC_TITLE_SCHEMINFO=Schematicinfo
DC_SCHEM_ACCEPT=Deine Schematic **{0}** wurde angenommen.
DC_SCHEM_DECLINE=Deine Schematic **{0}** wurde abgelehnt. **Grund:** \n{1}
DC_AUTH_SUCCESS=:white_check_mark: Dein Discordaccount wurde mit **{0}** verknüpft.
DC_ROLE_ADDED=:tada: Du bekommst nun {0}.
DC_ROLE_REMOVED=Du bekommst nun keine {0} mehr.
DC_TICKET_CREATED=Dein Ticket {0} wurde erstellt.
DC_TICKETINTRO_REPORT=Bitte beantworte für die Ahndung des Fehlverhaltens möglichst genau folgende Fragen und füge nach Möglichkeit Beweismaterial hinzu:\n - Welche(r) Spieler?\n - Auf welchem Server?\n - Zu welchem Zeitpunkt?\n - Art und Natur des Fehlverhaltens?
DC_TICKETINTRO_IDEA=Beschreibe deine Idee möglichst detailiert. Hierzu gehört: Was, Warum, Wie, Wo?
DC_TICKETINTRO_BUG=Bitte beschreibe das beobachtete unerwartete bzw. inkorrekte Verhalten der Serversoftware. Falls notwendig, beschreibe die Schritte, mit denen der Fehler reproduziert werden kann.
DC_TICKETINTRO_QUESTION=Bitte stelle deine Frage, ein Serverteammitglied wird sich dieser zeitnah annehmen.
DC_TICKETINTRO_APPEAL=Fragen wirkt Wunder!
DC_TICKET_CLOSE=Schließen
DC_SCHEMUPLOAD_NOPERM=Du darfst keine Schematics hochladen.
DC_SCHEMUPLOAD_IGNORED=`{0}` wird ignoriert, da die Datei keine Schematic ist.
DC_SCHEMUPLOAD_INVCHAR=`{0}` hat unzulässige Buchstaben im Namen.
DC_SCHEMUPLOAD_SUCCESS=`{0}` wurde erfolgreich hochgeladen.
DC_SCHEMUPLOAD_ERROR=Ein Fehler ist beim Hochladen von `{0}` aufgetreten. Für nähere Informationen wende dich an einen Developer.

Datei anzeigen

@ -19,11 +19,8 @@
package de.steamwar.messages;
import de.steamwar.bungeecore.BungeeCore;
import de.steamwar.bungeecore.Message;
import de.steamwar.bungeecore.Servertype;
import de.steamwar.bungeecore.Subserver;
import de.steamwar.bungeecore.bot.listeners.DiscordChatListener;
import de.steamwar.sql.SteamwarUser;
import de.steamwar.sql.UserPerm;
import net.md_5.bungee.api.ChatMessageType;
@ -47,7 +44,6 @@ import java.util.UUID;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.logging.Level;
import java.util.stream.Stream;
public interface Chatter {
@ -138,7 +134,7 @@ public interface Chatter {
}
default String parseToPlain(Message message) {
return parse(false, message).toPlainText();
return parse(message).toPlainText();
}
default String parseToLegacy(String format, Object... params) {
@ -146,7 +142,15 @@ public interface Chatter {
}
default String parseToLegacy(Message message) {
return parse(false, message).toLegacyText();
return parse(message).toLegacyText();
}
default BaseComponent parse(String format, Object... params) {
return parse(false, new Message(format, params));
}
default BaseComponent parse(Message message) {
return parse(false, message);
}
default BaseComponent parse(boolean prefixed, String format, Object... params) {
@ -174,6 +178,8 @@ public interface Chatter {
params[i] = ((ProxiedPlayer) params[i]).getName();
} else if(params[i] instanceof Chatter) {
params[i] = ((Chatter) params[i]).user().getUserName();
} else if(params[i] instanceof Function) {
params[i] = ((Function) params[i]).apply(this);
}
}
return TextComponent.fromLegacy(format.format(params));
@ -261,52 +267,6 @@ public interface Chatter {
};
}
static Chatter discordChannel(DiscordChatListener channel) {
return new PlayerlessChatter() {
@Override
public SteamwarUser user() {
return SteamwarUser.get(-1);
}
@Override
public boolean chatShown() {
return true;
}
@Override
public void sendMessage(ChatMessageType type, BaseComponent msg) {
try {
channel.send("<t:" + (System.currentTimeMillis() / 1000) + "> " + msg.toPlainText());
} catch (Exception e) {
BungeeCore.get().getLogger().log(Level.SEVERE, "Could not send chat message to discord", e);
}
}
};
}
static Chatter of(net.dv8tion.jda.api.entities.Message message, SteamwarUser user) {
return new PlayerlessChatter() {
@Override
public SteamwarUser user() {
return user;
}
@Override
public boolean chatShown() {
return true;
}
@Override
public void sendMessage(ChatMessageType type, BaseComponent msg) {
try {
message.delete().queue();
} catch (Exception e) {
BungeeCore.get().getLogger().log(Level.SEVERE, "Could not send chat reply to discord user", e);
}
}
};
}
abstract class PlayerlessChatter implements Chatter {
@Override
public Locale getLocale() {

Datei anzeigen

@ -19,7 +19,6 @@
package de.steamwar.messages;
import de.steamwar.bungeecore.Message;
import de.steamwar.sql.SteamwarUser;
import lombok.Getter;
import net.md_5.bungee.api.ChatMessageType;

Datei anzeigen

@ -0,0 +1,34 @@
/*
* This file is a part of the SteamWar software.
*
* Copyright (C) 2024 SteamWar.de-Serverteam
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package de.steamwar.messages;
import lombok.Getter;
@Getter
public class Message {
private final String format;
private final Object[] params;
public Message(String format, Object... params) {
this.format = format;
this.params = params;
}
}

Datei anzeigen

@ -19,8 +19,6 @@
package de.steamwar.messages;
import de.steamwar.bungeecore.Message;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;