Using ChatColors and convert remresidents command that we don't need anymore

This commit is contained in:
Norbi Peti 2023-04-19 02:55:41 +02:00
parent 6d0d9adef5
commit 17758bb54e
No known key found for this signature in database
GPG key ID: DBA4C4549A927E56
17 changed files with 178 additions and 213 deletions

View file

@ -26,9 +26,9 @@ public class ChromaCommand extends ICommand2MC {
if (plugin == null) if (plugin == null)
plugin = getPlugin(); plugin = getPlugin();
if (plugin.tryReloadConfig()) if (plugin.tryReloadConfig())
sender.sendMessage("§b" + plugin.getName() + " config reloaded."); sender.sendMessage("${ChatColor.AQUA}" + plugin.getName() + " config reloaded.");
else else
sender.sendMessage("§cFailed to reload config. Check console."); sender.sendMessage("${ChatColor.RED}Failed to reload config. Check console.");
} }
@Command2.Subcommand @Command2.Subcommand

View file

@ -11,6 +11,7 @@ import buttondevteam.lib.chat.CommandClass
import buttondevteam.lib.chat.CustomTabCompleteMethod import buttondevteam.lib.chat.CustomTabCompleteMethod
import buttondevteam.lib.chat.ICommand2MC import buttondevteam.lib.chat.ICommand2MC
import org.bukkit.Bukkit import org.bukkit.Bukkit
import org.bukkit.ChatColor
import org.bukkit.command.CommandSender import org.bukkit.command.CommandSender
import org.bukkit.plugin.Plugin import org.bukkit.plugin.Plugin
import org.bukkit.plugin.java.JavaPlugin import org.bukkit.plugin.java.JavaPlugin
@ -30,7 +31,7 @@ class ComponentCommand : ICommand2MC() {
fun enable(sender: CommandSender, plugin: Plugin, component: String, @OptionalArg permanent: Boolean): Boolean { fun enable(sender: CommandSender, plugin: Plugin, component: String, @OptionalArg permanent: Boolean): Boolean {
if (plugin is ButtonPlugin) { if (plugin is ButtonPlugin) {
if (!plugin.justReload()) { if (!plugin.justReload()) {
sender.sendMessage("§cCouldn't reload config, check console.") sender.sendMessage("${ChatColor.RED}Couldn't reload config, check console.")
return true return true
} }
} else plugin.reloadConfig() //Reload config so the new config values are read - All changes are saved to disk on disable } else plugin.reloadConfig() //Reload config so the new config values are read - All changes are saved to disk on disable
@ -44,7 +45,7 @@ class ComponentCommand : ICommand2MC() {
@Subcommand(helpText = ["List components", "Lists all of the registered Chroma components"]) @Subcommand(helpText = ["List components", "Lists all of the registered Chroma components"])
fun list(sender: CommandSender, @OptionalArg plugin: String?): Boolean { fun list(sender: CommandSender, @OptionalArg plugin: String?): Boolean {
sender.sendMessage("§6List of components:") sender.sendMessage("${ChatColor.GOLD}List of components:")
//If plugin is null, don't check for it //If plugin is null, don't check for it
components.values.stream().filter { c -> plugin == null || c.plugin.name.equals(plugin, ignoreCase = true) } components.values.stream().filter { c -> plugin == null || c.plugin.name.equals(plugin, ignoreCase = true) }
.map { c -> "${c.plugin.name} - ${c.javaClass.simpleName} - ${if (c.isEnabled) "en" else "dis"}abled" } .map { c -> "${c.plugin.name} - ${c.javaClass.simpleName} - ${if (c.isEnabled) "en" else "dis"}abled" }
@ -92,7 +93,7 @@ class ComponentCommand : ICommand2MC() {
private fun getComponentOrError(plugin: Plugin, arg: String, sender: CommandSender): Optional<Component<*>> { private fun getComponentOrError(plugin: Plugin, arg: String, sender: CommandSender): Optional<Component<*>> {
// TODO: Extend param converter to support accessing previous params // TODO: Extend param converter to support accessing previous params
val oc = getPluginComponents(plugin).filter { it.javaClass.simpleName.equals(arg, ignoreCase = true) }.findAny() val oc = getPluginComponents(plugin).filter { it.javaClass.simpleName.equals(arg, ignoreCase = true) }.findAny()
if (!oc.isPresent) sender.sendMessage("§cComponent not found!") if (!oc.isPresent) sender.sendMessage("${ChatColor.RED}Component not found!")
return oc return oc
} }
} }

View file

@ -20,6 +20,7 @@ import com.earth2me.essentials.Essentials
import net.milkbowl.vault.economy.Economy import net.milkbowl.vault.economy.Economy
import net.milkbowl.vault.permission.Permission import net.milkbowl.vault.permission.Permission
import org.bukkit.Bukkit import org.bukkit.Bukkit
import org.bukkit.ChatColor
import org.bukkit.OfflinePlayer import org.bukkit.OfflinePlayer
import org.bukkit.command.BlockCommandSender import org.bukkit.command.BlockCommandSender
import org.bukkit.command.Command import org.bukkit.command.Command
@ -91,26 +92,36 @@ class MainPlugin : ButtonPlugin() {
) )
} }
TBMCCoreAPI.RegisterUserClass(TBMCPlayerBase::class.java) { TBMCPlayer() } TBMCCoreAPI.RegisterUserClass(TBMCPlayerBase::class.java) { TBMCPlayer() }
TBMCChatAPI.registerChatChannel(Channel("§fg§f", Color.White, "g", null) TBMCChatAPI.registerChatChannel(Channel("${ChatColor.WHITE}g${ChatColor.WHITE}", Color.White, "g", null)
.also { Channel.globalChat = it }) //The /ooc ID has moved to the config .also { Channel.globalChat = it }) //The /ooc ID has moved to the config
TBMCChatAPI.registerChatChannel(Channel("§cADMIN§f", Color.Red, "a", Channel.inGroupFilter(null)) TBMCChatAPI.registerChatChannel(Channel(
"${ChatColor.RED}ADMIN${ChatColor.WHITE}",
Color.Red,
"a",
Channel.inGroupFilter(null)
)
.also { Channel.adminChat = it }) .also { Channel.adminChat = it })
TBMCChatAPI.registerChatChannel(Channel("§9MOD§f", Color.Blue, "mod", Channel.inGroupFilter("mod")) TBMCChatAPI.registerChatChannel(Channel(
"§9MOD${ChatColor.WHITE}",
Color.Blue,
"mod",
Channel.inGroupFilter("mod")
)
.also { Channel.modChat = it }) .also { Channel.modChat = it })
TBMCChatAPI.registerChatChannel( TBMCChatAPI.registerChatChannel(
Channel( Channel(
"§6DEV§f", "${ChatColor.GOLD}DEV${ChatColor.WHITE}",
Color.Gold, Color.Gold,
"dev", "dev",
Channel.inGroupFilter("developer") Channel.inGroupFilter("developer")
) )
) // TODO: Make groups configurable ) // TODO: Make groups configurable
TBMCChatAPI.registerChatChannel(ChatRoom("§cRED§f", Color.DarkRed, "red")) TBMCChatAPI.registerChatChannel(ChatRoom("${ChatColor.RED}RED${ChatColor.WHITE}", Color.DarkRed, "red"))
TBMCChatAPI.registerChatChannel(ChatRoom("§6ORANGE§f", Color.Gold, "orange")) TBMCChatAPI.registerChatChannel(ChatRoom("${ChatColor.GOLD}ORANGE${ChatColor.WHITE}", Color.Gold, "orange"))
TBMCChatAPI.registerChatChannel(ChatRoom("§eYELLOW§f", Color.Yellow, "yellow")) TBMCChatAPI.registerChatChannel(ChatRoom("§eYELLOW${ChatColor.WHITE}", Color.Yellow, "yellow"))
TBMCChatAPI.registerChatChannel(ChatRoom("§aGREEN§f", Color.Green, "green")) TBMCChatAPI.registerChatChannel(ChatRoom("§aGREEN${ChatColor.WHITE}", Color.Green, "green"))
TBMCChatAPI.registerChatChannel(ChatRoom("§bBLUE§f", Color.Blue, "blue")) TBMCChatAPI.registerChatChannel(ChatRoom("${ChatColor.AQUA}BLUE${ChatColor.WHITE}", Color.Blue, "blue"))
TBMCChatAPI.registerChatChannel(ChatRoom("§5PURPLE§f", Color.DarkPurple, "purple")) TBMCChatAPI.registerChatChannel(ChatRoom("§5PURPLE${ChatColor.WHITE}", Color.DarkPurple, "purple"))
val playerSupplier = Supplier { Bukkit.getOnlinePlayers().map { obj -> obj.name }.asIterable() } val playerSupplier = Supplier { Bukkit.getOnlinePlayers().map { obj -> obj.name }.asIterable() }
command2MC.addParamConverter( command2MC.addParamConverter(
OfflinePlayer::class.java, OfflinePlayer::class.java,
@ -151,7 +162,7 @@ class MainPlugin : ButtonPlugin() {
override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<String>): Boolean { override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<String>): Boolean {
if (command.name == "dontrunthiscmd") return true //Used in chat preprocess for console if (command.name == "dontrunthiscmd") return true //Used in chat preprocess for console
sender.sendMessage("§cThis command isn't available.") //In theory, unregistered commands use this method sender.sendMessage("${ChatColor.RED}This command isn't available.") //In theory, unregistered commands use this method
return true return true
} }

View file

@ -45,6 +45,6 @@ public class TestPrepare {
} }
})); }));
Component.registerComponent(Mockito.mock(JavaPlugin.class), new ChannelComponent()); Component.registerComponent(Mockito.mock(JavaPlugin.class), new ChannelComponent());
TBMCChatAPI.registerChatChannel(Channel.globalChat = new Channel("§fg§f", Color.White, "g", null)); TBMCChatAPI.registerChatChannel(Channel.globalChat = new Channel("${ChatColor.WHITE}g${ChatColor.WHITE}", Color.White, "g", null));
} }
} }

