More components, broadcasts #98

Merged
NorbiPeti merged 13 commits from dev into master 2019-03-17 01:28:22 +00:00
58 changed files with 1209 additions and 1274 deletions

2
.gitignore vendored
View file

@ -217,7 +217,7 @@ pip-log.txt
.mr.developer.cfg
.metadata/*
TheButtonAutoFlair/out/artifacts/Autoflair/Autoflair.jar
*.iml
#*.iml
*.name
.idea/compiler.xml
*.xml

71
.idea/ButtonChat.iml Normal file
View file

@ -0,0 +1,71 @@
<?xml version="1.0" encoding="UTF-8"?>
<module org.jetbrains.idea.maven.project.MavenProjectsManager.isMavenModule="true" type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_8">
<output url="file://$MODULE_DIR$/target/classes" />
<output-test url="file://$MODULE_DIR$/target/test-classes" />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/src/main/resources" type="java-resource" />
<sourceFolder url="file://$MODULE_DIR$/src/test/java" isTestSource="true" />
<excludeFolder url="file://$MODULE_DIR$/target" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" name="Maven: org.spigotmc:spigot-api:1.12.2-R0.1-SNAPSHOT" level="project" />
<orderEntry type="library" name="Maven: commons-lang:commons-lang:2.6" level="project" />
<orderEntry type="library" name="Maven: com.googlecode.json-simple:json-simple:1.1.1" level="project" />
<orderEntry type="library" name="Maven: com.google.guava:guava:21.0" level="project" />
<orderEntry type="library" name="Maven: com.google.code.gson:gson:2.8.0" level="project" />
<orderEntry type="library" name="Maven: org.yaml:snakeyaml:1.19" level="project" />
<orderEntry type="library" name="Maven: net.md-5:bungeecord-chat:1.12-SNAPSHOT" level="project" />
<orderEntry type="library" name="Maven: com.github.TBMCPlugins.ButtonCore:ButtonCore:master-SNAPSHOT" level="project" />
<orderEntry type="library" name="Maven: net.sourceforge.htmlcleaner:htmlcleaner:2.16" level="project" />
<orderEntry type="library" name="Maven: org.jdom:jdom2:2.0.5" level="project" />
<orderEntry type="library" name="Maven: org.reflections:reflections:0.9.10" level="project" />
<orderEntry type="library" name="Maven: org.javassist:javassist:3.19.0-GA" level="project" />
<orderEntry type="library" name="Maven: com.google.code.findbugs:annotations:2.0.1" level="project" />
<orderEntry type="library" name="Maven: net.ess3:Essentials:2.13.1" level="project" />
<orderEntry type="library" name="Maven: com.github.TBMCPlugins.ButtonCore:Towny:8d3b6b6" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: com.github.milkbowl:VaultAPI:master-68f14eca20-1" level="project" />
<orderEntry type="library" name="Maven: org.bukkit:bukkit:1.13.1-R0.1-SNAPSHOT" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.projectlombok:lombok:1.16.16" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.spigotmc:spigot:1.12.2-R0.1-SNAPSHOT" level="project" />
<orderEntry type="library" name="Maven: com.github.webbukkit:Dynmap-Towny:master-0.60-g924051d-7" level="project" />
<orderEntry type="library" name="Maven: com.github.webbukkit:Dynmap:v2.5" level="project" />
<orderEntry type="library" name="Maven: com.nijikokun.bukkit:Permissions:3.1.6" level="project" />
<orderEntry type="library" name="Maven: ru.tehkode:PermissionsEx:1.19.1" level="project" />
<orderEntry type="library" name="Maven: de.bananaco:bPermissions:2.9.1" level="project" />
<orderEntry type="library" name="Maven: com.platymuus.bukkit.permissions:PermissionsBukkit:1.6" level="project" />
<orderEntry type="library" name="Maven: org.anjocaido:EssentialsGroupManager:2.10.1" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: junit:junit:4.12" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.hamcrest:hamcrest-core:1.3" level="project" />
<orderEntry type="library" name="Maven: org.spigotmc:spigot-api:1.12.2-R0.1-SNAPSHOT" level="project" />
<orderEntry type="library" name="Maven: commons-lang:commons-lang:2.6" level="project" />
<orderEntry type="library" name="Maven: com.googlecode.json-simple:json-simple:1.1.1" level="project" />
<orderEntry type="library" name="Maven: com.google.guava:guava:21.0" level="project" />
<orderEntry type="library" name="Maven: com.google.code.gson:gson:2.8.0" level="project" />
<orderEntry type="library" name="Maven: org.yaml:snakeyaml:1.19" level="project" />
<orderEntry type="library" name="Maven: net.md-5:bungeecord-chat:1.12-SNAPSHOT" level="project" />
<orderEntry type="library" name="Maven: com.github.TBMCPlugins.ButtonCore:ButtonCore:master-SNAPSHOT" level="project" />
<orderEntry type="library" name="Maven: net.sourceforge.htmlcleaner:htmlcleaner:2.16" level="project" />
<orderEntry type="library" name="Maven: org.jdom:jdom2:2.0.5" level="project" />
<orderEntry type="library" name="Maven: org.reflections:reflections:0.9.10" level="project" />
<orderEntry type="library" name="Maven: org.javassist:javassist:3.19.0-GA" level="project" />
<orderEntry type="library" name="Maven: com.google.code.findbugs:annotations:2.0.1" level="project" />
<orderEntry type="library" name="Maven: net.ess3:Essentials:2.13.1" level="project" />
<orderEntry type="library" name="Maven: com.github.TBMCPlugins.ButtonCore:Towny:8d3b6b6" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: com.github.milkbowl:VaultAPI:master-68f14eca20-1" level="project" />
<orderEntry type="library" name="Maven: org.bukkit:bukkit:1.13.1-R0.1-SNAPSHOT" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.projectlombok:lombok:1.16.16" level="project" />
<orderEntry type="library" scope="PROVIDED" name="Maven: org.spigotmc:spigot:1.12.2-R0.1-SNAPSHOT" level="project" />
<orderEntry type="library" name="Maven: com.github.webbukkit:Dynmap-Towny:master-0.60-g924051d-7" level="project" />
<orderEntry type="library" name="Maven: com.github.webbukkit:Dynmap:v2.5" level="project" />
<orderEntry type="library" name="Maven: com.nijikokun.bukkit:Permissions:3.1.6" level="project" />
<orderEntry type="library" name="Maven: ru.tehkode:PermissionsEx:1.19.1" level="project" />
<orderEntry type="library" name="Maven: de.bananaco:bPermissions:2.9.1" level="project" />
<orderEntry type="library" name="Maven: com.platymuus.bukkit.permissions:PermissionsBukkit:1.6" level="project" />
<orderEntry type="library" name="Maven: org.anjocaido:EssentialsGroupManager:2.10.1" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: junit:junit:4.12" level="project" />
<orderEntry type="library" scope="TEST" name="Maven: org.hamcrest:hamcrest-core:1.3" level="project" />
</component>
</module>

17
pom.xml
View file

@ -155,18 +155,14 @@
<id>Essentials</id>
<url>http://repo.ess3.net/content/repositories/essrel/</url>
</repository>
<repository>
<id>Votifier</id>
<url>https://dl.bintray.com/nuvotifier/maven/</url>
</repository>
<repository>
<id>Minigames</id>
<url>http://maven.addstar.com.au/artifactory/release</url>
</repository>
<repository>
<!-- <repository>
<id>vault-repo</id>
<url>http://nexus.hc.to/content/repositories/pub_releases</url>
</repository>
</repository> -->
<!-- <repository> <id>WorldEdit</id> <url>http://maven.sk89q.com/artifactory/repo</url>
</repository> -->
<repository>
@ -207,17 +203,12 @@
<artifactId>Towny</artifactId>
<version>8d3b6b6</version>
</dependency>
<dependency>
<groupId>com.vexsoftware</groupId>
<artifactId>nuvotifier-universal</artifactId>
<version>2.3.4</version>
</dependency>
<!-- <dependency> <groupId>au.com.mineauz</groupId> <artifactId>Minigames</artifactId>
<version>1.8.0</version> </dependency> -->
<dependency>
<groupId>net.milkbowl.vault</groupId>
<groupId>com.github.milkbowl</groupId>
<artifactId>VaultAPI</artifactId>
<version>1.6</version>
<version>master-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>

View file

@ -1,12 +1,15 @@
package buttondevteam.chat;
import buttondevteam.chat.commands.UnlolCommand;
import buttondevteam.chat.commands.ucmds.admin.DebugCommand;
import buttondevteam.chat.components.chatonly.ChatOnlyComponent;
import buttondevteam.chat.components.fun.FunComponent;
import buttondevteam.chat.components.towny.TownyComponent;
import buttondevteam.chat.formatting.ChatFormatter;
import buttondevteam.chat.formatting.TellrawEvent;
import buttondevteam.chat.formatting.TellrawPart;
import buttondevteam.chat.formatting.TellrawSerializer;
import buttondevteam.chat.listener.PlayerListener;
import buttondevteam.core.ComponentManager;
import buttondevteam.core.component.channel.Channel;
import buttondevteam.lib.TBMCChatEvent;
import buttondevteam.lib.TBMCChatEventBase;
@ -52,7 +55,8 @@ public class ChatProcessing {
private static final Pattern SPOILER_PATTERN = Pattern.compile("\\|\\|");
private static final Color[] RainbowPresserColors = new Color[]{Color.Red, Color.Gold, Color.Yellow, Color.Green,
Color.Blue, Color.DarkPurple};
private static boolean pingedconsole = false;
private static final Pattern WORD_PATTERN = Pattern.compile("\\S+");
private static boolean pingedconsole = false;
public static final ChatFormatter ESCAPE_FORMATTER = ChatFormatter.builder().regex(ESCAPE_PATTERN).build();
@ -134,13 +138,13 @@ public class ChatProcessing {
ArrayList<ChatFormatter> formatters = addFormatters(colormode);
if (colormode == channel.Color().get() && mp != null && mp.RainbowPresserColorMode) { // Only overwrite channel color
final AtomicInteger rpc = new AtomicInteger(0);
formatters.add(ChatFormatter.builder().color(colormode).onmatch((match, cf, s) -> {
formatters.add(ChatFormatter.builder().regex(WORD_PATTERN).color(colormode).onmatch((match, cf, s) -> {
cf.setColor(RainbowPresserColors[rpc.getAndUpdate(i -> ++i < RainbowPresserColors.length ? i : 0)]);
return match;
}).build());
}
pingedconsole = false; // Will set it to true onmatch (static constructor)
final String channelidentifier = getChannelID(channel, sender, e.getOrigin());
final String channelidentifier = getChannelID(channel, e.getOrigin());
TellrawPart json = createTellraw(sender, message, player, mp, e.getUser(), channelidentifier, e.getOrigin());
long combinetime = System.nanoTime();
@ -174,16 +178,11 @@ public class ChatProcessing {
if (score < 0) // Never send messages to score below 0
sender.sendMessage("§cYou don't have permission to send this message or something went wrong");
else {
PluginMain.Instance.getServer().dispatchCommand(PluginMain.Console,
String.format("tellraw @a[score_%s=%d,score_%s_min=%d] %s", channel.ID, score, channel.ID,
score, jsonstr));
if (e.getChannel().ID.equals(PluginMain.TownChat.ID)
|| e.getChannel().ID.equals(PluginMain.NationChat.ID)) {
((List<TellrawPart>) json.getExtra()).add(0, new TellrawPart("[SPY]"));
jsonstr = toJson(json);
Bukkit.getServer().dispatchCommand(PluginMain.Console, String.format(
"tellraw @a[score_%s=1000,score_%s_min=1000] %s", channel.ID, channel.ID, jsonstr));
}
PluginMain.Instance.getServer().dispatchCommand(PluginMain.Console,
String.format("tellraw @a[score_%s=%d,score_%s_min=%d] %s", channel.ID, score, channel.ID,
score, jsonstr));
val tc = ComponentManager.getIfEnabled(TownyComponent.class);
if (tc != null) tc.handleSpies(channel, json, ChatProcessing::toJson);
}
} else
PluginMain.Instance.getServer().dispatchCommand(PluginMain.Console,
@ -209,10 +208,7 @@ public class ChatProcessing {
@Nullable ChatPlayer mp, @Nullable ChromaGamerBase cg, final String channelidentifier,
String origin) {
TellrawPart json = new TellrawPart("");
if (mp != null && mp.ChatOnly) {
json.addExtra(new TellrawPart("[C]")
.setHoverEvent(TellrawEvent.create(TellrawEvent.HoverAction.SHOW_TEXT, "Chat only")));
}
ChatOnlyComponent.tellrawCreate(mp, json); //TODO: Make nice API
json.addExtra(
new TellrawPart(channelidentifier)
.setHoverEvent(
@ -242,7 +238,7 @@ public class ChatProcessing {
return player.getDisplayName();
}
static String getChannelID(Channel channel, CommandSender sender, String origin) {
static String getChannelID(Channel channel, String origin) {
return ("[" + (MCORIGIN.equals(origin) ? "" : "§8" + origin.substring(0, 1) + "§r|") + channel.DisplayName().get())
+ "]";
}
@ -295,12 +291,8 @@ public class ChatProcessing {
}
ChatPlayer mpp = TBMCPlayer.getPlayer(nottest ? p.getUniqueId() : new UUID(0, 0), ChatPlayer.class);
if (nottest) {
if (PluginMain.Instance.notificationSound().get().length() == 0)
p.playSound(p.getLocation(), Sound.ENTITY_ARROW_HIT_PLAYER, 1.0f, 0.5f); // TODO: Airhorn
else
p.playSound(p.getLocation(), PluginMain.Instance.notificationSound().get(), 1.0f,
PluginMain.Instance.notificationPitch().get());
}
playPingSound(p);
}
String color = String.format("§%x", (mpp.GetFlairColor() == 0x00 ? 0xb : mpp.GetFlairColor()));
return color + (nottest ? p.getName() : pn.get()) + "§r"; //Fix name casing, except when testing
}).priority(Priority.High).type(ChatFormatter.Type.Excluder).build());
@ -315,12 +307,8 @@ public class ChatProcessing {
+ match.toLowerCase() + " but was reported as online.");
return "§c" + match + "§r";
}
if (PluginMain.Instance.notificationSound().get().length() == 0)
p.playSound(p.getLocation(), Sound.ENTITY_ARROW_HIT_PLAYER, 1.0f, 0.5f); // TODO: Airhorn
else
p.playSound(p.getLocation(), PluginMain.Instance.notificationSound().get(), 1.0f,
PluginMain.Instance.notificationPitch().get());
return PluginMain.essentials.getUser(p).getNickname();
playPingSound(p);
return PluginMain.essentials.getUser(p).getNickname();
}
error.accept("Player nicknamed " + match.toLowerCase()
+ " not found in nickname map but was reported as online.");
@ -330,24 +318,16 @@ public class ChatProcessing {
return formatters;
}
static void doFunStuff(CommandSender sender, TBMCChatEventBase event, String message) {
if (PlayerListener.ActiveF && !PlayerListener.Fs.contains(sender) && message.equalsIgnoreCase("F"))
PlayerListener.Fs.add(sender);
private static void playPingSound(Player p) {
if (PluginMain.Instance.notificationSound().get().length() == 0)
p.playSound(p.getLocation(), Sound.ENTITY_ARROW_HIT_PLAYER, 1.0f, 0.5f); // TODO: Airhorn
else
p.playSound(p.getLocation(), PluginMain.Instance.notificationSound().get(), 1.0f,
PluginMain.Instance.notificationPitch().get());
}
String msg = message.toLowerCase();
val lld = new UnlolCommand.LastlolData(sender, event, System.nanoTime());
boolean add;
if (add = msg.contains("lol"))
lld.setLolornot(true);
else {
for (int i = 0; i < PlayerListener.LaughStrings.length; i++) {
if (add = msg.contains(PlayerListener.LaughStrings[i])) {
lld.setLolornot(false);
break;
}
}
}
if (add)
UnlolCommand.Lastlol.put(event.getChannel(), lld);
static void doFunStuff(CommandSender sender, TBMCChatEventBase event, String message) {
val fc=ComponentManager.getIfEnabled(FunComponent.class);
if(fc!=null) fc.onChat(sender, event, message);
}
}

View file

@ -1,14 +1,19 @@
package buttondevteam.chat;
import buttondevteam.chat.commands.YeehawCommand;
import buttondevteam.chat.commands.MWikiCommand;
import buttondevteam.chat.commands.ucmds.HelpCommand;
import buttondevteam.chat.commands.ucmds.HistoryCommand;
import buttondevteam.chat.commands.ucmds.InfoCommand;
import buttondevteam.chat.commands.ucmds.admin.DebugCommand;
import buttondevteam.chat.components.announce.AnnouncerComponent;
import buttondevteam.chat.components.appendext.AppendTextComponent;
import buttondevteam.chat.components.flair.FlairComponent;
import buttondevteam.chat.components.fun.FunComponent;
import buttondevteam.chat.components.towncolors.TownColorComponent;
import buttondevteam.chat.components.towncolors.TownyListener;
import buttondevteam.chat.components.towny.TownyComponent;
import buttondevteam.chat.listener.PlayerJoinLeaveListener;
import buttondevteam.chat.listener.PlayerListener;
import buttondevteam.core.MainPlugin;
import buttondevteam.core.component.channel.Channel;
import buttondevteam.lib.TBMCCoreAPI;
import buttondevteam.lib.architecture.ButtonPlugin;
@ -17,7 +22,6 @@ import buttondevteam.lib.architecture.ConfigData;
import buttondevteam.lib.chat.Color;
import buttondevteam.lib.chat.TBMCChatAPI;
import com.earth2me.essentials.Essentials;
import net.milkbowl.vault.chat.Chat;
import net.milkbowl.vault.economy.Economy;
import net.milkbowl.vault.permission.Permission;
import org.bukkit.Bukkit;
@ -33,9 +37,6 @@ public class PluginMain extends ButtonPlugin { // Translated to Java: 2015.07.15
public static Scoreboard SB;
public static Channel TownChat;
public static Channel NationChat;
public ConfigData<String> notificationSound() {
return getIConfig().getData("notificationSound", "");
}
@ -52,23 +53,30 @@ public class PluginMain extends ButtonPlugin { // Translated to Java: 2015.07.15
TBMCCoreAPI.RegisterEventsForExceptions(new PlayerListener(), this);
TBMCCoreAPI.RegisterEventsForExceptions(new PlayerJoinLeaveListener(), this);
TBMCCoreAPI.RegisterEventsForExceptions(new TownyListener(), this);
TBMCChatAPI.AddCommands(this, YeehawCommand.class);
MainPlugin.Instance.setChatHandlerEnabled(false); //Disable Core chat handler
Console = this.getServer().getConsoleSender();
SB = getServer().getScoreboardManager().getMainScoreboard(); // Main can be detected with @a[score_...]
Component.registerComponent(this, new TownyComponent());
if (Bukkit.getPluginManager().isPluginEnabled("Towny"))
Component.registerComponent(this, new TownyComponent());
TBMCChatAPI.RegisterChatChannel(new Channel("§7RP§f", Color.Gray, "rp", null)); //Since it's null, it's recognised as global
if (!setupEconomy() || !setupPermissions())
TBMCCoreAPI.SendException("We're in trouble", new Exception("Failed to set up economy or permissions!"));
Component.registerComponent(this, new TownColorComponent());
if (Bukkit.getPluginManager().isPluginEnabled("Towny"))
Component.registerComponent(this, new TownColorComponent());
Component.registerComponent(this, new FlairComponent()); //The original purpose of this plugin
Component.registerComponent(this, new AnnouncerComponent());
Component.registerComponent(this, new FunComponent());
Component.registerComponent(this, new AppendTextComponent());
getCommand2MC().registerCommand(new DebugCommand());
getCommand2MC().registerCommand(new HelpCommand());
getCommand2MC().registerCommand(new HistoryCommand());
getCommand2MC().registerCommand(new InfoCommand());
getCommand2MC().registerCommand(new MWikiCommand());
}
public static Essentials essentials = null;
@ -80,11 +88,10 @@ public class PluginMain extends ButtonPlugin { // Translated to Java: 2015.07.15
public static Permission permission = null;
public static Economy economy = null;
public static Chat chat = null;
private boolean setupPermissions() {
RegisteredServiceProvider<Permission> permissionProvider = getServer().getServicesManager()
.getRegistration(net.milkbowl.vault.permission.Permission.class);
.getRegistration(net.milkbowl.vault.permission.Permission.class);
if (permissionProvider != null) {
permission = permissionProvider.getProvider();
}
@ -93,7 +100,7 @@ public class PluginMain extends ButtonPlugin { // Translated to Java: 2015.07.15
private boolean setupEconomy() {
RegisteredServiceProvider<Economy> economyProvider = getServer().getServicesManager()
.getRegistration(net.milkbowl.vault.economy.Economy.class);
.getRegistration(net.milkbowl.vault.economy.Economy.class);
if (economyProvider != null) {
economy = economyProvider.getProvider();
}

View file

@ -1,32 +0,0 @@
package buttondevteam.chat.commands;
import org.bukkit.GameMode;
import org.bukkit.entity.Player;
import buttondevteam.chat.ChatPlayer;
import buttondevteam.lib.chat.CommandClass;
import buttondevteam.lib.chat.PlayerCommandBase;
import buttondevteam.lib.player.TBMCPlayer;
@CommandClass(modOnly = false)
public final class ChatonlyCommand extends PlayerCommandBase {
@Override
public String[] GetHelpText(String alias) {
return new String[] { "§6---- Chat-only mode ----", //
"This mode makes you invincible but unable to move, teleport or interact with the world in any way", //
"It was designed for chat clients", //
"Once enabled, the only way of disabling it is by relogging to the server" //
};
}
@Override
public boolean OnCommand(Player player, String alias, String[] args) {
ChatPlayer p = TBMCPlayer.getPlayer(player.getUniqueId(), ChatPlayer.class);
p.ChatOnly = true;
player.setGameMode(GameMode.SPECTATOR);
player.sendMessage("§bChat-only mode enabled. You are now invincible.");
return true;
}
}

View file

@ -1,42 +1,33 @@
package buttondevteam.chat.commands;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import org.bukkit.command.CommandSender;
import buttondevteam.lib.chat.CommandClass;
import buttondevteam.lib.chat.TBMCCommandBase;
@CommandClass(modOnly = false)
public class MWikiCommand extends TBMCCommandBase {
@Override
public String[] GetHelpText(String alias) {
return new String[] { "§6---- Minecraft Wiki linker ----", //
"Use without parameters to get a link to the wiki", //
"You can also search the wiki, for example:", //
" /" + alias + " beacon - Provides a link that redirects to the beacon's wiki page" //
};
}
@Override
public boolean OnCommand(CommandSender sender, String alias, String[] args) {
String query = "";
for (int i = 0; i < args.length; i++)
query += args[i] + " ";
query = query.trim();
try {
if (query.length() == 0)
sender.sendMessage(new String[] { "§bMinecraft Wiki link: http://minecraft.gamepedia.com/",
"You can also search on it using /mwiki <query>" });
else
sender.sendMessage("§bMinecraft Wiki link: http://minecraft.gamepedia.com/index.php?search="
+ URLEncoder.encode(query, "UTF-8") + "&title=Special%3ASearch&go=Go");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return true;
}
}
package buttondevteam.chat.commands;
import buttondevteam.lib.chat.Command2;
import buttondevteam.lib.chat.CommandClass;
import buttondevteam.lib.chat.ICommand2MC;
import org.bukkit.command.CommandSender;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
@CommandClass(modOnly = false, helpText = {
"Minecraft Wiki linker", //
"Use without parameters to get a link to the wiki", //
"You can also search the wiki, for example:", //
" /mwiki beacon - Provides a link that redirects to the beacon's wiki page" //
})
public class MWikiCommand extends ICommand2MC {
@Command2.Subcommand
public boolean def(CommandSender sender, @Command2.OptionalArg String query) {
try {
if (query == null)
sender.sendMessage(new String[] { "§bMinecraft Wiki link: http://minecraft.gamepedia.com/",
"You can also search on it using /mwiki <query>" });
else
sender.sendMessage("§bMinecraft Wiki link: http://minecraft.gamepedia.com/index.php?search="
+ URLEncoder.encode(query, "UTF-8") + "&title=Special%3ASearch&go=Go");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return true;
}
}

View file

@ -1,27 +0,0 @@
package buttondevteam.chat.commands.appendtext;
import buttondevteam.lib.chat.ChatMessage;
import buttondevteam.lib.chat.CommandClass;
import buttondevteam.lib.chat.TBMCChatAPI;
import buttondevteam.lib.chat.TBMCCommandBase;
import buttondevteam.lib.player.ChromaGamerBase;
import org.bukkit.command.CommandSender;
@CommandClass(modOnly = false, excludeFromPath = true)
public abstract class AppendTextCommandBase extends TBMCCommandBase {
public abstract String[] GetHelpText(String alias);
public abstract String GetAppendedText();
@Override
public boolean OnCommand(CommandSender sender, String alias, String[] args) {
StringBuilder msg = new StringBuilder();
for (String arg : args) msg.append(arg).append(" ");
msg.append(GetAppendedText());
TBMCChatAPI.SendChatMessage(ChatMessage.builder(sender,
ChromaGamerBase.getFromSender(sender), msg.toString())
.fromCommand(true).build());
return true;
}
}

View file

@ -1,18 +0,0 @@
package buttondevteam.chat.commands.appendtext;
public final class LennyCommand extends AppendTextCommandBase {
@Override
public String[] GetHelpText(String alias) {
return new String[] { "§6---- Lenny ----", //
"This command appends a Lenny face after your message", //
"Or just sends one", //
"Use either /" + alias + " <message> or just /" + alias }; //
}
@Override
public String GetAppendedText() {
return "( ͡° ͜ʖ ͡°)";
}
}

View file

@ -1,18 +0,0 @@
package buttondevteam.chat.commands.appendtext;
public final class ShrugCommand extends AppendTextCommandBase {
@Override
public String[] GetHelpText(String alias) {
return new String[] { "§6---- Shrug ----", //
"This command appends a shrug after your message", //
"Or just makes you shrug", //
"Use either /" + alias + " <message> or just /" + alias }; //
}
@Override
public String GetAppendedText() {
return "¯\\\\\\_(ツ)\\_/¯";
}
}

View file

@ -1,17 +0,0 @@
package buttondevteam.chat.commands.appendtext;
public final class TableflipCommand extends AppendTextCommandBase {
@Override
public String[] GetHelpText(String alias) {
return new String[] { "§6---- Tableflip ----", //
"This command appends a tableflip after your message", //
"Or just makes you tableflip", //
"Use either /" + alias + " <message> or just /" + alias };
}
@Override
public String GetAppendedText() {
return "(╯°□°)╯︵ ┻━┻";
}
}

View file

@ -1,18 +0,0 @@
package buttondevteam.chat.commands.appendtext;
public final class UnflipCommand extends AppendTextCommandBase {
@Override
public String[] GetHelpText(String alias) {
return new String[] { "§6---- Unflip ----", //
"This command appends an unflip after your message", //
"Or just unflips as you", //
"Use either /" + alias + " <message> or just /" + alias };
}
@Override
public String GetAppendedText() {
return "┬─┬ ( ゜-゜ノ)";
}
}

View file

@ -1,19 +0,0 @@
package buttondevteam.chat.commands.appendtext;
import buttondevteam.lib.chat.CommandClass;
@CommandClass(modOnly = false)
public class WaitWhatCommand extends AppendTextCommandBase {
@Override
public String[] GetHelpText(String alias) {
return new String[] { //
"§6--- Wait what ----", //
"Wait what" //
};
}
@Override
public String GetAppendedText() {
return "wait what";
}
}

View file

@ -1,84 +1,79 @@
package buttondevteam.chat.commands.ucmds;
import java.util.ArrayList;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import buttondevteam.chat.PluginMain;
import buttondevteam.lib.chat.CommandClass;
import buttondevteam.lib.chat.TBMCChatAPI;
import buttondevteam.lib.chat.TBMCCommandBase;
@CommandClass(modOnly = false)
public final class HelpCommand extends UCommandBase {
@Override
public String[] GetHelpText(String alias) {
return new String[] { "§6---- Help ----", "Prints out help messages for the TBMC plugins" };
}
@Override
public boolean OnCommand(CommandSender sender, String alias, String[] args) {
if (args.length == 0) {
sender.sendMessage(new String[] { "§6---- TBMC Help ----", "Do /u help <topic> for more info",
"Do /u help <commandname> [subcommands] for more info about a command", "Topics:",
"commands: See all the commands from this plugin",
"chat: Shows some info about custom chat features", "colors: Shows Minecraft color codes" });
return true;
}
if (args[0].equalsIgnoreCase("chat"))
sender.sendMessage(new String[] { "§6---- Chat features ----",
"- [g] Channel identifier: Click it to copy message", "-- [g]: Global chat (/g)",
"-- [TC] Town chat (/tc)", "-- [NC] Nation chat (/nc)",
"- Playernames: Hover over them to get some player info",
"-- Respect: This is the number of paid respects divided by eliglble deaths. This is a reference to CoD:AW's \"Press F to pay respects\"" });
else if (args[0].equalsIgnoreCase("commands")) {
ArrayList<String> text = new ArrayList<String>();
text.add("§6---- Command list ----");
for (TBMCCommandBase cmd : TBMCChatAPI.GetCommands().values())
if (!cmd.getClass().getAnnotation(CommandClass.class).modOnly() || PluginMain.permission.has(sender, "tbmc.admin"))
if (!cmd.isPlayerOnly() || sender instanceof Player)
if (!cmd.GetCommandPath().contains(" "))
text.add("/" + cmd.GetCommandPath());
else {
final String topcmd = cmd.GetCommandPath().substring(0, cmd.GetCommandPath().indexOf(' '));
if (!text.contains("/" + topcmd))
text.add("/" + topcmd);
}
sender.sendMessage(text.toArray(new String[text.size()]));
} else if (args[0].equalsIgnoreCase("colors")) {
sender.sendMessage(new String[] { "§6---- Chat colors/formats ----", //
"Tellraw name - Code | Tellraw name - Code", //
"§0black - &0 | §1dark_blue - &1", //
"§2dark_green - &2 | §3dark_aqua - &3", //
"§4dark_red - &4 | §5dark_purple - &5", //
"§6gold - &6 | §7gray - &7", //
"§8dark_gray - &8 | §9blue - &9", //
"§agreen - &a | §baqua - &b", //
"§cred - &c | §dlight_purple - &d", //
"§eyellow - &e | §fwhite - &f", //
"§rreset - &r | §kk§robfuscated - &k", //
"§lbold - &l | §mstrikethrough - &m", //
"§nunderline - &n | §oitalic - &o", //
"The format codes in tellraw should be used like \"italic\":\"true\"" }); //
} else {
String path = args[0];
for (int i = 1; i < args.length; i++)
path += " " + args[i];
TBMCCommandBase cmd = TBMCChatAPI.GetCommands().get(path);
if (cmd == null) {
String[] subcmds = TBMCChatAPI.GetSubCommands(path, sender);
if (subcmds.length > 0)
sender.sendMessage(subcmds);
else
sender.sendMessage(
new String[] { "§cError: Command not found or you don't have permission for it: " + path,
"Usage example: /u accept --> /u help u accept" });
} else
sender.sendMessage(cmd.GetHelpText(args[0]));
}
return true;
}
}
package buttondevteam.chat.commands.ucmds;
import buttondevteam.chat.PluginMain;
import buttondevteam.lib.chat.Command2;
import buttondevteam.lib.chat.CommandClass;
import buttondevteam.lib.chat.TBMCChatAPI;
import buttondevteam.lib.chat.TBMCCommandBase;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.ArrayList;
@CommandClass(modOnly = false, helpText = {
"Help",
"Prints out help messages for the TBMC plugins"
})
public final class HelpCommand extends UCommandBase {
@Command2.Subcommand
public boolean def(CommandSender sender, @Command2.TextArg @Command2.OptionalArg String topicOrCommand) {
if (topicOrCommand == null) {
sender.sendMessage(new String[]{
"§6---- Thorpe Help ----",
"Do /u help <topic> for more info",
"Do /u help <commandname> [subcommands] for more info about a command",
"Topics:",
"commands: See all the commands from this plugin",
"chat: Shows some info about custom chat features",
"colors: Shows Minecraft color codes"
});
return true;
}
if (topicOrCommand.equalsIgnoreCase("chat"))
sender.sendMessage(new String[]{"§6---- Chat features ----",
"- [g] Channel identifier: Click it to copy message", "-- [g]: Global chat (/g)",
"-- [TC] Town chat (/tc)", "-- [NC] Nation chat (/nc)",
"- Playernames: Hover over them to get some player info",
"-- Respect: This is the number of paid respects divided by eliglble deaths. This is a reference to CoD:AW's \"Press F to pay respects\""});
else if (topicOrCommand.equalsIgnoreCase("commands")) {
ArrayList<String> text = new ArrayList<String>();
text.add("§6---- Command list ----");
for (TBMCCommandBase cmd : TBMCChatAPI.GetCommands().values())
if (!cmd.getClass().getAnnotation(CommandClass.class).modOnly() || PluginMain.permission.has(sender, "tbmc.admin"))
if (!cmd.isPlayerOnly() || sender instanceof Player)
if (!cmd.GetCommandPath().contains(" "))
text.add("/" + cmd.GetCommandPath());
else {
final String topcmd = cmd.GetCommandPath().substring(0, cmd.GetCommandPath().indexOf(' '));
if (!text.contains("/" + topcmd))
text.add("/" + topcmd);
}
sender.sendMessage(text.toArray(new String[0]));
} else if (topicOrCommand.equalsIgnoreCase("colors")) {
sender.sendMessage(new String[]{"§6---- Chat colors/formats ----", //
"Tellraw name - Code | Tellraw name - Code", //
"§0black - &0 | §1dark_blue - &1", //
"§2dark_green - &2 | §3dark_aqua - &3", //
"§4dark_red - &4 | §5dark_purple - &5", //
"§6gold - &6 | §7gray - &7", //
"§8dark_gray - &8 | §9blue - &9", //
"§agreen - &a | §baqua - &b", //
"§cred - &c | §dlight_purple - &d", //
"§eyellow - &e | §fwhite - &f", //
"§rreset - &r | §kk§robfuscated - &k", //
"§lbold - &l | §mstrikethrough - &m", //
"§nunderline - &n | §oitalic - &o", //
"The format codes in tellraw should be used like \"italic\":\"true\""}); //
} else {
String[] text = getManager().getHelpText(topicOrCommand);
if (text == null)
sender.sendMessage(
new String[]{"§cError: Command not found: " + topicOrCommand,
"Usage example: /u accept --> /u help u accept"});
else
sender.sendMessage(text);
}
return true;
}
}

View file

@ -2,48 +2,43 @@ package buttondevteam.chat.commands.ucmds;
import buttondevteam.core.component.channel.Channel;
import buttondevteam.lib.chat.ChatMessage;
import buttondevteam.lib.chat.Command2;
import buttondevteam.lib.chat.CommandClass;
import lombok.RequiredArgsConstructor;
import lombok.experimental.var;
import lombok.val;
import org.bukkit.command.CommandSender;
import javax.annotation.Nullable;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Function;
import java.util.stream.Stream;
@CommandClass
@CommandClass(helpText = {
"§6--- Chat History ----", //
"Returns the last 10 messages the player can see." //
})
public class HistoryCommand extends UCommandBase {
/**
* Key: ChannelID_groupID
*/
private static HashMap<String, LinkedList<HistoryEntry>> messages = new HashMap<>();
@Override
public String[] GetHelpText(String alias) {
return new String[]{ //
"§6--- Chat History ----", //
"Returns the last 10 messages the player can see." //
};
@Command2.Subcommand
public boolean def(CommandSender sender, @Command2.OptionalArg String channel) {
return showHistory(sender, channel);
}
@Override
public boolean OnCommand(CommandSender sender, String alias, String[] args) {
return showHistory(sender, alias, args, this);
}
public static boolean showHistory(CommandSender sender, String alias, String[] args, @Nullable HistoryCommand hc) {
public static boolean showHistory(CommandSender sender, String channel) {
Function<Channel, LinkedList<HistoryEntry>> getThem = ch -> messages.get(ch.ID + "_" + ch.getGroupID(sender)); //If can't see, groupID is null, and that shouldn't be in the map
sender.sendMessage("§6---- Chat History ----");
Stream<Channel> stream;
if (args.length == 0) {
if (channel == null) {
stream = Channel.getChannels();
} else {
Optional<Channel> och = Channel.getChannels().filter(chan -> chan.ID.equalsIgnoreCase(args[0])).findAny();
Optional<Channel> och = Channel.getChannels().filter(chan -> chan.ID.equalsIgnoreCase(channel)).findAny();
if (!och.isPresent()) {
sender.sendMessage("§cChannel not found. Use the ID, for example: /" + (hc == null ? "u history" : hc.GetCommandPath()) + " g");
sender.sendMessage("§cChannel not found. Use the ID, for example: /u history g");
return true;
}
stream = Stream.of(och.get());

View file

@ -1,44 +1,35 @@
package buttondevteam.chat.commands.ucmds;
import org.bukkit.command.CommandSender;
import buttondevteam.lib.TBMCCoreAPI;
import buttondevteam.lib.chat.CommandClass;
import buttondevteam.lib.player.TBMCPlayer;
import buttondevteam.lib.player.ChromaGamerBase.InfoTarget;
import buttondevteam.lib.player.TBMCPlayerBase;
@CommandClass(modOnly = false)
public class InfoCommand extends UCommandBase {
@Override
public String[] GetHelpText(String alias) {
return new String[] { //
"§6---- User information ----", //
"Get some information known about the user.", //
"Usage: /" + alias + " info <playername>" //
};
}
@Override
public boolean OnCommand(CommandSender sender, String alias, String[] args) {
if (args.length == 0)
return false;
if (args[0].equalsIgnoreCase("console") || args[0].equalsIgnoreCase("server")
|| args[0].equalsIgnoreCase("@console")) {
sender.sendMessage("The server console.");
return true;
}
try (TBMCPlayer p = TBMCPlayerBase.getFromName(args[0], TBMCPlayer.class)) {
if (p == null) {
sender.sendMessage("§cThe specified player cannot be found");
return true;
}
sender.sendMessage(p.getInfo(InfoTarget.MCCommand));
} catch (Exception e) {
TBMCCoreAPI.SendException("Error while getting player information!", e);
sender.sendMessage("§cError while getting player information!");
}
return true;
}
}
package buttondevteam.chat.commands.ucmds;
import buttondevteam.lib.TBMCCoreAPI;
import buttondevteam.lib.chat.Command2;
import buttondevteam.lib.chat.CommandClass;
import buttondevteam.lib.player.ChromaGamerBase.InfoTarget;
import buttondevteam.lib.player.TBMCPlayer;
import buttondevteam.lib.player.TBMCPlayerBase;
import org.bukkit.command.CommandSender;
@CommandClass(modOnly = false, helpText = {
"User information", //
"Get some information known about the user.", //
})
public class InfoCommand extends UCommandBase {
@Command2.Subcommand
public boolean def(CommandSender sender, String player) {
if (player.equalsIgnoreCase("console") || player.equalsIgnoreCase("server")
|| player.equalsIgnoreCase("@console")) {
sender.sendMessage("The server console.");
return true;
}
try (TBMCPlayer p = TBMCPlayerBase.getFromName(player, TBMCPlayer.class)) {
if (p == null) {
sender.sendMessage("§cThe specified player cannot be found");
return true;
}
sender.sendMessage(p.getInfo(InfoTarget.MCCommand));
} catch (Exception e) {
TBMCCoreAPI.SendException("Error while getting player information!", e);
sender.sendMessage("§cError while getting player information!");
}
return true;
}
}

View file

@ -1,21 +0,0 @@
package buttondevteam.chat.commands.ucmds;
import org.bukkit.command.CommandSender;
import buttondevteam.lib.chat.CommandClass;
@CommandClass(modOnly = false)
public class OpmeCommand extends UCommandBase {
@Override
public String[] GetHelpText(String alias) {
return new String[] { "§6---- OP me ----", "Totally makes you OP" };
}
@Override
public boolean OnCommand(CommandSender sender, String alias, String[] args) {
sender.sendMessage("It would be nice, wouldn't it?");
return true;
}
}

View file

@ -1,13 +1,10 @@
package buttondevteam.chat.commands.ucmds;
import buttondevteam.lib.chat.CommandClass;
import buttondevteam.lib.chat.OptionallyPlayerCommandBase;
import buttondevteam.lib.chat.OptionallyPlayerCommandClass;
@CommandClass(modOnly = false, path = "u")
@OptionallyPlayerCommandClass(playerOnly = false)
public abstract class UCommandBase extends OptionallyPlayerCommandBase {
public abstract String[] GetHelpText(String alias);
}
package buttondevteam.chat.commands.ucmds;
import buttondevteam.lib.chat.CommandClass;
import buttondevteam.lib.chat.ICommand2MC;
import buttondevteam.lib.chat.OptionallyPlayerCommandClass;
@CommandClass(modOnly = false, path = "u")
@OptionallyPlayerCommandClass(playerOnly = false)
public abstract class UCommandBase extends ICommand2MC {
}

View file

@ -1,11 +1,9 @@
package buttondevteam.chat.commands.ucmds.admin;
import buttondevteam.chat.commands.ucmds.UCommandBase;
import buttondevteam.lib.chat.CommandClass;
@CommandClass(modOnly = true)
public abstract class AdminCommandBase extends UCommandBase {
public abstract String[] GetHelpText(String alias);
}
package buttondevteam.chat.commands.ucmds.admin;
import buttondevteam.chat.commands.ucmds.UCommandBase;
import buttondevteam.lib.chat.CommandClass;
@CommandClass(modOnly = true)
public abstract class AdminCommandBase extends UCommandBase {
}

View file

@ -1,29 +1,28 @@
package buttondevteam.chat.commands.ucmds.admin;
import org.bukkit.command.CommandSender;
import buttondevteam.chat.PluginMain;
public class DebugCommand extends AdminCommandBase {
public static boolean DebugMode = false;
@Override
public String[] GetHelpText(String alias) {
return new String[] { "§6---- Debug mode ----",
"Toggles debug mode, which prints debug messages to the console." };
}
@Override
public boolean OnCommand(CommandSender sender, String alias, String[] args) {
sender.sendMessage("§eDebug mode " + ((DebugMode = !DebugMode) ? "§aenabled." : "§cdisabled."));
return true;
}
public static void SendDebugMessage(String message) {
if (DebugMode)
if (PluginMain.Instance != null)
PluginMain.Instance.getLogger().info(message);
else
System.out.println(message);
}
}
package buttondevteam.chat.commands.ucmds.admin;
import buttondevteam.chat.PluginMain;
import buttondevteam.lib.chat.Command2;
import buttondevteam.lib.chat.CommandClass;
import org.bukkit.command.CommandSender;
@CommandClass(helpText = {
"Debug mode",
"Toggles debug mode, which prints debug messages to the console."
})
public class DebugCommand extends AdminCommandBase {
public static boolean DebugMode = false;
@Command2.Subcommand
public boolean def(CommandSender sender, String alias, String[] args) {
sender.sendMessage("§eDebug mode " + ((DebugMode = !DebugMode) ? "§aenabled." : "§cdisabled."));
return true;
}
public static void SendDebugMessage(String message) {
if (DebugMode)
if (PluginMain.Instance != null)
PluginMain.Instance.getLogger().info(message);
else
System.out.println(message);
}
}

View file

@ -1,43 +0,0 @@
package buttondevteam.chat.commands.ucmds.admin;
import org.bukkit.command.CommandSender;
import buttondevteam.chat.ChatPlayer;
import buttondevteam.lib.player.TBMCPlayerBase;
public class PlayerInfoCommand extends AdminCommandBase {
@Override
public String[] GetHelpText(String alias) {
return new String[] { "§6---- Player info ----",
"Shows some info about the player's flair, Reddit username(s) and other data known by the plugin",
"Usage: /u admin playerinfo <player>" };
}
@Override
public boolean OnCommand(CommandSender sender, String alias, String[] args) {
if (args.length == 0) {
return false;
}
ChatPlayer p = TBMCPlayerBase.getFromName(args[0], ChatPlayer.class);
if (p == null) {
sender.sendMessage("§cPlayer not found: " + args[0] + "§r");
return true;
}
StringBuilder sb = new StringBuilder();
sb.append("§6Usernames:");
for (String username : p.UserNames())
sb.append(" ").append(username);
sender.sendMessage(new String[] { //
"Player name: " + p.PlayerName(), //
"User flair: " + p.GetFormattedFlair(), //
"Username: " + p.UserName(), //
"Flair state: " + p.FlairState(), //
sb.toString(), //
"FCount: " + p.FCount(), //
"FDeaths: " + p.FDeaths() //
});
return true;
}
}

View file

@ -1,40 +0,0 @@
package buttondevteam.chat.commands.ucmds.admin;
import buttondevteam.chat.PluginMain;
import buttondevteam.core.component.updater.PluginUpdater;
import buttondevteam.lib.TBMCCoreAPI;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
public class UpdatePlugin extends AdminCommandBase {
@Override
public String[] GetHelpText(String alias) {
return new String[] { //
"§6---- Update plugin ----", //
"This command downloads the latest version of a TBMC plugin from GitHub", //
"To update a plugin: /" + alias + " <plugin>", //
"To list the plugin names: /" + alias //
};
}
@Override
public boolean OnCommand(CommandSender sender, String alias, String[] args) {
Bukkit.getScheduler().runTaskAsynchronously(PluginMain.Instance, () -> {
if (args.length == 0) {
sender.sendMessage("Downloading plugin names...");
boolean first = true;
for (String plugin : PluginUpdater.GetPluginNames()) {
if (first) {
sender.sendMessage("§6---- Plugin names ----");
first = false;
}
sender.sendMessage("- " + plugin);
}
} else
TBMCCoreAPI.UpdatePlugin(args[0], sender, args.length == 1 ? "master" : args[1]);
});
return true;
}
}

View file

@ -1,36 +0,0 @@
package buttondevteam.chat.components.announce;
import org.bukkit.command.CommandSender;
public class AddCommand extends AnnounceCommandBase {
@Override
public String[] GetHelpText(String alias) {
return new String[] {
"§6---- Add announcement ----",
"This command adds a new announcement",
"Note: Please avoid using this command, if possible",
"Instead, use the command blocks in flatworld to set announcements",
"This makes editing announcements easier" };
}
@Override
public boolean OnCommand(CommandSender sender, String alias,
String[] args) {
if (args.length < 1) {
return false;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < args.length; i++) {
sb.append(args[i]);
if (i != args.length - 1)
sb.append(" ");
}
String finalmessage = sb.toString().replace('&', '§');
AnnouncerComponent component = (AnnouncerComponent) getComponent();
component.AnnounceMessages().get().add(finalmessage);
sender.sendMessage("§bAnnouncement added. - Plase avoid using this command if possible, see /u announce add without args.§r");
return true;
}
}

View file

@ -0,0 +1,80 @@
package buttondevteam.chat.components.announce;
import buttondevteam.chat.commands.ucmds.UCommandBase;
import buttondevteam.lib.chat.Command2;
import buttondevteam.lib.chat.CommandClass;
import buttondevteam.lib.chat.OptionallyPlayerCommandClass;
import lombok.RequiredArgsConstructor;
import lombok.val;
import org.bukkit.command.CommandSender;
@CommandClass(modOnly = true)
@OptionallyPlayerCommandClass(playerOnly = false)
@RequiredArgsConstructor
public class AnnounceCommand extends UCommandBase {
private final AnnouncerComponent component;
@Command2.Subcommand(helpText = {
"Add announcement",
"This command adds a new announcement",
})
public boolean add(CommandSender sender, @Command2.TextArg String text) {
String finalmessage = text.replace('&', '§');
component.AnnounceMessages().get().add(finalmessage);
sender.sendMessage("§bAnnouncement added.§r");
return true;
}
@Command2.Subcommand(helpText = {
"Edit announcement",
"This command lets you edit an announcement by its index.",
"Shouldn't be used directly, use either command blocks or click on an announcement in /u announce list (WIP) instead." //TODO: <--
})
public boolean edit(CommandSender sender, byte index, @Command2.TextArg String text) {
String finalmessage1 = text.replace('&', '§');
if (index > 100)
return false;
while (component.AnnounceMessages().get().size() <= index)
component.AnnounceMessages().get().add("");
component.AnnounceMessages().get().set(index, finalmessage1);
sender.sendMessage("Announcement edited.");
return true;
}
@Command2.Subcommand(helpText = {
"List announcements",
"This command lists the announcements and the time between them"
})
public boolean list(CommandSender sender) {
sender.sendMessage("§bList of announce messages:§r");
sender.sendMessage("§bFormat: [index] message§r");
int i = 0;
for (String message : component.AnnounceMessages().get())
sender.sendMessage("[" + i++ + "] " + message);
sender.sendMessage("§bCurrent wait time between announcements: "
+ component.AnnounceTime().get() / 60 / 1000 + " minute(s)§r");
return true;
}
@Command2.Subcommand(helpText = {
"Remove announcement",
"This command removes an announcement"
})
public boolean remove(CommandSender sender, int index) {
val msgs = component.AnnounceMessages().get();
if (index < 0 || index > msgs.size()) return false;
msgs.remove(index);
sender.sendMessage("Announcement removed.");
return true;
}
@Command2.Subcommand(helpText = {
"Set time",
"This command sets the time between the announcements"
})
public boolean settime(CommandSender sender, int minutes) {
component.AnnounceTime().set(minutes * 60 * 1000);
sender.sendMessage("Time set between announce messages to " + minutes + " minutes");
return true;
}
}

View file

@ -1,13 +0,0 @@
package buttondevteam.chat.components.announce;
import buttondevteam.chat.commands.ucmds.UCommandBase;
import buttondevteam.lib.chat.CommandClass;
import buttondevteam.lib.chat.OptionallyPlayerCommandClass;
@CommandClass(modOnly = true)
@OptionallyPlayerCommandClass(playerOnly = false)
public abstract class AnnounceCommandBase extends UCommandBase {
public abstract String[] GetHelpText(String alias);
}

View file

@ -1,12 +1,16 @@
package buttondevteam.chat.components.announce;
import buttondevteam.chat.PluginMain;
import buttondevteam.core.component.channel.Channel;
import buttondevteam.lib.TBMCSystemChatEvent;
import buttondevteam.lib.architecture.Component;
import buttondevteam.lib.architecture.ConfigData;
import buttondevteam.lib.chat.TBMCChatAPI;
import org.bukkit.Bukkit;
import java.util.ArrayList;
public class AnnouncerComponent extends Component implements Runnable {
public class AnnouncerComponent extends Component<PluginMain> implements Runnable {
public ConfigData<ArrayList<String>> AnnounceMessages() {
return getConfig().getData("announceMessages", new ArrayList<>(0));
}
@ -14,6 +18,9 @@ public class AnnouncerComponent extends Component implements Runnable {
public ConfigData<Integer> AnnounceTime() {
return getConfig().getData("announceTime", 15 * 60 * 1000);
}
private TBMCSystemChatEvent.BroadcastTarget target;
private static int AnnounceMessageIndex = 0;
@Override
@ -26,7 +33,7 @@ public class AnnouncerComponent extends Component implements Runnable {
}
if (Bukkit.getOnlinePlayers().size() == 0) continue; //Don't post to Discord if nobody is on
if (AnnounceMessages().get().size() > AnnounceMessageIndex) {
Bukkit.broadcastMessage(AnnounceMessages().get().get(AnnounceMessageIndex));
TBMCChatAPI.SendSystemMessage(Channel.GlobalChat, Channel.RecipientTestResult.ALL, AnnounceMessages().get().get(AnnounceMessageIndex), target);
AnnounceMessageIndex++;
if (AnnounceMessageIndex == AnnounceMessages().get().size())
AnnounceMessageIndex = 0;
@ -36,11 +43,8 @@ public class AnnouncerComponent extends Component implements Runnable {
@Override
protected void enable() {
registerCommand(new AddCommand());
registerCommand(new EditCommand());
registerCommand(new ListCommand());
registerCommand(new RemoveCommand());
registerCommand(new SetTimeCommand());
target= TBMCSystemChatEvent.BroadcastTarget.add("announcements");
registerCommand(new AnnounceCommand(this));
new Thread(this).start();
}

View file

@ -1,44 +0,0 @@
package buttondevteam.chat.components.announce;
import org.bukkit.command.BlockCommandSender;
import org.bukkit.command.CommandSender;
public class EditCommand extends AnnounceCommandBase {
@Override
public String[] GetHelpText(String alias) {
return new String[] { "§6---- Edit announcement ----",
"This command can only be used in a command block.",
"Usage: /u annonunce edit <index> <text>" };
}
@Override
public boolean OnCommand(CommandSender sender, String alias,
String[] args) {
if (!(sender instanceof BlockCommandSender)) {
sender.sendMessage("§cError: This command can only be used from a command block. You can use add and remove, though it's not recommended.");
return true;
}
if (args.length < 1) {
return false;
}
StringBuilder sb1 = new StringBuilder();
for (int i1 = 1; i1 < args.length; i1++) {
sb1.append(args[i1]);
if (i1 != args.length - 1)
sb1.append(" ");
}
String finalmessage1 = sb1.toString().replace('&', '§');
int index = Integer.parseInt(args[0]);
if (index > 100)
return false;
AnnouncerComponent component = (AnnouncerComponent) getComponent();
while (component.AnnounceMessages().get().size() <= index)
component.AnnounceMessages().get().add("");
component.AnnounceMessages().get().set(Integer.parseInt(args[0]),
finalmessage1);
sender.sendMessage("Announcement edited.");
return true;
}
}

View file

@ -1,27 +0,0 @@
package buttondevteam.chat.components.announce;
import org.bukkit.command.CommandSender;
public class ListCommand extends AnnounceCommandBase {
@Override
public String[] GetHelpText(String alias) {
return new String[] { "§6---- List announcements ----",
"This command lists the announcements and the time between them" };
}
@Override
public boolean OnCommand(CommandSender sender, String alias,
String[] args) {
sender.sendMessage("§bList of announce messages:§r");
sender.sendMessage("§bFormat: [index] message§r");
int i = 0;
AnnouncerComponent component = (AnnouncerComponent) getComponent();
for (String message : component.AnnounceMessages().get())
sender.sendMessage("[" + i++ + "] " + message);
sender.sendMessage("§bCurrent wait time between announcements: "
+ component.AnnounceTime().get() / 60 / 1000 + " minute(s)§r");
return true;
}
}

View file

@ -1,28 +0,0 @@
package buttondevteam.chat.components.announce;
import org.bukkit.command.CommandSender;
public class RemoveCommand extends AnnounceCommandBase {
@Override
public String[] GetHelpText(String alias) {
return new String[] {
"§6---- Remove announcement ----",
"This command removes an announcement",
"Note: Please avoid using this command, if possible",
"Instead, use the command blocks in flatworld to set announcements",
"This makes editing announcements easier" };
}
@Override
public boolean OnCommand(CommandSender sender, String alias,
String[] args) {
if (args.length < 1) {
sender.sendMessage("§cUsage: /u announce remove <index>");
return true;
}
((AnnouncerComponent) getComponent()).AnnounceMessages().get().remove(Integer.parseInt(args[0]));
return true;
}
}

View file

@ -1,31 +0,0 @@
package buttondevteam.chat.components.announce;
import org.bukkit.command.CommandSender;
public class SetTimeCommand extends AnnounceCommandBase {
@Override
public String[] GetHelpText(String alias) {
return new String[] { "§6---- Set time ----",
"This command sets the time between the announcements",
"Usage: /u anonunce settime <minutes>", "Default: 15" };
}
@Override
public boolean OnCommand(CommandSender sender, String alias,
String[] args) {
if (args.length < 1) {
return false;
}
try {
((AnnouncerComponent) getComponent()).AnnounceTime().set(Integer.parseInt(args[0]) * 60 * 1000);
} catch (Exception e) {
sender.sendMessage("§cMinutes argument must be a number. Got: "
+ args[0]);
return true;
}
sender.sendMessage("Time set between announce messages");
return true;
}
}

View file

@ -0,0 +1,115 @@
package buttondevteam.chat.components.appendext;
import buttondevteam.chat.PluginMain;
import buttondevteam.lib.architecture.Component;
import buttondevteam.lib.architecture.ConfigData;
import buttondevteam.lib.architecture.IHaveConfig;
import buttondevteam.lib.chat.*;
import buttondevteam.lib.player.ChromaGamerBase;
import lombok.val;
import org.bukkit.command.CommandSender;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.function.Consumer;
public class AppendTextComponent extends Component<PluginMain> {
private Map<String, IHaveConfig> appendTexts;
private ConfigData<String[]> helpText(IHaveConfig config) {
return config.getData("helpText", () -> new String[]{
"Tableflip", //
"This command appends a tableflip after your message", //
"Or just makes you tableflip", //
});
}
private ConfigData<String> appendedText(IHaveConfig config) {
return config.getData("appendedText", () -> "tableflip");
}
@Override
protected void enable() {
val map = new HashMap<String, Consumer<IHaveConfig>>();
map.put("tableflip", conf -> {
helpText(conf).set(new String[]{
"Tableflip", //
"This command appends a tableflip after your message", //
"Or just makes you tableflip", //
});
appendedText(conf).set("(╯°□°)╯︵ ┻━┻");
});
map.put("unflip", conf -> {
helpText(conf).set(new String[]{
"Unflip", //
"This command appends an unflip after your message", //
"Or just unflips as you", //
});
appendedText(conf).set("┬─┬ ( ゜-゜ノ)");
});
map.put("shrug", conf -> {
helpText(conf).set(new String[]{
"Shrug", //
"This command appends a shrug after your message", //
"Or just makes you shrug", //
});
appendedText(conf).set("¯\\\\\\_(ツ)\\_/¯");
});
map.put("lenny", conf -> {
helpText(conf).set(new String[]{
"Lenny", //
"This command appends a Lenny face after your message", //
"Or just sends one", //
});
appendedText(conf).set("( ͡° ͜ʖ ͡°)");
});
map.put("ww", conf -> {
helpText(conf).set(new String[]{
"Wait what", //
"Wait what" //
});
appendedText(conf).set("wait what");
});
appendTexts = getConfigMap("texts", map);
for (String cmd : appendTexts.keySet())
registerCommand(new CommandHandler(cmd));
}
@Override
protected void disable() {
}
@CommandClass
public class CommandHandler extends ICommand2MC {
private final String path;
private final String[] helpText;
private final String appendedText;
CommandHandler(String command) {
val conf = appendTexts.get(command);
if (conf == null) throw new NoSuchElementException("AppendText command not found: " + command);
path = command;
helpText = helpText(conf).get();
appendedText = appendedText(conf).get();
}
@Command2.Subcommand
public void def(CommandSender sender, @Command2.OptionalArg @Command2.TextArg String message) {
TBMCChatAPI.SendChatMessage(ChatMessage.builder(sender, ChromaGamerBase.getFromSender(sender),
(message == null ? "" : message + " ") + appendedText).fromCommand(true).build());
}
@Override
public String getCommandPath() {
return path;
}
@Override
public String[] getHelpText(Method method, Command2.Subcommand ann) {
return helpText;
}
}
}

View file

@ -0,0 +1,63 @@
package buttondevteam.chat.components.chatonly;
import buttondevteam.chat.ChatPlayer;
import buttondevteam.chat.formatting.TellrawEvent;
import buttondevteam.chat.formatting.TellrawPart;
import buttondevteam.core.ComponentManager;
import buttondevteam.lib.architecture.Component;
import buttondevteam.lib.player.TBMCPlayer;
import buttondevteam.lib.player.TBMCPlayerJoinEvent;
import lombok.val;
import org.bukkit.GameMode;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.event.player.PlayerTeleportEvent;
public class ChatOnlyComponent extends Component implements Listener {
@Override
protected void enable() {
registerListener(this);
registerCommand(new ChatonlyCommand());
}
@Override
protected void disable() {
}
@EventHandler
public void playerJoin(TBMCPlayerJoinEvent event) {
val p = event.getPlayer();
val cp = event.GetPlayer().asPluginPlayer(ChatPlayer.class);
if (cp.ChatOnly || p.getGameMode().equals(GameMode.SPECTATOR)) {
cp.ChatOnly = false;
p.setGameMode(GameMode.SURVIVAL);
}
}
public static void tellrawCreate(ChatPlayer mp, TellrawPart json) {
if(!ComponentManager.isEnabled(ChatOnlyComponent.class))
return;
if (mp != null && mp.ChatOnly) {
json.addExtra(new TellrawPart("[C]")
.setHoverEvent(TellrawEvent.create(TellrawEvent.HoverAction.SHOW_TEXT, "Chat only")));
}
}
@EventHandler
public void onPlayerMove(PlayerMoveEvent e) {
ChatPlayer mp = TBMCPlayer.getPlayer(e.getPlayer().getUniqueId(), ChatPlayer.class);
if (mp.ChatOnly)
e.setCancelled(true);
}
@EventHandler(priority = EventPriority.LOWEST)
public void onPlayerTeleport(PlayerTeleportEvent e) {
if (TBMCPlayer.getPlayer(e.getPlayer().getUniqueId(), ChatPlayer.class).ChatOnly) {
e.setCancelled(true);
e.getPlayer().sendMessage("§cYou are not allowed to teleport while in chat-only mode.");
}
}
}

View file

@ -0,0 +1,28 @@
package buttondevteam.chat.components.chatonly;
import buttondevteam.lib.chat.ICommand2MC;
import org.bukkit.GameMode;
import org.bukkit.entity.Player;
import buttondevteam.chat.ChatPlayer;
import buttondevteam.lib.chat.CommandClass;
import buttondevteam.lib.chat.PlayerCommandBase;
import buttondevteam.lib.player.TBMCPlayer;
@CommandClass(modOnly = false, helpText = {
"§6---- Chat-only mode ----", //
"This mode makes you invincible but unable to move, teleport or interact with the world in any way", //
"It was designed for chat clients", //
"Once enabled, the only way of disabling it is by relogging to the server" //
})
public final class ChatonlyCommand extends ICommand2MC {
public boolean def(Player player) {
ChatPlayer p = TBMCPlayer.getPlayer(player.getUniqueId(), ChatPlayer.class);
p.ChatOnly = true;
player.setGameMode(GameMode.SPECTATOR);
player.sendMessage("§bChat-only mode enabled. You are now invincible.");
return true;
}
}

View file

@ -4,45 +4,46 @@ import buttondevteam.chat.ChatPlayer;
import buttondevteam.chat.PlayerJoinTimerTask;
import buttondevteam.chat.commands.ucmds.UCommandBase;
import buttondevteam.lib.TBMCCoreAPI;
import buttondevteam.lib.chat.Command2;
import buttondevteam.lib.chat.CommandClass;
import buttondevteam.lib.chat.OptionallyPlayerCommandClass;
import buttondevteam.lib.player.TBMCPlayer;
import lombok.RequiredArgsConstructor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.Timer;
@CommandClass(modOnly = false)
@CommandClass(modOnly = false, helpText = {
"Accept flair", //
"Accepts a flair from Reddit", //
"Use /u accept <username> if you commented from multiple accounts"
})
@OptionallyPlayerCommandClass(playerOnly = true)
@RequiredArgsConstructor
public class AcceptCommand extends UCommandBase {
private final FlairComponent component;
@Override
public String[] GetHelpText(String alias) {
return new String[] { "§6---- Accept flair ----", //
"Accepts a flair from Reddit", //
"Use /u accept <username> if you commented from multiple accounts" //
};
}
@Override
public boolean OnCommand(CommandSender sender, String alias, String[] args) {
@Command2.Subcommand
public boolean def(CommandSender sender, @Command2.OptionalArg String username) {
final Player player = (Player) sender;
ChatPlayer p = TBMCPlayer.getPlayer(player.getUniqueId(), ChatPlayer.class);
if (args.length < 1 && p.UserNames().size() > 1) {
if (username == null && p.UserNames().size() > 1) {
player.sendMessage("§9Multiple users commented your name. §bPlease pick one using /u accept <username>");
StringBuilder sb = new StringBuilder();
sb.append("§6Usernames:");
for (String username : p.UserNames())
sb.append(" ").append(username);
for (String name : p.UserNames())
sb.append(" ").append(name);
player.sendMessage(sb.toString());
return true;
}
if (p.FlairState().get().equals(FlairStates.NoComment) || p.UserNames().size() == 0) {
player.sendMessage("§cError: You need to write your username to the reddit thread at /r/ChromaGamers§r");
player.sendMessage("§cError: You need to write your username to the reddit thread§r");
player.sendMessage(component.FlairThreadURL().get());
return true;
}
if (args.length > 0 && !p.UserNames().contains(args[0])) {
player.sendMessage("§cError: Unknown name: " + args[0] + "§r");
if (username != null && !p.UserNames().contains(username)) {
player.sendMessage("§cError: Unknown name: " + username + "§r");
return true;
}
if (p.Working) {
@ -50,12 +51,12 @@ public class AcceptCommand extends UCommandBase {
return true;
}
if ((args.length > 0 ? args[0] : p.UserNames().get(0)).equals(p.UserName().get())) {
if ((username != null ? username : p.UserNames().get(0)).equals(p.UserName().get())) {
player.sendMessage("§cYou already have this user's flair.§r");
return true;
}
if (args.length > 0)
p.UserName().set(args[0]);
if (username != null)
p.UserName().set(username);
else
p.UserName().set(p.UserNames().get(0));
@ -66,7 +67,7 @@ public class AcceptCommand extends UCommandBase {
@Override
public void run() {
try {
FlairComponent.DownloadFlair(mp);
component.DownloadFlair(mp);
} catch (Exception e) {
TBMCCoreAPI.SendException(
"An error occured while downloading flair for " + player.getCustomName() + "!", e);
@ -93,5 +94,4 @@ public class AcceptCommand extends UCommandBase {
timer.schedule(tt, 20);
return true;
}
}

View file

@ -1,6 +1,7 @@
package buttondevteam.chat.components.flair;
import buttondevteam.chat.ChatPlayer;
import buttondevteam.chat.PluginMain;
import buttondevteam.lib.TBMCCoreAPI;
import buttondevteam.lib.architecture.Component;
import buttondevteam.lib.architecture.ConfigData;
@ -21,8 +22,8 @@ import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.*;
public class FlairComponent extends Component {
private ConfigData<String> FlairThreadURL() {
public class FlairComponent extends Component<PluginMain> {
ConfigData<String> FlairThreadURL() {
return getConfig().getData("flairThreadURL", "https://www.reddit.com/r/Chromagamers/comments/51ys94/flair_thread_for_the_mc_server/");
}
@ -38,7 +39,7 @@ public class FlairComponent extends Component {
@Override
protected void enable() {
registerCommand(new AcceptCommand());
registerCommand(new AcceptCommand(this));
registerCommand(new IgnoreCommand());
registerCommand(new SetFlairCommand());
new Thread(this::FlairGetterThreadMethod).start();
@ -105,7 +106,7 @@ public class FlairComponent extends Component {
}
}
public static void DownloadFlair(ChatPlayer mp) throws IOException {
void DownloadFlair(ChatPlayer mp) throws IOException {
String[] flairdata = TBMCCoreAPI
.DownloadString("http://karmadecay.com/thebutton-data.php?users=" + mp.UserName().get())
.replace("\"", "").split(":");

View file

@ -2,24 +2,21 @@ package buttondevteam.chat.components.flair;
import buttondevteam.chat.ChatPlayer;
import buttondevteam.chat.commands.ucmds.UCommandBase;
import buttondevteam.lib.chat.Command2;
import buttondevteam.lib.chat.CommandClass;
import buttondevteam.lib.chat.OptionallyPlayerCommandClass;
import buttondevteam.lib.player.TBMCPlayer;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
@CommandClass(modOnly = false)
@CommandClass(modOnly = false, helpText = {
"Ignore flair",
"Stop the \"write your name in the thread\" message from showing up"
})
@OptionallyPlayerCommandClass(playerOnly = true)
public final class IgnoreCommand extends UCommandBase {
@Override
public String[] GetHelpText(String alias) {
return new String[] { "§6---- Ignore flair ----",
"Stop the \"write your name in the thread\" message from showing up" };
}
@Override
public boolean OnCommand(CommandSender sender, String alias, String[] args) {
@Command2.Subcommand
public boolean def(CommandSender sender) {
final Player player = (Player) sender;
ChatPlayer p = TBMCPlayer.getPlayer(player.getUniqueId(), ChatPlayer.class);
if (p.FlairState().get().equals(FlairStates.Accepted)) {
@ -39,5 +36,4 @@ public final class IgnoreCommand extends UCommandBase {
player.sendMessage("§cYou already ignored the message.§r");
return true;
}
}

View file

@ -2,65 +2,52 @@ package buttondevteam.chat.components.flair;
import buttondevteam.chat.ChatPlayer;
import buttondevteam.chat.commands.ucmds.admin.AdminCommandBase;
import buttondevteam.lib.chat.Command2;
import buttondevteam.lib.chat.CommandClass;
import buttondevteam.lib.player.TBMCPlayerBase;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
@CommandClass(helpText = {
"§6---- Set flair -----", "Set a flair for a player",
"Usage: /u admin setflair <player> <flairtime (or non-presser, cant-press, none)> <cheater(true/false)> [username]",
"Example 1: /u admin setflair NorbiPeti 19 false NorbiPeti --> orange (19s)",
"Example 2: /u admin setflair iie 0 true asde --> purple (0s)"
})
public class SetFlairCommand extends AdminCommandBase {
@Override
public String[] GetHelpText(String alias) {
return new String[] { "§6---- Set flair -----", "Set a flair for a player",
"Usage: /u admin setflair <player> <flairtime (or non-presser, cant-press, none)> <cheater(true/false)> [username]",
"Example 1: /u admin setflair NorbiPeti 19 false NorbiPeti --> orange (19s)",
"Example 2: /u admin setflair iie 0 true asde --> purple (0s)" };
}
@Override
public boolean OnCommand(CommandSender sender, String alias, String[] args) {
if (args.length < 3) {
return false;
}
Player p = Bukkit.getPlayer(args[0]);
@Command2.Subcommand
public boolean def(CommandSender sender, String player, String flairtime, boolean cheater, @Command2.OptionalArg String username) {
Player p = Bukkit.getPlayer(player);
if (p == null) {
sender.sendMessage("§cPlayer not found.&r");
return true;
}
short flairtime = 0x00;
if (args[1].equalsIgnoreCase("non-presser"))
flairtime = ChatPlayer.FlairTimeNonPresser;
else if (args[1].equalsIgnoreCase("cant-press"))
flairtime = ChatPlayer.FlairTimeCantPress;
else if (args[1].equalsIgnoreCase("none"))
flairtime = ChatPlayer.FlairTimeNone;
short ft = 0x00;
if (flairtime.equalsIgnoreCase("non-presser"))
ft = ChatPlayer.FlairTimeNonPresser;
else if (flairtime.equalsIgnoreCase("cant-press"))
ft = ChatPlayer.FlairTimeCantPress;
else if (flairtime.equalsIgnoreCase("none"))
ft = ChatPlayer.FlairTimeNone;
else {
try {
flairtime = Short.parseShort(args[1]);
ft = Short.parseShort(flairtime);
} catch (Exception e) {
sender.sendMessage(
"§cFlairtime must be a number, \"non-presser\", \"cant-press\" or \"none\". Run without args to see usage.");
return true;
}
}
boolean cheater;
if (args[2].equalsIgnoreCase("true"))
cheater = true;
else if (args[2].equalsIgnoreCase("false"))
cheater = false;
else {
sender.sendMessage("§cUnknown value for cheater parameter.");
return false;
}
ChatPlayer mp = TBMCPlayerBase.getPlayer(p.getUniqueId(), ChatPlayer.class);
mp.SetFlair(flairtime, cheater);
mp.SetFlair(ft, cheater);
mp.FlairState().set(FlairStates.Accepted);
if (args.length < 4)
if (username == null)
mp.UserName().set("");
else {
mp.UserName().set(args[3]);
if (!mp.UserNames().contains(args[3]))
mp.UserNames().add(args[3]);
mp.UserName().set(username);
if (!mp.UserNames().contains(username))
mp.UserNames().add(username);
}
sender.sendMessage(
"§bThe flair has been set. Player: " + mp.PlayerName() + " Flair: " + mp.GetFormattedFlair() + "§r");

View file

@ -1,59 +1,51 @@
package buttondevteam.chat.commands.ucmds;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import buttondevteam.chat.ChatPlayer;
import buttondevteam.chat.PluginMain;
import buttondevteam.lib.chat.*;
import buttondevteam.lib.player.TBMCPlayer;
@CommandClass(modOnly = false)
@OptionallyPlayerCommandClass(playerOnly = true)
public class CCommand extends UCommandBase {
@Override
public String[] GetHelpText(String alias) {
return new String[] { "§6---- Rainbow mode ----", "This command allows you to talk in rainbow colors",
"You need to be a donator or a mod to use this command" };
}
@Override
public boolean OnCommand(CommandSender sender, String alias, String[] args) {
Player player = (Player) sender;
ChatPlayer p = TBMCPlayer.getPlayer(player.getUniqueId(), ChatPlayer.class);
if (args.length < 1) {
if (PluginMain.permission.has(player, "tbmc.rainbow")) {
p.RainbowPresserColorMode = !p.RainbowPresserColorMode;
p.OtherColorMode = null;
if (p.RainbowPresserColorMode)
player.sendMessage("§eRainbow colors §aenabled.");
else
player.sendMessage("§eRainbow colors §cdisabled.");
} else {
player.sendMessage("§cYou don't have permission for this command. Donate to get it!");
return true;
}
} else {
if (PluginMain.permission.has(player, "tbmc.admin")) {
p.RainbowPresserColorMode = false;
p.OtherColorMode = null;
try {
p.OtherColorMode = Color.valueOf(args[0].toLowerCase());
} catch (Exception e) {
player.sendMessage("§cUnknown message color: " + args[0]);
player.sendMessage("§cUse color names, like blue, or dark_aqua");
}
if (p.OtherColorMode != null)
player.sendMessage(String.format("§eMessage color set to %s", p.OtherColorMode));
else
player.sendMessage("§eMessage color reset.");
} else {
player.sendMessage("§cYou don't have permission for this command.");
return true;
}
}
return true;
}
}
package buttondevteam.chat.components.fun;
import buttondevteam.chat.ChatPlayer;
import buttondevteam.chat.PluginMain;
import buttondevteam.lib.chat.*;
import buttondevteam.lib.player.TBMCPlayer;
import org.bukkit.entity.Player;
@CommandClass(path = "u c", helpText = {
"Rainbow mode",
"This command allows you to talk in rainbow colors"
})
@OptionallyPlayerCommandClass(playerOnly = true)
public class CCommand extends ICommand2MC {
@Command2.Subcommand
public boolean def(Player player, @Command2.OptionalArg String color) {
ChatPlayer p = TBMCPlayer.getPlayer(player.getUniqueId(), ChatPlayer.class);
if (color == null) {
if (PluginMain.permission.has(player, "thorpe.color.rainbow")) {
p.RainbowPresserColorMode = !p.RainbowPresserColorMode;
p.OtherColorMode = null;
if (p.RainbowPresserColorMode)
player.sendMessage("§eRainbow colors §aenabled.");
else
player.sendMessage("§eRainbow colors §cdisabled.");
} else {
player.sendMessage("§cYou don't have permission for this command.");
return true;
}
} else {
if (PluginMain.permission.has(player, "thorpe.color.custom")) {
p.RainbowPresserColorMode = false;
p.OtherColorMode = null;
try {
p.OtherColorMode = Color.valueOf(color.toLowerCase());
} catch (Exception e) {
player.sendMessage("§cUnknown message color: " + color);
player.sendMessage("§cUse color names, like blue, or dark_aqua");
}
if (p.OtherColorMode != null)
player.sendMessage(String.format("§eMessage color set to %s", p.OtherColorMode));
else
player.sendMessage("§eMessage color reset.");
} else {
player.sendMessage("§cYou don't have permission for this command.");
return true;
}
}
return true;
}
}

View file

@ -1,8 +1,10 @@
package buttondevteam.chat.commands;
package buttondevteam.chat.components.fun;
import buttondevteam.chat.ChatPlayer;
import buttondevteam.chat.PluginMain;
import buttondevteam.lib.chat.Command2;
import buttondevteam.lib.chat.CommandClass;
import buttondevteam.lib.chat.ICommand2MC;
import buttondevteam.lib.chat.TBMCCommandBase;
import buttondevteam.lib.player.TBMCPlayerBase;
import lombok.val;
@ -16,23 +18,17 @@ import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
@CommandClass
public class FTopCommand extends TBMCCommandBase {
@Override
public String[] GetHelpText(String arg0) {
return new String[]{ //
"§6---- F Top ----", //
"Shows the respect leaderboard" //
};
}
@CommandClass(helpText = {
"§6---- F Top ----", //
"Shows the respect leaderboard" //
})
public class FTopCommand extends ICommand2MC {
private final File playerdir = new File(TBMCPlayerBase.TBMC_PLAYERS_DIR);
private ChatPlayer[] cached;
private long lastcache = 0;
@Override
public boolean OnCommand(CommandSender arg0, String arg1, String[] arg2) {
public boolean def(CommandSender sender, @Command2.OptionalArg int page) {
Bukkit.getScheduler().runTaskAsynchronously(PluginMain.Instance, () -> {
if (cached == null || lastcache < System.nanoTime() - 60000000000L) { // 1m - (no guarantees of nanoTime's relation to 0, so we need the null check too)
cached = Arrays.stream(Objects.requireNonNull(playerdir.listFiles())).sequential()
@ -52,15 +48,13 @@ public class FTopCommand extends TBMCCommandBase {
}
int i;
try {
i = arg2.length > 0 ? Integer.parseInt(arg2[0]) : 1;
if (i < 1)
i = 1; //i=1
} catch (Exception e) {
i = 1;
}
i = page<1?1:page;
} catch (Exception e) {
i = 1;
}
val ai = new AtomicInteger();
arg0.sendMessage("§6---- Top Fs ----");
arg0.sendMessage(Arrays.stream(cached).skip((i - 1) * 10).limit(i * 10)
sender.sendMessage("§6---- Top Fs ----");
sender.sendMessage(Arrays.stream(cached).skip((i - 1) * 10).limit(i * 10)
.map(cp -> String.format("%d. %s - %f.2", ai.incrementAndGet(), cp.PlayerName().get(), cp.getF()))
.collect(Collectors.joining("\n")));
});

View file

@ -1,18 +1,163 @@
package buttondevteam.chat.components.fun;
import buttondevteam.chat.ChatPlayer;
import buttondevteam.chat.PluginMain;
import buttondevteam.core.component.channel.Channel;
import buttondevteam.lib.TBMCChatEventBase;
import buttondevteam.lib.TBMCCommandPreprocessEvent;
import buttondevteam.lib.TBMCSystemChatEvent;
import buttondevteam.lib.ThorpeUtils;
import buttondevteam.lib.architecture.Component;
import buttondevteam.lib.architecture.ConfigData;
import buttondevteam.lib.chat.TBMCChatAPI;
import buttondevteam.lib.player.ChromaGamerBase;
import buttondevteam.lib.player.TBMCPlayer;
import lombok.val;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.help.HelpTopic;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import org.bukkit.scheduler.BukkitTask;
import java.util.ArrayList;
import java.util.Random;
public class FunComponent extends Component<PluginMain> implements Listener {
private boolean ActiveF = false;
private ChatPlayer FPlayer = null;
private BukkitTask Ftask = null;
private ArrayList<CommandSender> Fs = new ArrayList<>();
private UnlolCommand command;
private TBMCSystemChatEvent.BroadcastTarget unlolTarget;
private TBMCSystemChatEvent.BroadcastTarget fTarget;
private ConfigData<String[]> laughStrings() {
return getConfig().getData("laughStrings", () -> new String[]{"xd", "lel", "lawl", "kek", "lmao", "hue", "hah", "rofl"});
}
private ConfigData<Boolean> respect() {
return getConfig().getData("respect", true);
}
private ConfigData<Boolean> unlol() {
return getConfig().getData("unlol", true);
}
public class FunComponent extends Component {
@Override
protected void enable() {
unlolTarget = TBMCSystemChatEvent.BroadcastTarget.add("unlol");
fTarget = TBMCSystemChatEvent.BroadcastTarget.add("respect");
val pc = new PressCommand();
registerCommand(pc);
registerListener(pc);
registerCommand(command=new UnlolCommand(unlolTarget));
registerListener(this);
registerCommand(new FTopCommand());
registerCommand(new OpmeCommand());
registerCommand(new YeehawCommand());
registerCommand(new CCommand());
}
@Override
protected void disable() {
}
public void onChat(CommandSender sender, TBMCChatEventBase event, String message) {
if (ActiveF && !Fs.contains(sender) && message.equalsIgnoreCase("F"))
Fs.add(sender);
if (unlol().get()) {
String msg = message.toLowerCase();
val lld = new UnlolCommand.LastlolData(sender, event, System.nanoTime());
boolean add;
if (add = msg.contains("lol"))
lld.setLolornot(true);
else {
String[] laughs = laughStrings().get();
for (String laugh : laughs) {
if (add = msg.contains(laugh)) {
lld.setLolornot(false);
break;
}
}
}
if (add)
command.Lastlol.put(event.getChannel(), lld);
}
}
@EventHandler
public void onPlayerDeath(PlayerDeathEvent e) {
// MinigamePlayer mgp = Minigames.plugin.pdata.getMinigamePlayer(e.getEntity());
if (e.getDeathMessage().length() > 0 && respect().get() && new Random().nextBoolean()) { // Don't store Fs for NPCs
Runnable tt = () -> {
if (ActiveF) {
ActiveF = false;
if (FPlayer != null && FPlayer.FCount().get() < Integer.MAX_VALUE - 1)
FPlayer.FCount().set(FPlayer.FCount().get() + Fs.size());
TBMCChatAPI.SendSystemMessage(Channel.GlobalChat, Channel.RecipientTestResult.ALL,
"§b" + Fs.size() + " " + (Fs.size() == 1 ? "person" : "people")
+ " paid their respects.§r", fTarget);
Fs.clear();
}
};
if (Ftask != null) {
Ftask.cancel();
tt.run(); //Finish previous one
}
ActiveF = true;
Fs.clear();
FPlayer = TBMCPlayer.getPlayer(e.getEntity().getUniqueId(), ChatPlayer.class);
FPlayer.FDeaths().set(FPlayer.FDeaths().get() + 1);
TBMCChatAPI.SendSystemMessage(Channel.GlobalChat, Channel.RecipientTestResult.ALL,
"§bPress F to pay respects.§r", fTarget);
Bukkit.getScheduler().runTaskLaterAsynchronously(PluginMain.Instance, tt, 15 * 20);
}
}
@EventHandler
public void onPlayerLeave(PlayerQuitEvent event) {
if (unlol().get())
command.Lastlol.values().removeIf(lld -> lld.getLolowner().equals(event.getPlayer()));
}
@EventHandler(priority = EventPriority.LOWEST)
public void onCommandPreprocess(TBMCCommandPreprocessEvent event) {
if (event.isCancelled()) return;
if (!unlol().get()) return;
final String cmd = event.getMessage();
// We don't care if we have arguments
if (cmd.toLowerCase().startsWith("/un")) {
for (HelpTopic ht : PluginMain.Instance.getServer().getHelpMap().getHelpTopics()) {
if (ht.getName().equalsIgnoreCase(cmd))
return;
}
if (PluginMain.permission.has(event.getSender(), "thorpe.unanything")) {
event.setCancelled(true);
String s = cmd.substring(3);
int index = event.getMessage().indexOf(' ');
if (index == -1) {
event.getSender().sendMessage("§cUsage: /un" + s + " <player>");
return;
}
Player target = Bukkit.getPlayer(event.getMessage().substring(index + 1));
if (target == null) {
event.getSender().sendMessage("§cError: Player not found. (/un" + s + " <player>)");
return;
}
val user = ChromaGamerBase.getFromSender(event.getSender());
target.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, 10 * 20, 5, false, false));
val chan = user.channel().get();
TBMCChatAPI.SendSystemMessage(chan, chan.getRTR(event.getSender()), ThorpeUtils.getDisplayName(event.getSender()) + " un" + s
+ "'d " + target.getDisplayName(), unlolTarget);
}
}
}
}

View file

@ -0,0 +1,18 @@
package buttondevteam.chat.components.fun;
import buttondevteam.lib.chat.Command2;
import buttondevteam.lib.chat.CommandClass;
import buttondevteam.lib.chat.ICommand2MC;
import org.bukkit.command.CommandSender;
@CommandClass(modOnly = false, path = "u opme", helpText = {
"OP me",
"Totally makes you OP"
})
public class OpmeCommand extends ICommand2MC {
@Command2.Subcommand
public boolean def(CommandSender sender) {
sender.sendMessage("It would be nice, wouldn't it?");
return true;
}
}

View file

@ -1,10 +1,14 @@
package buttondevteam.chat.components.fun;
import buttondevteam.core.component.channel.Channel;
import buttondevteam.core.component.restart.RestartComponent;
import buttondevteam.core.component.restart.ScheduledRestartCommand;
import buttondevteam.lib.ScheduledServerRestartEvent;
import buttondevteam.lib.ThorpeUtils;
import buttondevteam.lib.chat.Command2MC;
import buttondevteam.lib.chat.Command2;
import buttondevteam.lib.chat.CommandClass;
import buttondevteam.lib.chat.ICommand2MC;
import buttondevteam.lib.chat.TBMCChatAPI;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.event.EventHandler;
@ -13,12 +17,12 @@ import org.bukkit.event.Listener;
import java.util.HashSet;
@CommandClass
public class PressCommand extends Command2MC implements Listener {
public class PressCommand extends ICommand2MC implements Listener {
private HashSet<CommandSender> pressers; //Will be cleared with this class on shutdown/disable
private ScheduledRestartCommand command;
private int startTicks;
@Subcommand
@Command2.Subcommand
public void def(CommandSender sender) {
if (command == null) {
sender.sendMessage("§cThe timer isn't ticking... yet.");
@ -29,7 +33,7 @@ public class PressCommand extends Command2MC implements Listener {
return;
}
pressers.add(sender);
Bukkit.broadcastMessage(String.format("§b-- %s §bpressed at %.0fs", ThorpeUtils.getDisplayName(sender), command.getRestartCounter() / 20f));
TBMCChatAPI.SendSystemMessage(Channel.GlobalChat, Channel.RecipientTestResult.ALL, String.format("§b-- %s §bpressed at %.0fs", ThorpeUtils.getDisplayName(sender), command.getRestartCounter() / 20f), command.getComponent().getRestartBroadcast());
command.setRestartCounter(startTicks);
}

View file

@ -1,10 +1,12 @@
package buttondevteam.chat.commands;
package buttondevteam.chat.components.fun;
import buttondevteam.core.component.channel.Channel;
import buttondevteam.lib.TBMCChatEventBase;
import buttondevteam.lib.chat.CommandClass;
import buttondevteam.lib.chat.TBMCCommandBase;
import buttondevteam.lib.TBMCSystemChatEvent;
import buttondevteam.lib.ThorpeUtils;
import buttondevteam.lib.chat.*;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
@ -15,21 +17,21 @@ import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
@CommandClass(modOnly = false)
public final class UnlolCommand extends TBMCCommandBase {
@CommandClass(modOnly = false, helpText = {
"§6---- Unlol/unlaugh ----",
"This command is based on a joke between NorbiPeti and Ghostise",
"It will make the last person saying one of the recognized laugh strings blind for a few seconds",
"Note that you can only unlaugh laughs that weren't unlaughed before"
})
@RequiredArgsConstructor
public final class UnlolCommand extends ICommand2MC {
public static Map<Channel, LastlolData> Lastlol = new HashMap<>();
public Map<Channel, LastlolData> Lastlol = new HashMap<>();
@Override
public String[] GetHelpText(String alias) {
return new String[] { "§6---- Unlol/unlaugh ----",
"This command is based on a joke between NorbiPeti and Ghostise",
"It will make the last person saying one of the recognized laugh strings blind for a few seconds",
"Note that you can only unlaugh laughs that weren't unlaughed before" };
}
private final TBMCSystemChatEvent.BroadcastTarget target;
@Override
public boolean OnCommand(CommandSender sender, String alias, String[] args) {
@Command2.Subcommand
public boolean def(CommandSender sender) {
LastlolData lol = Lastlol.values().stream().filter(lld -> lld.Chatevent.shouldSendTo(sender))
.max(Comparator.comparingLong(lld -> lld.Loltime)).orElse(null);
if (lol == null)
@ -37,10 +39,10 @@ public final class UnlolCommand extends TBMCCommandBase {
if (lol.Lolowner instanceof Player)
((Player) lol.Lolowner)
.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, 2 * 20, 5, false, false));
String msg = (sender instanceof Player ? ((Player) sender).getDisplayName() : sender.getName())
String msg = ThorpeUtils.getDisplayName(sender)
+ (lol.Lolornot ? " unlolled " : " unlaughed ")
+ (lol.Lolowner instanceof Player ? ((Player) lol.Lolowner).getDisplayName() : lol.Lolowner.getName());
Bukkit.broadcastMessage(msg);
+ ThorpeUtils.getDisplayName(lol.Lolowner);
TBMCChatAPI.SendSystemMessage(Channel.GlobalChat, Channel.RecipientTestResult.ALL, msg, target);
Lastlol.remove(lol.Chatevent.getChannel());
return true;
}

View file

@ -1,30 +1,28 @@
package buttondevteam.chat.commands;
import buttondevteam.lib.chat.CommandClass;
import buttondevteam.lib.chat.TBMCCommandBase;
import buttondevteam.lib.player.TBMCYEEHAWEvent;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
@CommandClass(modOnly = false)
public class YeehawCommand extends TBMCCommandBase {
@Override
public String[] GetHelpText(String alias) {
return new String[] { "§6---- YEEHAW command ----", "This command makes you YEEHAW." };
}
@Override
public boolean OnCommand(CommandSender sender, String alias, String[] args) {
final String message = "§b* "
+ (sender instanceof Player ? ((Player) sender).getDisplayName() : sender.getName()) + " §bYEEHAWs.";
for (Player p : Bukkit.getOnlinePlayers()) {
p.playSound(p.getLocation(), "tbmc.yeehaw", 1f, 1f);
p.sendMessage(message); //Not broadcasting, so the Discord plugin can handle the event in a special way
} // Even a cmdblock could yeehaw in theory
// Or anyone from Discord
Bukkit.getPluginManager().callEvent(new TBMCYEEHAWEvent(sender));
return true;
}
}
package buttondevteam.chat.components.fun;
import buttondevteam.lib.chat.Command2;
import buttondevteam.lib.chat.CommandClass;
import buttondevteam.lib.chat.ICommand2MC;
import buttondevteam.lib.player.TBMCYEEHAWEvent;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
@CommandClass(modOnly = false, helpText = {
"YEEHAW command",
"This command makes you YEEHAW."
})
public class YeehawCommand extends ICommand2MC {
@Command2.Subcommand
public boolean def(CommandSender sender) {
final String message = "§b* "
+ (sender instanceof Player ? ((Player) sender).getDisplayName() : sender.getName()) + " §bYEEHAWs.";
for (Player p : Bukkit.getOnlinePlayers()) {
p.playSound(p.getLocation(), "tbmc.yeehaw", 1f, 1f);
p.sendMessage(message); //Not broadcasting, so the Discord plugin can handle the event in a special way
} // Even a cmdblock could yeehaw in theory
// Or anyone from Discord
Bukkit.getPluginManager().callEvent(new TBMCYEEHAWEvent(sender));
return true;
}
}

View file

@ -4,6 +4,7 @@ import buttondevteam.chat.ChatPlayer;
import buttondevteam.chat.commands.ucmds.UCommandBase;
import buttondevteam.chat.components.towny.TownyComponent;
import buttondevteam.lib.chat.Color;
import buttondevteam.lib.chat.Command2;
import buttondevteam.lib.chat.CommandClass;
import buttondevteam.lib.chat.OptionallyPlayerCommandClass;
import com.palmergames.bukkit.towny.object.Resident;
@ -16,21 +17,16 @@ import java.util.Arrays;
import java.util.stream.Collectors;
@OptionallyPlayerCommandClass(playerOnly = true)
@CommandClass
@CommandClass(helpText = {
"Name color", //
"This command allows you to set how the town colors look on your name.", //
"To use this command, you need to be in a town which has town colors set.", //
"Use a vertical line (or a colon) as a separator between the colors.", //
"Example: /u ncolor Norbi|Peti --> §6Norbi§ePeti" //
})
public class NColorCommand extends UCommandBase {
@Override
public String[] GetHelpText(String alias) {
return new String[] { //
"§6---- Name color ----", //
"This command allows you to set how the town colors look on your name.", //
"To use this command, you need to be in a town which has town colors set.", //
"Use a vertical line as a separator between the colors.", //
"Example: /u ncolor Norbi|Peti --> §6Norbi§ePeti" //
};
}
@Override
public boolean OnCommand(Player player, String alias, String[] args) {
@Command2.Subcommand
public boolean def(Player player, String nameWithLines) {
Resident res;
Town town;
try {
@ -43,16 +39,14 @@ public class NColorCommand extends UCommandBase {
player.sendMessage("§cYou need to be in a town. (" + e + ")");
return true;
}
if (args.length == 0)
return false;
final String name = ChatColor.stripColor(player.getDisplayName()).replace("~", ""); //Remove ~
String arg = args[0]; //Don't add ~ for nicknames
if (!arg.replace("|", "").replace(":", "").equalsIgnoreCase(name)) {
//Don't add ~ for nicknames
if (!nameWithLines.replace("|", "").replace(":", "").equalsIgnoreCase(name)) {
player.sendMessage("§cThe name you gave doesn't match your name. Make sure to use "
+ name + "§c with added vertical lines (|) or colons (:).");
return true;
}
String[] nameparts = arg.split("[|:]");
String[] nameparts = nameWithLines.split("[|:]");
Color[] towncolors = TownColorComponent.TownColors.get(town.getName().toLowerCase());
if (towncolors == null) {
player.sendMessage("§cYour town doesn't have a color set. The town mayor can set it using /u towncolor.");

View file

@ -3,48 +3,38 @@ package buttondevteam.chat.components.towncolors;
import buttondevteam.chat.commands.ucmds.UCommandBase;
import buttondevteam.chat.components.towny.TownyComponent;
import buttondevteam.lib.TBMCCoreAPI;
import buttondevteam.lib.chat.Command2;
import buttondevteam.lib.chat.CommandClass;
import buttondevteam.lib.chat.OptionallyPlayerCommandClass;
import com.palmergames.bukkit.towny.exceptions.NotRegisteredException;
import com.palmergames.bukkit.towny.object.Nation;
import com.palmergames.bukkit.towny.object.Resident;
import org.bukkit.entity.Player;
@CommandClass
@CommandClass(helpText = {
"Nation Color", //
"This command allows setting a color for a nation.", //
"Each town in the nation will have it's first color (border) set to this color.", //
"See the help text for /u towncolor for more details.", //
})
@OptionallyPlayerCommandClass(playerOnly = true)
public class NationColorCommand extends UCommandBase {
@Override
public String[] GetHelpText(String alias) {
return new String[]{ //
"§6---- Nation Color ----", //
"This command allows setting a color for a nation.", //
"Each town in the nation will have it's first color (border) set to this color.", //
"See the help text for /u towncolor for more details.", //
"Usage: /" + GetCommandPath() + " <colorname>", //
"Example: /" + GetCommandPath() + " blue" //
};
}
@Override
public boolean OnCommand(Player player, String alias, String[] args) {
@Command2.Subcommand
public boolean def(Player player, String color) {
Resident res;
if (!(TownyComponent.TU.getResidentMap().containsKey(player.getName().toLowerCase())
&& (res = TownyComponent.TU.getResidentMap().get(player.getName().toLowerCase())).isKing())) {
player.sendMessage("§cYou need to be the king of a nation to set it's colors.");
return true;
}
if (args.length > 1) {
player.sendMessage("You can only use one color.");
return true;
}
String[] a = new String[args.length + 1];
System.arraycopy(args, 0, a, 1, args.length);
final Nation n;
try {
a[0] = res.getTown().getNation().getName();
n = res.getTown().getNation();
} catch (NotRegisteredException e) {
TBMCCoreAPI.SendException("Failed to set nation color for player " + player + "!", e);
player.sendMessage("§cCouldn't find your town/nation... Error reported.");
return true;
}
return buttondevteam.chat.components.towncolors.admin.NationColorCommand.SetNationColor(player, alias, a);
return buttondevteam.chat.components.towncolors.admin.NationColorCommand.SetNationColor(player, n, color);
}
}

View file

@ -3,54 +3,62 @@ package buttondevteam.chat.components.towncolors;
import buttondevteam.chat.commands.ucmds.UCommandBase;
import buttondevteam.chat.components.towny.TownyComponent;
import buttondevteam.lib.TBMCCoreAPI;
import buttondevteam.lib.chat.Command2;
import buttondevteam.lib.chat.CommandClass;
import buttondevteam.lib.chat.OptionallyPlayerCommandClass;
import com.palmergames.bukkit.towny.exceptions.NotRegisteredException;
import com.palmergames.bukkit.towny.object.Resident;
import com.palmergames.bukkit.towny.object.Town;
import lombok.RequiredArgsConstructor;
import lombok.val;
import org.bukkit.entity.Player;
@CommandClass // TODO: /u u when annotation not present
import java.lang.reflect.Method;
@CommandClass(helpText = {
"Town Color", //
"This command allows setting a color for a town.", //
"The town will be shown with this color on Dynmap and all players in the town will appear in chat with these colors.", //
"The colors will split the name evenly but residents can override that with /u ncolor.", //
}) // TODO: /u u when annotation not present
@OptionallyPlayerCommandClass(playerOnly = true)
@RequiredArgsConstructor
public class TownColorCommand extends UCommandBase {
private final TownColorComponent component;
@Override
public String GetHelpText(String alias)[] {
public String[] getHelpText(Method method, Command2.Subcommand ann) {
StringBuilder cns = new StringBuilder(" <colorname1>");
val comp = (TownColorComponent) getComponent();
for (int i = 2; i <= comp.colorCount().get(); i++)
for (int i = 2; i <= component.colorCount().get(); i++)
cns.append(" [colorname").append(i).append("]");
return new String[] { //
"§6---- Town Color ----", //
"This command allows setting a color for a town.", //
"The town will be shown with this color on Dynmap and all players in the town will appear in chat with these colors.", //
"The colors will split the name evenly.", //
"Usage: /" + GetCommandPath() + cns, //
"Example: /" + GetCommandPath() + " blue" //
"§6---- Town Color ----", //
"This command allows setting color(s) for a town.", //
"The town will be shown with this color on Dynmap and all players in the town will appear in chat with these colors.", //
"The colors will split the name evenly.", //
};
}
@Override
public boolean OnCommand(Player player, String alias, String[] args) {
@Command2.Subcommand
public boolean def(Player player, String... colornames) {
Resident res;
if (!(TownyComponent.TU.getResidentMap().containsKey(player.getName().toLowerCase())
&& (res = TownyComponent.TU.getResidentMap().get(player.getName().toLowerCase())).isMayor())) {
player.sendMessage("§cYou need to be the mayor of a town to set it's colors.");
player.sendMessage("§cYou need to be the mayor of a town to set its colors.");
return true;
}
val comp = (TownColorComponent) getComponent();
if (args.length > comp.colorCount().get()) {
player.sendMessage("You can only use " + comp.colorCount().get() + " color" + (comp.colorCount().get() > 1 ? "s" : "") + ".");
val cc = component.colorCount().get();
if (colornames.length > cc) {
player.sendMessage("You can only use " + cc + " color" + (cc > 1 ? "s" : "") + ".");
return true;
}
String[] a = new String[args.length + 1];
System.arraycopy(args, 0, a, 1, args.length);
final Town t;
try {
a[0] = res.getTown().getName();
t = res.getTown();
} catch (NotRegisteredException e) {
TBMCCoreAPI.SendException("Failed to set town color for player " + player + "!", e);
player.sendMessage("§cCouldn't find your town... Error reported.");
return true;
}
return buttondevteam.chat.components.towncolors.admin.TownColorCommand.SetTownColor(player, alias, a);
return buttondevteam.chat.components.towncolors.admin.TownColorCommand.SetTownColor(player, t, colornames);
}
}

View file

@ -10,8 +10,11 @@ import buttondevteam.lib.architecture.Component;
import buttondevteam.lib.architecture.ComponentMetadata;
import buttondevteam.lib.architecture.ConfigData;
import buttondevteam.lib.chat.Color;
import buttondevteam.lib.player.TBMCPlayerJoinEvent;
import com.earth2me.essentials.User;
import com.palmergames.bukkit.towny.exceptions.NotRegisteredException;
import com.palmergames.bukkit.towny.object.Nation;
import lombok.Getter;
import lombok.experimental.var;
import lombok.val;
import org.bukkit.Bukkit;
@ -19,6 +22,8 @@ import org.bukkit.ChatColor;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.dynmap.towny.DTBridge;
import org.dynmap.towny.DynmapTownyPlugin;
@ -31,7 +36,7 @@ import java.util.function.Function;
import java.util.stream.Collectors;
@ComponentMetadata(depends = TownyComponent.class)
public class TownColorComponent extends Component {
public class TownColorComponent extends Component<PluginMain> implements Listener {
/**
* Names lowercased
*/
@ -45,17 +50,22 @@ public class TownColorComponent extends Component {
return getConfig().getData("colorCount", (byte) 1, cc -> ((Integer) cc).byteValue(), Byte::intValue);
}
public ConfigData<Boolean> useNationColors() { //TODO
public ConfigData<Boolean> useNationColors() {
return getConfig().getData("useNationColors", true);
}
@Getter
private static TownColorComponent component;
@SuppressWarnings("unchecked")
@Override
protected void enable() {
component = this;
//TODO: Don't register all commands automatically (welp)
Consumer<ConfigurationSection> loadTC = cs -> TownColorComponent.TownColors.putAll(cs.getValues(true).entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey, v -> ((List<String>) v.getValue()).stream()
.map(Color::valueOf).toArray(Color[]::new))));
boolean usenc = useNationColors().get();
Consumer<ConfigurationSection> loadNC = ncs ->
TownColorComponent.NationColor.putAll(ncs.getValues(true).entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey, v -> Color.valueOf((String) v.getValue()))));
@ -64,14 +74,17 @@ public class TownColorComponent extends Component {
loadTC.accept(cs);
else
load_old(loadTC, null); //Load old data
var ncs = getConfig().getConfig().getConfigurationSection("nationcolors");
if (ncs != null)
loadNC.accept(ncs);
else
load_old(null, loadNC); //Why not choose by making different args null
if (usenc) {
var ncs = getConfig().getConfig().getConfigurationSection("nationcolors");
if (ncs != null)
loadNC.accept(ncs);
else
load_old(null, loadNC); //Why not choose by making different args null
}
TownColors.keySet().removeIf(t -> !TownyComponent.TU.getTownsMap().containsKey(t)); // Removes town colors for deleted/renamed towns
NationColor.keySet().removeIf(n -> !TownyComponent.TU.getNationsMap().containsKey(n)); // Removes nation colors for deleted/renamed nations
if (usenc)
NationColor.keySet().removeIf(n -> !TownyComponent.TU.getNationsMap().containsKey(n)); // Removes nation colors for deleted/renamed nations
Bukkit.getScheduler().runTask(getPlugin(), () -> {
val dtp = (DynmapTownyPlugin) Bukkit.getPluginManager().getPlugin("Dynmap-Towny");
@ -79,9 +92,12 @@ public class TownColorComponent extends Component {
return;
for (val entry : TownColors.entrySet()) {
try {
val nation = TownyComponent.TU.getTownsMap().get(entry.getKey()).getNation();
val town = TownyComponent.TU.getTownsMap().get(entry.getKey());
Nation nation;
Color nc;
if (nation == null || (nc = NationColor.get(nation.getName().toLowerCase())) == null)
if (!useNationColors().get())
nc = null;
else if (!town.hasNation() || (nation = town.getNation()) == null || (nc = NationColor.get(nation.getName().toLowerCase())) == null)
nc = Color.White;
setTownColor(dtp, buttondevteam.chat.components.towncolors.admin.TownColorCommand.getTownNameCased(entry.getKey()), entry.getValue(), nc);
} catch (Exception e) {
@ -90,19 +106,24 @@ public class TownColorComponent extends Component {
}
});
registerCommand(new TownColorCommand());
registerCommand(new NationColorCommand());
registerCommand(new TownColorCommand(this));
if (useNationColors().get())
registerCommand(new NationColorCommand());
registerCommand(new buttondevteam.chat.components.towncolors.admin.TownColorCommand());
registerCommand(new buttondevteam.chat.components.towncolors.admin.NationColorCommand());
if (useNationColors().get())
registerCommand(new buttondevteam.chat.components.towncolors.admin.NationColorCommand());
registerCommand(new TCCount());
registerListener(new TownyListener());
registerListener(this);
}
@Override
protected void disable() {
getConfig().getConfig().createSection("towncolors", TownColors.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey,
v -> Arrays.stream(v.getValue()).map(Enum::toString).toArray(String[]::new))));
getConfig().getConfig().createSection("nationcolors", NationColor.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey,
v -> v.getValue().toString())));
if (useNationColors().get())
getConfig().getConfig().createSection("nationcolors", NationColor.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey,
v -> v.getValue().toString())));
}
/**
@ -150,18 +171,20 @@ public class TownColorComponent extends Component {
len = name.length() / (clrs.length+1);
else
len = name.length() / clrs.length;*/
boolean usenc = component.useNationColors().get();
val nclar = cp.NameColorLocations().get();
int[] ncl = nclar == null ? null : nclar.stream().mapToInt(Integer::intValue).toArray();
if (ncl != null && (Arrays.stream(ncl).sum() != name.length() || ncl.length != clrs.length + 1)) //+1: Nation color
if (ncl != null && (Arrays.stream(ncl).sum() != name.length() || ncl.length != clrs.length + (usenc ? 1 : 0))) //+1: Nation color
ncl = null; // Reset if name length changed
//System.out.println("ncl: "+Arrays.toString(ncl)+" - sum: "+Arrays.stream(ncl).sum()+" - name len: "+name.length());
if (!res.getTown().hasNation()
|| (nc = NationColor.get(res.getTown().getNation().getName().toLowerCase())) == null)
nc = Color.White;
ret.append(anyColoredNamePart.apply(nc, ncl == null ? len : ncl[0])); //Make first color the nation color
if (usenc) {
if (!res.getTown().hasNation()
|| (nc = NationColor.get(res.getTown().getNation().getName().toLowerCase())) == null)
nc = Color.White;
ret.append(anyColoredNamePart.apply(nc, ncl == null ? len : ncl[0])); //Make first color the nation color
}
for (int i = 0; i < clrs.length; i++)
//ret.append(coloredNamePart.apply(ncl == null ? len : (nc==null?ncl[i]:ncl[i+1]), i));
ret.append(coloredNamePart.apply(ncl == null ? len : ncl[i + 1], i));
ret.append(coloredNamePart.apply(ncl == null ? len : (usenc ? ncl[i + 1] : ncl[i]), i));
return ret.toString();
} catch (NotRegisteredException e) {
return nickname;
@ -178,7 +201,7 @@ public class TownColorComponent extends Component {
/**
* Checks if the component is enabled
*/
public static void updatePlayerColors(Player player, ChatPlayer cp) { //Probably at join - nop, nicknames
private static void updatePlayerColors(Player player, ChatPlayer cp) { //Probably at join - nop, nicknames
if (!ComponentManager.isEnabled(TownColorComponent.class))
return;
User user = PluginMain.essentials.getUser(player);
@ -187,6 +210,11 @@ public class TownColorComponent extends Component {
cp.FlairUpdate(); //Update in list
}
@EventHandler
public void onPlayerJoin(TBMCPlayerJoinEvent event) {
updatePlayerColors(event.getPlayer(), event.GetPlayer().asPluginPlayer(ChatPlayer.class));
}
private static void load_old(Consumer<ConfigurationSection> loadTC,
Consumer<ConfigurationSection> loadNC) {
PluginMain.Instance.getLogger().info("Loading files...");

View file

@ -61,6 +61,7 @@ public class TownyListener implements Listener {
@EventHandler
public void onNationRename(RenameNationEvent event) {
if (!TownColorComponent.getComponent().useNationColors().get()) return;
val clrs = TownColorComponent.NationColor.remove(event.getOldName().toLowerCase());
if (clrs != null)
TownColorComponent.NationColor.put(event.getNation().getName().toLowerCase(), clrs);
@ -68,21 +69,25 @@ public class TownyListener implements Listener {
@EventHandler //Gets called on town load as well
public void onNationJoin(NationAddTownEvent event) {
if (!TownColorComponent.getComponent().useNationColors().get()) return;
updateTownMembers(event.getTown());
}
@EventHandler
public void onNationLeave(NationRemoveTownEvent event) {
if (!TownColorComponent.getComponent().useNationColors().get()) return;
updateTownMembers(event.getTown()); //The town still has it's colours
}
@EventHandler
public void onNationDelete(DeleteNationEvent event) {
if (!TownColorComponent.getComponent().useNationColors().get()) return;
TownColorComponent.NationColor.remove(event.getNationName().toLowerCase());
}
@EventHandler
public void onNationCreate(NewNationEvent event) {
if (!TownColorComponent.getComponent().useNationColors().get()) return;
Player p = Bukkit.getPlayer(event.getNation().getCapital().getMayor().getName());
if (p != null)
p.sendMessage("§6Use /u nationcolor to set a color for the nation.");

View file

@ -6,40 +6,31 @@ import buttondevteam.chat.components.towncolors.TownColorComponent;
import buttondevteam.chat.components.towncolors.TownyListener;
import buttondevteam.chat.components.towny.TownyComponent;
import buttondevteam.lib.chat.Color;
import buttondevteam.lib.chat.Command2;
import buttondevteam.lib.chat.CommandClass;
import com.palmergames.bukkit.towny.object.Nation;
import com.palmergames.bukkit.towny.object.Town;
import lombok.val;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
@CommandClass(helpText = {
"Nation color", //
"Sets the color of the nation.", //
})
public class NationColorCommand extends AdminCommandBase {
@Override
public String[] GetHelpText(String alias) {
return new String[]{ //
"§6---- Nation color ----", //
"Sets the color of the nation.", //
"Usage: /u admin nationcolor <color>" //
};
}
@Override
public boolean OnCommand(CommandSender sender, String alias, String[] args) {
return SetNationColor(sender, alias, args);
}
public static boolean SetNationColor(CommandSender sender, String alias, String[] args) {
if (args.length < 2)
return false;
if (args.length > 2) {
sender.sendMessage("§cYou can only use one color as a nation color.");
@Command2.Subcommand
public boolean def(CommandSender sender, String nation, String color) {
final Nation n = TownyComponent.TU.getNationsMap().get(nation.toLowerCase());
if (n == null) {
sender.sendMessage("§cThe nation '" + nation + "' cannot be found.");
return true;
}
final Nation nation = TownyComponent.TU.getNationsMap().get(args[0].toLowerCase());
if (nation == null) {
sender.sendMessage("§cThe nation '" + args[0] + "' cannot be found.");
return true;
}
val c = TownColorCommand.getColorOrSendError(args[1], sender);
return SetNationColor(sender, n, color);
}
public static boolean SetNationColor(CommandSender sender, Nation nation, String color) {
val c = TownColorCommand.getColorOrSendError(color, sender);
if (!c.isPresent()) return true;
if (!c.get().getName().equals(Color.White.getName())) { //Default nation color
for (val e : TownColorComponent.NationColor.entrySet()) {
@ -49,7 +40,7 @@ public class NationColorCommand extends AdminCommandBase {
}
}
}
TownColorComponent.NationColor.put(args[0].toLowerCase(), c.get());
TownColorComponent.NationColor.put(nation.getName().toLowerCase(), c.get());
Bukkit.getScheduler().runTaskAsynchronously(PluginMain.Instance, () -> {
for (Town t : nation.getTowns())
TownyListener.updateTownMembers(t);

View file

@ -2,28 +2,19 @@ package buttondevteam.chat.components.towncolors.admin;
import buttondevteam.chat.commands.ucmds.admin.AdminCommandBase;
import buttondevteam.chat.components.towncolors.TownColorComponent;
import buttondevteam.lib.chat.Command2;
import buttondevteam.lib.chat.CommandClass;
import lombok.val;
import org.bukkit.command.CommandSender;
@CommandClass(helpText = {
"Town Color Count", //
"Sets how many colors can be used for a town." //
})
public class TCCount extends AdminCommandBase {
@Override
public String[] GetHelpText(String alias) {
return new String[] { //
"§6---- Town Color Count", //
"Sets how many colors can be used for a town." //
};
}
@Override
public boolean OnCommand(CommandSender sender, String alias, String[] args) {
byte count;
try {
if (args.length == 0 || (count = Byte.parseByte(args[0])) <= 0)
return false;
} catch (NumberFormatException e) {
return false;
}
val comp = (TownColorComponent) getComponent();
@Command2.Subcommand
public boolean def(CommandSender sender, byte count) {
val comp = TownColorComponent.getComponent();
comp.colorCount().set(count);
sender.sendMessage("Color count set to " + count);
return true;

View file

@ -1,11 +1,12 @@
package buttondevteam.chat.components.towncolors.admin;
import buttondevteam.chat.PluginMain;
import buttondevteam.chat.commands.ucmds.admin.AdminCommandBase;
import buttondevteam.chat.components.towncolors.TownColorComponent;
import buttondevteam.chat.components.towncolors.TownyListener;
import buttondevteam.chat.components.towny.TownyComponent;
import buttondevteam.lib.chat.Color;
import buttondevteam.lib.chat.Command2;
import buttondevteam.lib.chat.CommandClass;
import com.palmergames.bukkit.towny.object.Town;
import lombok.val;
import org.bukkit.Bukkit;
@ -17,55 +18,52 @@ import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
public class TownColorCommand extends AdminCommandBase {
@Override
public String GetHelpText(String alias)[] { // TODO: Command path aliases
return new String[]{ //
"§6---- Town Color ----", //
"This command allows setting a color for a town.", //
"The town will be shown with this color on Dynmap and all players in the town will appear in chat with these colors.", //
"The colors will split the name evenly.", //
"Usage: /" + GetCommandPath() + " <town> <colorname1> [colorname2...]", //
"Example: /" + GetCommandPath() + " Alderon blue gray" //
};
}
@CommandClass(helpText = {
"Town Color", //
"This command allows setting a color for a town.", //
"The town will be shown with this color on Dynmap and all players in the town will appear in chat with these colors.", //
"The colors will split the name evenly.", //
})
public class TownColorCommand extends AdminCommandBase { //TODO: Command path aliases
@Command2.Subcommand
public boolean def(CommandSender sender, String town, String... colornames) {
if (!TownyComponent.TU.getTownsMap().containsKey(town.toLowerCase())) {
sender.sendMessage("§cThe town '" + town + "' cannot be found.");
return true;
}
Town targetTown = TownyComponent.TU.getTownsMap().get(town.toLowerCase());
return SetTownColor(sender, targetTown, colornames);
}
@Override
public boolean OnCommand(CommandSender sender, String alias, String[] args) {
return SetTownColor(sender, alias, args);
}
public static boolean SetTownColor(CommandSender sender, String alias, String[] args) {
if (args.length < 2)
return false;
if (!TownyComponent.TU.getTownsMap().containsKey(args[0].toLowerCase())) {
sender.sendMessage("§cThe town '" + args[0] + "' cannot be found.");
return true;
}
Color[] clrs = new Color[args.length - 1];
Town targetTown = TownyComponent.TU.getTownsMap().get(args[0].toLowerCase());
for (int i = 1; i < args.length; i++) {
val c = getColorOrSendError(args[i], sender);
public static boolean SetTownColor(CommandSender sender, Town town, String[] colors) {
Color[] clrs = new Color[colors.length];
for (int i = 0; i < colors.length; i++) {
val c = getColorOrSendError(colors[i], sender);
if (!c.isPresent())
return true;
clrs[i - 1] = c.get();
}
Color tnc;
try {
tnc = TownColorComponent.NationColor.get(targetTown.getNation().getName().toLowerCase());
} catch (Exception e) {
tnc = null;
}
if (tnc == null) tnc = Color.White; //Default nation color - TODO: Make configurable
boolean usenc = TownColorComponent.getComponent().useNationColors().get();
if (usenc) {
try {
tnc = TownColorComponent.NationColor.get(town.getNation().getName().toLowerCase());
} catch (Exception e) {
tnc = null;
}
if (tnc == null) tnc = Color.White; //Default nation color - TODO: Make configurable
} else tnc = null;
for (Map.Entry<String, Color[]> other : TownColorComponent.TownColors.entrySet()) {
Color nc;
try {
nc = TownColorComponent.NationColor.get(TownyComponent.TU.getTownsMap().get(other.getKey()).getNation().getName().toLowerCase());
} catch (Exception e) { //Too lazy for lots of null-checks and it may throw exceptions anyways
nc = null;
}
if (nc == null) nc = Color.White; //Default nation color
if (nc.getName().equals(tnc.getName())) {
if (usenc) {
try {
nc = TownColorComponent.NationColor.get(TownyComponent.TU.getTownsMap().get(other.getKey()).getNation().getName().toLowerCase());
} catch (Exception e) { //Too lazy for lots of null-checks and it may throw exceptions anyways
nc = null;
}
if (nc == null) nc = Color.White; //Default nation color
} else nc = null;
if (!usenc || nc.getName().equals(tnc.getName())) {
int C = 0;
if (clrs.length == other.getValue().length)
for (int i = 0; i < clrs.length; i++)
@ -78,16 +76,12 @@ public class TownColorCommand extends AdminCommandBase {
}
}
}
TownColorComponent.TownColors.put(args[0].toLowerCase(), clrs);
TownyListener.updateTownMembers(targetTown);
TownColorComponent.TownColors.put(town.getName().toLowerCase(), clrs);
TownyListener.updateTownMembers(town);
val dtp = (DynmapTownyPlugin) Bukkit.getPluginManager().getPlugin("Dynmap-Towny");
if (dtp == null) {
sender.sendMessage("§cDynmap-Towny couldn't be found §6but otherwise §btown color set.");
PluginMain.Instance.getLogger().warning("Dynmap-Towny not found for setting town color!");
return true;
}
TownColorComponent.setTownColor(dtp, targetTown.getName(), clrs, tnc);
if (dtp != null) //If it's not found then it's not loaded, it'll be noticed by the admins if needed
TownColorComponent.setTownColor(dtp, town.getName(), clrs, tnc);
sender.sendMessage("§bColor(s) set.");
return true;
}

View file

@ -1,8 +1,8 @@
package buttondevteam.chat.components.towny;
import buttondevteam.chat.ChatProcessing;
import buttondevteam.chat.PluginMain;
import buttondevteam.core.component.channel.Channel;
import buttondevteam.lib.TBMCSystemChatEvent;
import buttondevteam.lib.chat.TBMCChatAPI;
import com.palmergames.bukkit.towny.TownyLogger;
import lombok.val;
@ -22,19 +22,21 @@ public class TownyAnnouncer {
String groupID = m.group(2); //The group ID is correctly cased
switch (String.valueOf(m.group(1))) { //valueOf: Handles null
case "Town":
TBMCChatAPI.SendSystemMessage(PluginMain.TownChat,
if (townChannel == null) return;
TBMCChatAPI.SendSystemMessage(townChannel,
new Channel.RecipientTestResult(TownyComponent.getTownNationIndex(groupID, false), groupID),
logRecord.getMessage(), ChatProcessing.MCORIGIN);
logRecord.getMessage(), target, ChatProcessing.MCORIGIN);
break;
case "Nation":
TBMCChatAPI.SendSystemMessage(PluginMain.NationChat,
if (nationChannel == null) return;
TBMCChatAPI.SendSystemMessage(nationChannel,
new Channel.RecipientTestResult(TownyComponent.getTownNationIndex(groupID, true), groupID),
logRecord.getMessage(), ChatProcessing.MCORIGIN);
logRecord.getMessage(), target, ChatProcessing.MCORIGIN);
break;
case "Global":
TBMCChatAPI.SendSystemMessage(Channel.GlobalChat,
Channel.RecipientTestResult.ALL,
logRecord.getMessage(), ChatProcessing.MCORIGIN);
logRecord.getMessage(), target, ChatProcessing.MCORIGIN);
break;
}
}
@ -50,11 +52,22 @@ public class TownyAnnouncer {
}
};
public static void setup() {
private static TBMCSystemChatEvent.BroadcastTarget target;
private static Channel townChannel;
private static Channel nationChannel;
public static void setup(Channel townChannel, Channel nationChannel) {
target = TBMCSystemChatEvent.BroadcastTarget.add("towny");
TownyAnnouncer.townChannel = townChannel;
TownyAnnouncer.nationChannel = nationChannel;
TownyLogger.log.addHandler(HANDLER);
}
public static void setdown() {
TBMCSystemChatEvent.BroadcastTarget.remove(target);
target = null;
TownyAnnouncer.townChannel = null;
TownyAnnouncer.nationChannel = null;
TownyLogger.log.removeHandler(HANDLER);
}
}

View file

@ -1,6 +1,7 @@
package buttondevteam.chat.components.towny;
import buttondevteam.chat.PluginMain;
import buttondevteam.chat.formatting.TellrawPart;
import buttondevteam.core.component.channel.Channel;
import buttondevteam.lib.architecture.Component;
import buttondevteam.lib.chat.Color;
@ -17,23 +18,28 @@ import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
public class TownyComponent extends Component {
public class TownyComponent extends Component<PluginMain> {
public static TownyUniverse TU;
private static ArrayList<String> Towns;
private static ArrayList<String> Nations;
private Channel TownChat;
private Channel NationChat;
@Override
protected void enable() {
TU = ((Towny) Bukkit.getPluginManager().getPlugin("Towny")).getTownyUniverse();
Towns = TU.getTownsMap().values().stream().map(Town::getName).collect(Collectors.toCollection(ArrayList::new)); // Creates a snapshot of towns, new towns will be added when needed
Nations = TU.getNationsMap().values().stream().map(Nation::getName).collect(Collectors.toCollection(ArrayList::new)); // Same here but with nations
TBMCChatAPI.RegisterChatChannel(
PluginMain.TownChat = new Channel("§3TC§f", Color.DarkAqua, "tc", s -> checkTownNationChat(s, false)));
TownChat = new Channel("§3TC§f", Color.DarkAqua, "tc", s -> checkTownNationChat(s, false)));
TBMCChatAPI.RegisterChatChannel(
PluginMain.NationChat = new Channel("§6NC§f", Color.Gold, "nc", s -> checkTownNationChat(s, true)));
TownyAnnouncer.setup();
NationChat = new Channel("§6NC§f", Color.Gold, "nc", s -> checkTownNationChat(s, true)));
TownyAnnouncer.setup(TownChat, NationChat);
}
@Override
@ -41,6 +47,14 @@ public class TownyComponent extends Component {
TownyAnnouncer.setdown();
}
public void handleSpies(Channel channel, TellrawPart json, Function<TellrawPart, String> toJson) {
if (channel.ID.equals(TownChat.ID) || channel.ID.equals(NationChat.ID)) {
((List<TellrawPart>) json.getExtra()).add(0, new TellrawPart("[SPY]"));
String jsonstr = toJson.apply(json);
Bukkit.getServer().dispatchCommand(PluginMain.Console, String.format(
"tellraw @a[score_%s=1000,score_%s_min=1000] %s", channel.ID, channel.ID, jsonstr));
}
}
/**
* Return the error message for the message sender if they can't send it and the score
@ -49,13 +63,13 @@ public class TownyComponent extends Component {
if (!(sender instanceof Player))
return new Channel.RecipientTestResult("§cYou are not a player!");
Resident resident = TU.getResidentMap().get(sender.getName().toLowerCase());
Channel.RecipientTestResult result = checkTownNationChatInternal(sender, nationchat, resident);
Channel.RecipientTestResult result = checkTownNationChatInternal(nationchat, resident);
if (result.errormessage != null && resident != null && resident.getModes().contains("spy")) // Only use spy if they wouldn't see it
result = new Channel.RecipientTestResult(1000, "allspies"); // There won't be more than a thousand towns/nations probably
return result;
}
private static Channel.RecipientTestResult checkTownNationChatInternal(CommandSender sender, boolean nationchat,
private static Channel.RecipientTestResult checkTownNationChatInternal(boolean nationchat,
Resident resident) {
try {
/*

View file

@ -3,16 +3,13 @@ package buttondevteam.chat.listener;
import buttondevteam.chat.ChatPlayer;
import buttondevteam.chat.PlayerJoinTimerTask;
import buttondevteam.chat.PluginMain;
import buttondevteam.chat.commands.UnlolCommand;
import buttondevteam.chat.commands.ucmds.HistoryCommand;
import buttondevteam.chat.components.flair.FlairComponent;
import buttondevteam.chat.components.flair.FlairStates;
import buttondevteam.chat.components.towncolors.TownColorComponent;
import buttondevteam.core.ComponentManager;
import buttondevteam.lib.player.TBMCPlayerJoinEvent;
import buttondevteam.lib.player.TBMCPlayerLoadEvent;
import buttondevteam.lib.player.TBMCPlayerSaveEvent;
import org.bukkit.GameMode;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
@ -58,16 +55,9 @@ public class PlayerJoinLeaveListener implements Listener {
nwithoutformatting = nwithoutformatting.replace("§" + nwithoutformatting.charAt(index + 1), "");
} else
nwithoutformatting = p.getName();
PlayerListener.nicknames.forcePut(nwithoutformatting.toLowerCase(), p.getUniqueId());
PlayerListener.nicknames.forcePut(nwithoutformatting.toLowerCase(), p.getUniqueId()); //TODO: FormatterComponent
TownColorComponent.updatePlayerColors(p, cp); //TO!DO: Doesn't have effect - It can help to register the listener
if (cp.ChatOnly || p.getGameMode().equals(GameMode.SPECTATOR)) {
cp.ChatOnly = false;
p.setGameMode(GameMode.SURVIVAL);
}
HistoryCommand.showHistory(e.getPlayer(), "u history", new String[0], null);
HistoryCommand.showHistory(e.getPlayer(), null);
}
@EventHandler
@ -77,7 +67,6 @@ public class PlayerJoinLeaveListener implements Listener {
@EventHandler
public void onPlayerLeave(PlayerQuitEvent event) {
PlayerListener.nicknames.inverse().remove(event.getPlayer().getUniqueId());
UnlolCommand.Lastlol.values().removeIf(lld -> lld.getLolowner().equals(event.getPlayer()));
}
}

View file

@ -12,16 +12,15 @@ import buttondevteam.core.component.channel.ChatChannelRegisterEvent;
import buttondevteam.core.component.channel.ChatRoom;
import buttondevteam.lib.TBMCChatEvent;
import buttondevteam.lib.TBMCCoreAPI;
import buttondevteam.lib.TBMCSystemChatEvent;
import buttondevteam.lib.ThorpeUtils;
import buttondevteam.lib.chat.ChatMessage;
import buttondevteam.lib.chat.TBMCChatAPI;
import buttondevteam.lib.player.ChromaGamerBase;
import buttondevteam.lib.player.ChromaGamerBase.InfoTarget;
import buttondevteam.lib.player.TBMCPlayer;
import buttondevteam.lib.player.TBMCPlayerGetInfoEvent;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import com.vexsoftware.votifier.model.Vote;
import com.vexsoftware.votifier.model.VotifierEvent;
import lombok.val;
import net.ess3.api.events.NickChangeEvent;
import org.bukkit.Bukkit;
@ -32,18 +31,13 @@ import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.player.*;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.event.player.PlayerChatTabCompleteEvent;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.event.server.ServerCommandEvent;
import org.bukkit.help.HelpTopic;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import org.bukkit.scheduler.BukkitTask;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map.Entry;
import java.util.Random;
import java.util.UUID;
import java.util.function.BiPredicate;
@ -53,14 +47,11 @@ public class PlayerListener implements Listener {
*/
public static BiMap<String, UUID> nicknames = HashBiMap.create();
public final static String[] LaughStrings = new String[]{"xd", "lel", "lawl", "kek", "lmao", "hue", "hah", "rofl"};
@EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerChat(AsyncPlayerChatEvent event) {
if (event.isCancelled())
return;
ChatPlayer cp = TBMCPlayer.getPlayer(event.getPlayer().getUniqueId(), ChatPlayer.class);
TBMCChatAPI.SendChatMessage(ChatMessage.builder(event.getPlayer(), cp, event.getMessage()).build());
//The custom event is called in the core, but doesn't cancel the MC event
event.setCancelled(true); // The custom event should only be cancelled when muted or similar
}
@ -103,12 +94,12 @@ public class PlayerListener implements Listener {
if (cmd.equalsIgnoreCase("tpahere")) {
Player player = Bukkit.getPlayer(message.substring(index + 1));
if (player != null && sender instanceof Player)
player.sendMessage("§b" + ((Player) sender).getDisplayName() + " §bis in this world: "
player.sendMessage("§b" + ((Player) sender).getDisplayName() + " §bis in this world: " //TODO: Move to the Core
+ ((Player) sender).getWorld().getName());
} else if (cmd.equalsIgnoreCase("minecraft:me")) {
if (!(sender instanceof Player) || !PluginMain.essentials.getUser((Player) sender).isMuted()) {
String msg = message.substring(index + 1);
Bukkit.broadcastMessage(String.format("* %s %s", sender instanceof Player ? ((Player) sender).getDisplayName() : sender.getName(), msg));
TBMCChatAPI.SendSystemMessage(Channel.GlobalChat, Channel.RecipientTestResult.ALL, String.format("* %s %s", ThorpeUtils.getDisplayName(sender), msg), TBMCSystemChatEvent.BroadcastTarget.ALL); //TODO: Don't send to all
return true;
} else {
sender.sendMessage("§cCan't use /minecraft:me while muted.");
@ -132,26 +123,6 @@ public class PlayerListener implements Listener {
}
// TODO: Target selectors
}
// We don't care if we have arguments
if (cmd.toLowerCase().startsWith("un")) {
for (HelpTopic ht : PluginMain.Instance.getServer().getHelpMap().getHelpTopics()) {
if (ht.getName().equalsIgnoreCase("/" + cmd))
return false;
}
if (PluginMain.permission.has(sender, "tbmc.admin")) {
String s = cmd.substring(2);
Player target = Bukkit.getPlayer(message.substring(index + 1));
if (target == null) {
sender.sendMessage("§cError: Player not found. (/un" + s + " <player>)");
return true;
}
target.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, 10 * 20, 5, false, false));
Bukkit.broadcastMessage(
(sender instanceof Player ? ((Player) sender).getDisplayName() : sender.getName()) + " un" + s
+ "'d " + target.getDisplayName());
return true;
}
}
return false;
}
@ -164,68 +135,6 @@ public class PlayerListener implements Listener {
}
}
public static boolean ActiveF = false;
public static ChatPlayer FPlayer = null;
public static BukkitTask Ftask = null;
public static ArrayList<CommandSender> Fs = new ArrayList<>();
@EventHandler
public void onPlayerDeath(PlayerDeathEvent e) {
// MinigamePlayer mgp = Minigames.plugin.pdata.getMinigamePlayer(e.getEntity());
if (/* (mgp != null && !mgp.isInMinigame()) && */ new Random().nextBoolean()) { // Don't store Fs for NPCs
Runnable tt = () -> {
if (ActiveF) {
ActiveF = false;
if (FPlayer != null && FPlayer.FCount().get() < Integer.MAX_VALUE - 1)
FPlayer.FCount().set(FPlayer.FCount().get() + Fs.size());
Bukkit.broadcastMessage("§b" + Fs.size() + " " + (Fs.size() == 1 ? "person" : "people")
+ " paid their respects.§r");
Fs.clear();
}
};
if (Ftask != null) {
Ftask.cancel();
tt.run(); //Finish previous one
}
ActiveF = true;
Fs.clear();
FPlayer = TBMCPlayer.getPlayer(e.getEntity().getUniqueId(), ChatPlayer.class);
FPlayer.FDeaths().set(FPlayer.FDeaths().get() + 1);
Bukkit.broadcastMessage("§bPress F to pay respects.§r");
Bukkit.getScheduler().runTaskLaterAsynchronously(PluginMain.Instance, tt, 15 * 20);
}
}
@EventHandler
@SuppressWarnings("deprecation")
public void onVotifierEvent(VotifierEvent event) { //TODO: Move to teh Core eh
Vote vote = event.getVote();
PluginMain.Instance.getLogger().info("Vote: " + vote);
org.bukkit.OfflinePlayer op = Bukkit.getOfflinePlayer(vote.getUsername());
Player p = Bukkit.getPlayer(vote.getUsername());
if (op != null) {
PluginMain.economy.depositPlayer(op, 50.0);
}
if (p != null) {
p.sendMessage("§bThanks for voting! $50 was added to your account.");
}
}
@EventHandler
public void onPlayerMove(PlayerMoveEvent e) {
ChatPlayer mp = TBMCPlayer.getPlayer(e.getPlayer().getUniqueId(), ChatPlayer.class);
if (mp.ChatOnly)
e.setCancelled(true);
}
@EventHandler(priority = EventPriority.LOWEST)
public void onPlayerTeleport(PlayerTeleportEvent e) {
if (TBMCPlayer.getPlayer(e.getPlayer().getUniqueId(), ChatPlayer.class).ChatOnly) {
e.setCancelled(true);
e.getPlayer().sendMessage("§cYou are not allowed to teleport while in chat-only mode.");
}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onConsoleCommand(ServerCommandEvent event) {
if (onCommandPreprocess(event.getSender(), event.getCommand()))
@ -259,12 +168,12 @@ public class PlayerListener implements Listener {
HistoryCommand.addChatMessage(e.getCm(), e.getChannel());
e.setCancelled(ChatProcessing.ProcessChat(e));
} catch (NoClassDefFoundError | Exception ex) { // Weird things can happen
val str = "§c!§r[" + e.getChannel().DisplayName().get() + "] <"
+ ThorpeUtils.getDisplayName(e.getSender()) + "> " + e.getMessage();
for (Player p : Bukkit.getOnlinePlayers())
if (e.shouldSendTo(p))
p.sendMessage("§c!§r["
+ e.getChannel().DisplayName().get() + "] <" + (e.getSender() instanceof Player
? ((Player) e.getSender()).getDisplayName() : e.getSender().getName())
+ "> " + e.getMessage());
p.sendMessage(str);
Bukkit.getConsoleSender().sendMessage(str);
TBMCCoreAPI.SendException("An error occured while processing a chat message!", ex);
}
}

View file

@ -1,4 +1,4 @@
name: ButtonChat
name: Thorpe-Chat
main: buttondevteam.chat.PluginMain
version: 4.0
commands:
@ -33,13 +33,12 @@ commands:
author: NorbiPeti
depend:
- Essentials
- Towny
- Votifier
- Vault
- ThorpeCore
soft-depend:
- Minigames
- Dynmap-Towny
- Towny
permissions:
tbmc.admin:
description: Gives access to /un- commands and /u admin commands

View file

@ -92,7 +92,7 @@ public class ChatFormatIT {
@Test
public void testMessage() {
ArrayList<ChatFormatter> cfs = ChatProcessing.addFormatters(Color.White);
final String chid = ChatProcessing.getChannelID(Channel.GlobalChat, sender, ChatProcessing.MCORIGIN);
final String chid = ChatProcessing.getChannelID(Channel.GlobalChat, ChatProcessing.MCORIGIN);
final TellrawPart tp = ChatProcessing.createTellraw(sender, message, null, null, null, chid, ChatProcessing.MCORIGIN);
ChatFormatter.Combine(cfs, message, tp);
System.out.println("Testing: " + message);