View file

@ -6,6 +6,7 @@ import buttondevteam.lib.architecture.Component
import buttondevteam.lib.chat.* import buttondevteam.lib.chat.*
import buttondevteam.lib.chat.Command2.* import buttondevteam.lib.chat.Command2.*
import buttondevteam.lib.player.ChromaGamerBase import buttondevteam.lib.player.ChromaGamerBase
import org.bukkit.ChatColor
import org.bukkit.plugin.java.JavaPlugin import org.bukkit.plugin.java.JavaPlugin
/** /**
@ -41,7 +42,7 @@ class ChannelComponent : Component<JavaPlugin>() {
val sender = senderMC.sender val sender = senderMC.sender
val user = ChromaGamerBase.getFromSender(sender) val user = ChromaGamerBase.getFromSender(sender)
if (user == null) { if (user == null) {
sender.sendMessage("§cYou can't use channels from this platform.") sender.sendMessage("${ChatColor.RED}You can't use channels from this platform.")
return return
} }
if (message == null) { if (message == null) {
@ -51,7 +52,7 @@ class ChannelComponent : Component<JavaPlugin>() {
user.channel.set(channel) user.channel.set(channel)
if (channel is ChatRoom) channel.joinRoom(sender) if (channel is ChatRoom) channel.joinRoom(sender)
} }
sender.sendMessage("§6You are now talking in: §b" + user.channel.get().displayName.get()) sender.sendMessage("${ChatColor.GOLD}You are now talking in: ${ChatColor.AQUA}" + user.channel.get().displayName.get())
} else TBMCChatAPI.sendChatMessage( } else TBMCChatAPI.sendChatMessage(
ChatMessage.builder(sender, user, message).fromCommand(true) ChatMessage.builder(sender, user, message).fromCommand(true)
.permCheck(senderMC.permCheck).build(), channel .permCheck(senderMC.permCheck).build(), channel

View file

@ -1,72 +1,67 @@
package buttondevteam.core.component.members; package buttondevteam.core.component.members
import buttondevteam.core.MainPlugin; import buttondevteam.core.MainPlugin
import buttondevteam.lib.chat.Command2; import buttondevteam.lib.chat.Command2.Subcommand
import buttondevteam.lib.chat.CommandClass; import buttondevteam.lib.chat.CommandClass
import buttondevteam.lib.chat.ICommand2MC; import buttondevteam.lib.chat.ICommand2MC
import org.bukkit.Bukkit; import buttondevteam.lib.chat.commands.MCCommandSettings
import org.bukkit.OfflinePlayer; import org.bukkit.Bukkit
import org.bukkit.command.CommandSender; import org.bukkit.ChatColor
import org.bukkit.entity.Player; import org.bukkit.OfflinePlayer
import org.bukkit.command.CommandSender
import org.bukkit.entity.Player
import java.util.concurrent.TimeUnit
import java.util.concurrent.TimeUnit; @CommandClass(
path = "member", helpText = [ //
"Member command", //
"Add or remove server members."]
)
class MemberCommand() : ICommand2MC() {
@Subcommand
@MCCommandSettings(permGroup = MCCommandSettings.MOD_GROUP)
fun add(sender: CommandSender, player: OfflinePlayer): Boolean {
return addRemove(sender, player, true)
}
@CommandClass(path = "member", helpText = { // @Subcommand
"Member command", // @MCCommandSettings(permGroup = MCCommandSettings.MOD_GROUP)
"Add or remove server members.", // fun remove(sender: CommandSender, player: OfflinePlayer): Boolean {
}) return addRemove(sender, player, false)
public class MemberCommand extends ICommand2MC { }
private final MemberComponent component;
public MemberCommand(MemberComponent component) { private fun addRemove(sender: CommandSender, op: OfflinePlayer, add: Boolean): Boolean {
this.component = component; Bukkit.getScheduler().runTaskAsynchronously(MainPlugin.instance, Runnable {
} val component = component as MemberComponent
if (!op.hasPlayedBefore()) {
sender.sendMessage("${ChatColor.RED}Cannot find player or haven't played before.")
return@Runnable
}
if (if (add) MainPlugin.permission.playerAddGroup(null, op, component.memberGroup.get())
else MainPlugin.permission.playerRemoveGroup(null, op, component.memberGroup.get())
)
sender.sendMessage("${ChatColor.AQUA}${op.name} ${if (add) "added" else "removed"} as a member!")
else sender.sendMessage("${ChatColor.RED}Failed to ${if (add) "add" else "remove"} ${op.name} as a member!")
})
return true
}
@Command2.Subcommand(permGroup = Command2.Subcommand.MOD_GROUP) @Subcommand
public boolean add(CommandSender sender, OfflinePlayer player) { fun def(player: Player) {
return addRemove(sender, player, true); val component = component as MemberComponent
} val msg = if (!component.checkNotMember(player)) "You are a member." else {
val pt = component.getPlayTime(player)
@Command2.Subcommand(permGroup = Command2.Subcommand.MOD_GROUP) val rt = component.getRegTime(player)
public boolean remove(CommandSender sender, OfflinePlayer player) { if (pt == -1.0 || rt == -1L) {
return addRemove(sender, player, false); val result = component.addPlayerAsMember(player)
} if (result == null) "Can't assign member group because groups are not supported by the permissions plugin."
else if (result) "You meet all the requirements."
public boolean addRemove(CommandSender sender, OfflinePlayer op, boolean add) { else "You should be a member but failed to add you to the group."
Bukkit.getScheduler().runTaskAsynchronously(MainPlugin.instance, () -> { } else String.format(
if (!op.hasPlayedBefore()) { "You need to play for %.2f hours total or play for %d more days to become a member.",
sender.sendMessage("§cCannot find player or haven't played before."); pt, TimeUnit.MILLISECONDS.toDays(rt)
return; )
} }
if (add ? MainPlugin.permission.playerAddGroup(null, op, component.memberGroup.get()) player.sendMessage(msg)
: MainPlugin.permission.playerRemoveGroup(null, op, component.memberGroup.get())) }
sender.sendMessage("§b" + op.getName() + " " + (add ? "added" : "removed") + " as a member!"); }
else
sender.sendMessage("§cFailed to " + (add ? "add" : "remove") + " " + op.getName() + " as a member!");
});
return true;
}
@Command2.Subcommand
public void def(Player player) {
String msg;
if (!component.checkNotMember(player))
msg = "You are a member.";
else {
double pt = component.getPlayTime(player);
long rt = component.getRegTime(player);
if (pt == -1 || rt == -1) {
Boolean result = component.addPlayerAsMember(player);
if (result == null)
msg = "Can't assign member group because groups are not supported by the permissions plugin.";
else if (result)
msg = "You meet all the requirements.";
else
msg = "You should be a member but failed to add you to the group.";
} else
msg = String.format("You need to play for %.2f hours total or play for %d more days to become a member.",
pt, TimeUnit.MILLISECONDS.toDays(rt));
}
player.sendMessage(msg);
}
}

View file

@ -42,7 +42,7 @@ public class MemberComponent extends Component<MainPlugin> implements Listener {
@Override @Override
protected void enable() { protected void enable() {
registerListener(this); registerListener(this);
registerCommand(new MemberCommand(this)); registerCommand(new MemberCommand());
try { try {
playtime = new AbstractMap.SimpleEntry<>(Statistic.valueOf("PLAY_ONE_MINUTE"), 60); //1.14 playtime = new AbstractMap.SimpleEntry<>(Statistic.valueOf("PLAY_ONE_MINUTE"), 60); //1.14
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
@ -64,7 +64,7 @@ public class MemberComponent extends Component<MainPlugin> implements Listener {
public Boolean addPlayerAsMember(Player player) { public Boolean addPlayerAsMember(Player player) {
try { try {
if (permission.playerAddGroup(null, player, memberGroup.get())) { if (permission.playerAddGroup(null, player, memberGroup.get())) {
player.sendMessage("§bYou are a member now!"); player.sendMessage("${ChatColor.AQUA}You are a member now!");
log("Added " + player.getName() + " as a member."); log("Added " + player.getName() + " as a member.");
return true; return true;
} else { } else {

View file

@ -7,11 +7,9 @@ import org.bukkit.*;
import org.bukkit.command.CommandSender; import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import java.util.logging.Logger;
// @formatter:off // @formatter:off
@SuppressWarnings("FieldCanBeLocal")@CommandClass(helpText = { @SuppressWarnings("FieldCanBeLocal")@CommandClass(helpText = {
"§6---- Random Teleport ----", "Random Teleport",
"Teleport player to random location within world border. Every five players teleport to the same general area, and then a new general area is randomly selected for the next five players." "Teleport player to random location within world border. Every five players teleport to the same general area, and then a new general area is randomly selected for the next five players."
}) })
public class RandomTP extends ICommand2MC public class RandomTP extends ICommand2MC
@ -94,8 +92,8 @@ public class RandomTP extends ICommand2MC
&& !newLocation()) && !newLocation())
{ {
//if unable to find new location, message player and return false //if unable to find new location, message player and return false
player.sendMessage("§c could not find a location in 10,000 attempts"); player.sendMessage("${ChatColor.RED} could not find a location in 10,000 attempts");
player.sendMessage("§c (sorry bud... I did try!)"); player.sendMessage("${ChatColor.RED} (sorry bud... I did try!)");
return false; return false;
} }
@ -177,37 +175,25 @@ public class RandomTP extends ICommand2MC
southHeadMaterial == Material.AIR && southHeadMaterial == Material.AIR &&
eastHeadMaterial == Material.AIR && eastHeadMaterial == Material.AIR &&
westHeadMaterial == Material.AIR && westHeadMaterial == Material.AIR &&
centerFeetMaterial == Material.AIR && centerFeetMaterial == Material.AIR &&
northFeetMaterial == Material.AIR && northFeetMaterial == Material.AIR &&
southFeetMaterial == Material.AIR && southFeetMaterial == Material.AIR &&
eastFeetMaterial == Material.AIR && eastFeetMaterial == Material.AIR &&
westFeetMaterial == Material.AIR && westFeetMaterial == Material.AIR &&
centerGroundMaterial != Material.AIR && centerGroundMaterial != Material.AIR &&
northGroundMaterial != Material.AIR && northGroundMaterial != Material.AIR &&
southGroundMaterial != Material.AIR && southGroundMaterial != Material.AIR &&
eastGroundMaterial != Material.AIR && eastGroundMaterial != Material.AIR &&
westGroundMaterial != Material.AIR && westGroundMaterial != Material.AIR &&
centerGroundMaterial != Material.STATIONARY_WATER &&
northGroundMaterial != Material.STATIONARY_WATER &&
southGroundMaterial != Material.STATIONARY_WATER &&
eastGroundMaterial != Material.STATIONARY_WATER &&
westGroundMaterial != Material.STATIONARY_WATER &&
centerGroundMaterial != Material.WATER && centerGroundMaterial != Material.WATER &&
northGroundMaterial != Material.WATER && northGroundMaterial != Material.WATER &&
southGroundMaterial != Material.WATER && southGroundMaterial != Material.WATER &&
eastGroundMaterial != Material.WATER && eastGroundMaterial != Material.WATER &&
westGroundMaterial != Material.WATER && westGroundMaterial != Material.WATER &&
centerGroundMaterial != Material.STATIONARY_LAVA &&
northGroundMaterial != Material.STATIONARY_LAVA &&
southGroundMaterial != Material.STATIONARY_LAVA &&
eastGroundMaterial != Material.STATIONARY_LAVA &&
westGroundMaterial != Material.STATIONARY_LAVA &&
centerGroundMaterial != Material.LAVA && centerGroundMaterial != Material.LAVA &&
northGroundMaterial != Material.LAVA && northGroundMaterial != Material.LAVA &&
southGroundMaterial != Material.LAVA && southGroundMaterial != Material.LAVA &&

View file

@ -10,7 +10,7 @@ import org.bukkit.ChatColor
import org.bukkit.command.CommandSender import org.bukkit.command.CommandSender
@CommandClass( @CommandClass(
path = "primerestart", modOnly = true, helpText = ["§6---- Prime restart ----", // path = "primerestart", modOnly = true, helpText = ["Prime restart", //
"Restarts the server as soon as nobody is online.", // "Restarts the server as soon as nobody is online.", //
"To be loud, type something after, like /primerestart lol (it doesn't matter what you write)", // "To be loud, type something after, like /primerestart lol (it doesn't matter what you write)", //
"To be silent, don't type anything" // "To be silent, don't type anything" //
@ -23,7 +23,7 @@ class PrimeRestartCommand : ICommand2MC() {
val component = component as RestartComponent val component = component as RestartComponent
component.isLoud = isLoud component.isLoud = isLoud
if (Bukkit.getOnlinePlayers().isNotEmpty()) { if (Bukkit.getOnlinePlayers().isNotEmpty()) {
sender.sendMessage("§bPlayers online, restart delayed.") sender.sendMessage("${ChatColor.AQUA}Players online, restart delayed.")
if (isLoud) SendSystemMessage( if (isLoud) SendSystemMessage(
Channel.globalChat, Channel.globalChat,
Channel.RecipientTestResult.ALL, Channel.RecipientTestResult.ALL,
@ -32,7 +32,7 @@ class PrimeRestartCommand : ICommand2MC() {
) )
component.isPlsrestart = true component.isPlsrestart = true
} else { } else {
sender.sendMessage("§bNobody is online. Restarting now.") sender.sendMessage("${ChatColor.AQUA}Nobody is online. Restarting now.")
if (isLoud) SendSystemMessage( if (isLoud) SendSystemMessage(
Channel.globalChat, Channel.globalChat,
Channel.RecipientTestResult.ALL, Channel.RecipientTestResult.ALL,

View file

@ -78,7 +78,7 @@ class RestartComponent : Component<MainPlugin>(), Listener {
if (isLoud) TBMCChatAPI.SendSystemMessage( if (isLoud) TBMCChatAPI.SendSystemMessage(
Channel.globalChat, Channel.globalChat,
Channel.RecipientTestResult.ALL, Channel.RecipientTestResult.ALL,
"§cNobody is online anymore. Restarting.", "${ChatColor.RED}Nobody is online anymore. Restarting.",
restartBroadcast restartBroadcast
) )
Bukkit.spigot().restart() Bukkit.spigot().restart()

View file

@ -9,6 +9,7 @@ import buttondevteam.lib.chat.CommandClass
import buttondevteam.lib.chat.ICommand2MC import buttondevteam.lib.chat.ICommand2MC
import buttondevteam.lib.chat.TBMCChatAPI.SendSystemMessage import buttondevteam.lib.chat.TBMCChatAPI.SendSystemMessage
import org.bukkit.Bukkit import org.bukkit.Bukkit
import org.bukkit.ChatColor
import org.bukkit.boss.BarColor import org.bukkit.boss.BarColor
import org.bukkit.boss.BarFlag import org.bukkit.boss.BarFlag
import org.bukkit.boss.BarStyle import org.bukkit.boss.BarStyle
@ -40,7 +41,7 @@ class ScheduledRestartCommand : ICommand2MC() {
private fun restart(sender: CommandSender, seconds: Int): Boolean { private fun restart(sender: CommandSender, seconds: Int): Boolean {
if (seconds < 10) { if (seconds < 10) {
sender.sendMessage("§cError: Seconds must be at least 10.") sender.sendMessage("${ChatColor.RED}Error: Seconds must be at least 10.")
return false return false
} }
restartCounter = seconds * 20 restartCounter = seconds * 20
@ -65,7 +66,7 @@ class ScheduledRestartCommand : ICommand2MC() {
if (restartCounter % 200 == 0 && Bukkit.getOnlinePlayers().isNotEmpty()) SendSystemMessage( if (restartCounter % 200 == 0 && Bukkit.getOnlinePlayers().isNotEmpty()) SendSystemMessage(
Channel.globalChat, Channel.globalChat,
Channel.RecipientTestResult.ALL, Channel.RecipientTestResult.ALL,
"§c-- The server is restarting in " + restartCounter / 20 + " seconds!", "${ChatColor.RED}-- The server is restarting in " + restartCounter / 20 + " seconds!",
(component as RestartComponent).restartBroadcast (component as RestartComponent).restartBroadcast
) )
restartBar.progress = restartCounter / restartInitialTicks.toDouble() restartBar.progress = restartCounter / restartInitialTicks.toDouble()

View file

@ -91,7 +91,7 @@ public class SpawnComponent extends Component<MainPlugin> implements PluginMessa
@Command2.Subcommand @Command2.Subcommand
public void def(Player player) { public void def(Player player) {
if (targetServer.get().length() == 0) { if (targetServer.get().length() == 0) {
player.sendMessage("§bTeleporting to spawn..."); player.sendMessage("${ChatColor.AQUA}Teleporting to spawn...");
try { try {
if (MainPlugin.ess != null) if (MainPlugin.ess != null)
MainPlugin.ess.getUser(player).getTeleport() MainPlugin.ess.getUser(player).getTeleport()
@ -99,7 +99,7 @@ public class SpawnComponent extends Component<MainPlugin> implements PluginMessa
else else
player.teleport(spawnloc); player.teleport(spawnloc);
} catch (Exception e) { } catch (Exception e) {
player.sendMessage("§cFailed to teleport: " + e); player.sendMessage("${ChatColor.RED}Failed to teleport: " + e);
} }
return; return;
} }

View file

@ -1,61 +1,53 @@
package buttondevteam.core.component.towny; package buttondevteam.core.component.towny
import buttondevteam.core.MainPlugin; import buttondevteam.core.MainPlugin
import buttondevteam.lib.chat.Command2; import buttondevteam.lib.chat.Command2.OptionalArg
import buttondevteam.lib.chat.CommandClass; import buttondevteam.lib.chat.Command2.Subcommand
import buttondevteam.lib.chat.CustomTabComplete; import buttondevteam.lib.chat.CommandClass
import buttondevteam.lib.chat.ICommand2MC; import buttondevteam.lib.chat.CustomTabComplete
import buttondevteam.lib.player.TBMCPlayer; import buttondevteam.lib.chat.ICommand2MC
import com.earth2me.essentials.Essentials; import com.palmergames.bukkit.towny.TownySettings
import com.earth2me.essentials.User; import com.palmergames.bukkit.towny.TownyUniverse
import com.palmergames.bukkit.towny.TownySettings; import com.palmergames.bukkit.towny.`object`.Resident
import com.palmergames.bukkit.towny.TownyUniverse; import org.bukkit.Bukkit
import com.palmergames.bukkit.towny.object.Resident; import org.bukkit.ChatColor
import com.palmergames.bukkit.towny.object.TownyObject; import org.bukkit.OfflinePlayer
import org.bukkit.Bukkit; import org.bukkit.command.CommandSender
import org.bukkit.OfflinePlayer; import java.util.*
import org.bukkit.command.CommandSender; import java.util.function.Consumer
import java.util.AbstractMap; @CommandClass(
import java.util.Map; path = "chroma remresidents",
import java.util.stream.Collectors; modOnly = true,
import java.util.stream.Stream; helpText = ["Removes invalid Towny residents from their towns (usually after a rename that didn't get caught by the plugin)", "If the delete eco account setting is off, then it will completely delete the resident", "(The economy account could still be used by the player)"]
)
@CommandClass(path = "chroma remresidents", modOnly = true, helpText = { class RemoveResidentsCommand : ICommand2MC() {
"Removes invalid Towny residents from their towns (usually after a rename that didn't get caught by the plugin)", @Subcommand
"If the delete eco account setting is off, then it will completely delete the resident", fun def(sender: CommandSender, @OptionalArg @CustomTabComplete("remove") remove: String?) {
"(The economy account could still be used by the player)" Bukkit.getScheduler().runTaskAsynchronously(plugin, Runnable {
}) sender.sendMessage("Starting...")
public class RemoveResidentsCommand extends ICommand2MC { val ds = TownyUniverse.getInstance().dataSource
@Command2.Subcommand val res: Map<Resident, OfflinePlayer> = ds.residents
public void def(CommandSender sender, @Command2.OptionalArg @CustomTabComplete("remove") String remove) { .mapNotNull { r ->
Bukkit.getScheduler().runTaskAsynchronously(getPlugin(), () -> { val player = MainPlugin.ess?.getOfflineUser(r.name)?.base ?: Bukkit.getOfflinePlayer(r.name)
sender.sendMessage("Starting..."); if (player.hasPlayedBefore()) null else r to player
var ds = TownyUniverse.getInstance().getDataSource(); }.associate { it }
var res = ds.getResidents().stream() if (MainPlugin.ess == null)
.flatMap(r -> { sender.sendMessage("${ChatColor.RED}Essentials not found, players who haven't joined after changing their names are also listed here.")
var st = Stream.of(r) //https://stackoverflow.com/questions/37299312/in-java-8-lambdas-how-to-access-original-object-in-the-stream sender.sendMessage("Residents to remove:")
.map(TownyObject::getName); res.values.forEach { op: OfflinePlayer -> sender.sendMessage(op.name) }
return (MainPlugin.ess == null if (TownySettings.isDeleteEcoAccount()) sender.sendMessage("${ChatColor.AQUA}Will only remove from town, as delete eco account setting is on") else sender.sendMessage(
? st.map(Bukkit::getOfflinePlayer) "${ChatColor.YELLOW}Will completely delete the resident, delete eco account setting is off"
: st.map(MainPlugin.ess::getOfflineUser).map(User::getBase)) )
.filter(p -> !p.hasPlayedBefore()) if (remove != null && remove.equals("remove", ignoreCase = true)) {
.map(p -> new AbstractMap.SimpleEntry<>(r, p)); sender.sendMessage("Removing residents...") //Removes from town and deletes town if needed - doesn't delete the resident if the setting is on
}).collect(Collectors.toMap(AbstractMap.SimpleEntry::getKey, AbstractMap.SimpleEntry::getValue)); //If it did, that could mean the player's economy is deleted too, unless this setting is false
if (MainPlugin.ess == null) res.keys.forEach(if (TownySettings.isDeleteEcoAccount())
sender.sendMessage("§cEssentials not found, players who haven't joined after changing their names are also listed here."); Consumer { resident -> ds.removeResident(resident) }
sender.sendMessage("Residents to remove:"); else
res.values().forEach(op -> sender.sendMessage(op.getName())); Consumer { resident -> ds.removeResidentList(resident) })
if (TownySettings.isDeleteEcoAccount()) sender.sendMessage("Done")
sender.sendMessage("§bWill only remove from town, as delete eco account setting is on"); }
else })
sender.sendMessage("§eWill completely delete the resident, delete eco account setting is off"); }
if (remove != null && remove.equalsIgnoreCase("remove")) { }
sender.sendMessage("Removing residents..."); //Removes from town and deletes town if needed - doesn't delete the resident if the setting is on
//If it did, that could mean the player's economy is deleted too, unless this setting is false
res.keySet().forEach(TownySettings.isDeleteEcoAccount() ? ds::removeResident : ds::removeResidentList);
sender.sendMessage("Done");
}
});
}
}

View file

@ -89,8 +89,8 @@ public class TBMCCoreAPI {
if (!devsOnline.isEmpty()) { if (!devsOnline.isEmpty()) {
DebugPotato potato = new DebugPotato() DebugPotato potato = new DebugPotato()
.setMessage(new String[]{ // .setMessage(new String[]{ //
"§b§o" + e.getClass().getSimpleName(), // "${ChatColor.AQUA}§o" + e.getClass().getSimpleName(), //
"§c§o" + sourcemsg, // "${ChatColor.RED}§o" + sourcemsg, //
"§a§oFind a dev to fix this issue"}) "§a§oFind a dev to fix this issue"})
.setType(e instanceof IOException ? "Throwable Potato" .setType(e instanceof IOException ? "Throwable Potato"
: e instanceof ClassCastException ? "Squished Potato" : e instanceof ClassCastException ? "Squished Potato"

View file

@ -308,13 +308,13 @@ abstract class Command2<TC : ICommand2<TP>, TP : Command2Sender>(
println("Should be running sync: $runOnPrimaryThread") println("Should be running sync: $runOnPrimaryThread")
/*if (!hasPermission(sender, sd.command, sd.method)) { /*if (!hasPermission(sender, sd.command, sd.method)) {
sender.sendMessage("§cYou don't have permission to use this command"); sender.sendMessage("${ChatColor.RED}You don't have permission to use this command");
return; return;
} }
// TODO: WIP // TODO: WIP
val type = sendertype.simpleName.fold("") { s, ch -> s + if (ch.isUpperCase()) " " + ch.lowercase() else ch } val type = sendertype.simpleName.fold("") { s, ch -> s + if (ch.isUpperCase()) " " + ch.lowercase() else ch }
sender.sendMessage("§cYou need to be a $type to use this command.") sender.sendMessage("${ChatColor.RED}You need to be a $type to use this command.")
sender.sendMessage(sd.getHelpText(sender)) //Send what the command is about, could be useful for commands like /member where some subcommands aren't player-only sender.sendMessage(sd.getHelpText(sender)) //Send what the command is about, could be useful for commands like /member where some subcommands aren't player-only
if (processSenderType(sender, sd, params, parameterTypes)) return; // Checks if the sender is the wrong type if (processSenderType(sender, sd, params, parameterTypes)) return; // Checks if the sender is the wrong type

View file

@ -23,6 +23,7 @@ import com.mojang.brigadier.tree.LiteralCommandNode
import me.lucko.commodore.Commodore import me.lucko.commodore.Commodore
import me.lucko.commodore.CommodoreProvider import me.lucko.commodore.CommodoreProvider
import org.bukkit.Bukkit import org.bukkit.Bukkit
import org.bukkit.ChatColor
import org.bukkit.Location import org.bukkit.Location
import org.bukkit.OfflinePlayer import org.bukkit.OfflinePlayer
import org.bukkit.command.* import org.bukkit.command.*
@ -113,7 +114,7 @@ class Command2MC : Command2<ICommand2MC, Command2MCSender>('/', true), Listener
errormsg: String, errormsg: String,
allSupplier: Supplier<Iterable<String>> allSupplier: Supplier<Iterable<String>>
) { ) {
super.addParamConverter(cl, converter, "§c$errormsg", allSupplier) super.addParamConverter(cl, converter, "${ChatColor.RED}$errormsg", allSupplier)
} }
override fun convertSenderType(sender: Command2MCSender, senderType: Class<*>): Any? { override fun convertSenderType(sender: Command2MCSender, senderType: Class<*>): Any? {
@ -160,7 +161,7 @@ class Command2MC : Command2<ICommand2MC, Command2MCSender>('/', true), Listener
} }
private var shouldRegisterOfficially = true private var shouldRegisterOfficially = true
private fun registerOfficially(command: ICommand2MC, node: LiteralCommandNode<Command2MCSender>): Command? { private fun registerOfficially(command: ICommand2MC, node: CoreCommandNode<Command2MCSender, *>): Command? {
return if (!shouldRegisterOfficially) null else try { return if (!shouldRegisterOfficially) null else try {
val cmdmap = val cmdmap =
Bukkit.getServer().javaClass.getMethod("getCommandMap").invoke(Bukkit.getServer()) as SimpleCommandMap Bukkit.getServer().javaClass.getMethod("getCommandMap").invoke(Bukkit.getServer()) as SimpleCommandMap
@ -169,8 +170,8 @@ class Command2MC : Command2<ICommand2MC, Command2MCSender>('/', true), Listener
val mainPath = path.substring(0, if (x == -1) path.length else x) val mainPath = path.substring(0, if (x == -1) path.length else x)
val bukkitCommand: Command val bukkitCommand: Command
//Commands conflicting with Essentials have to be registered in plugin.yml //Commands conflicting with Essentials have to be registered in plugin.yml
val oldcmd = //The label with the fallback prefix is always registered
cmdmap.getCommand(command.plugin.name + ":" + mainPath) //The label with the fallback prefix is always registered val oldcmd = cmdmap.getCommand("${command.plugin.name}:$mainPath")
if (oldcmd == null) { if (oldcmd == null) {
bukkitCommand = BukkitCommand(mainPath) bukkitCommand = BukkitCommand(mainPath)
cmdmap.register(command.plugin.name, bukkitCommand) cmdmap.register(command.plugin.name, bukkitCommand)
@ -198,7 +199,7 @@ class Command2MC : Command2<ICommand2MC, Command2MCSender>('/', true), Listener
Throwable("No Chroma user found"), Throwable("No Chroma user found"),
MainPlugin.instance MainPlugin.instance
) )
sender.sendMessage("§cAn internal error occurred.") sender.sendMessage("${ChatColor.RED}An internal error occurred.")
return true return true
} }
///trim(): remove space if there are no args ///trim(): remove space if there are no args
@ -246,22 +247,6 @@ class Command2MC : Command2<ICommand2MC, Command2MCSender>('/', true), Listener
commodore commodore
} }
private fun appendSubcommand(
path: String, parent: CommandNode<Any>,
subcommand: SubcommandData<ICommand2MC>?
): LiteralCommandNode<Any> {
var scmd: LiteralCommandNode<Any>
if (parent.getChild(path) as LiteralCommandNode<kotlin.Any?>?. also { scmd = it } != null) return scmd
val scmdBuilder = LiteralArgumentBuilder.literal<Any>(path)
if (subcommand != null) scmdBuilder.requires { o: Any? ->
val sender = commodore.getBukkitSender(o)
subcommand.hasPermission(sender)
}
scmd = scmdBuilder.build()
parent.addChild(scmd)
return scmd
}
fun registerTabcomplete( fun registerTabcomplete(
command2MC: ICommand2MC, command2MC: ICommand2MC,
commandNode: LiteralCommandNode<Command2MCSender>, commandNode: LiteralCommandNode<Command2MCSender>,

View file

@ -11,8 +11,8 @@ import buttondevteam.lib.TBMCChatPreprocessEvent
import buttondevteam.lib.TBMCSystemChatEvent import buttondevteam.lib.TBMCSystemChatEvent
import buttondevteam.lib.TBMCSystemChatEvent.BroadcastTarget import buttondevteam.lib.TBMCSystemChatEvent.BroadcastTarget
import org.bukkit.Bukkit import org.bukkit.Bukkit
import org.bukkit.ChatColor
import org.bukkit.command.CommandSender import org.bukkit.command.CommandSender
import java.util.*
import java.util.function.Supplier import java.util.function.Supplier
object TBMCChatAPI { object TBMCChatAPI {
@ -24,20 +24,13 @@ object TBMCChatAPI {
* @param channel The MC channel to send in * @param channel The MC channel to send in
* @return The event cancelled state * @return The event cancelled state
*/ */
/**
* Sends a chat message to Minecraft. Make sure that the channel is registered with [.RegisterChatChannel].<br></br>
* This will also send the error message to the sender, if they can't send the message.
*
* @param cm The message to send
* @return The event cancelled state
*/
@JvmOverloads @JvmOverloads
fun sendChatMessage(cm: ChatMessage, channel: Channel = cm.user.channel.get()): Boolean { fun sendChatMessage(cm: ChatMessage, channel: Channel = cm.user.channel.get()): Boolean {
if (!channelList.contains(channel)) throw RuntimeException( if (!channelList.contains(channel)) throw RuntimeException(
"Channel " + channel.displayName.get() + " not registered!" "Channel " + channel.displayName.get() + " not registered!"
) )
if (!channel.isEnabled.get()) { if (!channel.isEnabled.get()) {
cm.sender.sendMessage("§cThe channel '" + channel.displayName.get() + "' is disabled!") cm.sender.sendMessage("${ChatColor.RED}The channel '${channel.displayName.get()}' is disabled!")
return true //Cancel sending if channel is disabled return true //Cancel sending if channel is disabled
} }
val task = Supplier { val task = Supplier {
@ -61,7 +54,7 @@ object TBMCChatAPI {
* @param channel The channel to send to * @param channel The channel to send to
* @param rtr The score&group to use to find the group - use [RecipientTestResult.ALL] if the channel doesn't have scores * @param rtr The score&group to use to find the group - use [RecipientTestResult.ALL] if the channel doesn't have scores
* @param message The message to send * @param message The message to send
* @param exceptions Platforms where this message shouldn't be sent (same as [ChatMessage.getOrigin] * @param exceptions Platforms where this message shouldn't be sent (same as [ChatMessage.origin]
* @return The event cancelled state * @return The event cancelled state
*/ */
@JvmStatic @JvmStatic
@ -82,12 +75,12 @@ object TBMCChatAPI {
private fun getScoreOrSendError(channel: Channel, sender: CommandSender): RecipientTestResult { private fun getScoreOrSendError(channel: Channel, sender: CommandSender): RecipientTestResult {
val result = channel.getRTR(sender) val result = channel.getRTR(sender)
if (result.errormessage != null) sender.sendMessage("§c" + result.errormessage) if (result.errormessage != null) sender.sendMessage("${ChatColor.RED}" + result.errormessage)
return result return result
} }
/** /**
* Register a chat channel. See [Channel.Channel] for details. * Register a chat channel. See [Channel] for details.
* *
* @param channel A new [Channel] to register * @param channel A new [Channel] to register
*/ */