下面列出了怎么用org.bukkit.event.player.PlayerCommandPreprocessEvent的API类实例代码及写法,或者点击链接到github查看源代码。
@EventHandler(priority = EventPriority.MONITOR)
public void onPlayerCommandMonitor(PlayerCommandPreprocessEvent event) {
String message = event.getMessage();
String arguments = "";
String command = "";
if (!message.contains(" ")) {
command = message.replace("/", "");
} else {
command = message.substring(0, message.indexOf(" ")).replace("/", "");
arguments = message.substring(message.indexOf(" ") + 1, message.length());
}
if (command.equalsIgnoreCase("datapack") && (arguments.contains("enable") || arguments.contains("disable"))) {
if (GriefDefenderPlugin.getInstance().getTagProvider() != null) {
GriefDefenderPlugin.getInstance().getTagProvider().refresh();
}
}
}
@EventHandler(priority = EventPriority.LOWEST)
public void onCommandPreprocess(PlayerCommandPreprocessEvent e)
{
String cmd = e.getMessage().substring(1);
if(cmd.length() <= 0) return;
String[] unprocessedArgs = cmd.split(" ");
String label = unprocessedArgs[0];
String[] args = new String[unprocessedArgs.length - 1];
System.arraycopy(unprocessedArgs, 1, args, 0, args.length);
if(label.equalsIgnoreCase("cmapi"))
{
e.setCancelled(true);
command.onCommand(e.getPlayer(), null, label, args);
}
}
@EventHandler
public void onCommand(PlayerCommandPreprocessEvent e){
if (!e.getMessage().equalsIgnoreCase("/uhccore update")){
return;
}
e.setCancelled(true);
Player player = e.getPlayer();
GameManager gm = GameManager.getGameManager();
if (gm.getGameState() == GameState.PLAYING || gm.getGameState() == GameState.DEATHMATCH){
player.sendMessage(ChatColor.RED + "You can not update the plugin during games as it will restart your server.");
return;
}
player.sendMessage(ChatColor.GREEN + "Updating plugin ...");
try{
updatePlugin(true);
}catch (Exception ex){
player.sendMessage(ChatColor.RED + "Failed to update plugin, check console for more info.");
ex.printStackTrace();
}
}
@EventHandler
public void onPlayerCommand(PlayerCommandPreprocessEvent event) {
Player player = event.getPlayer();
Location location = player.getLocation();
Civilian civilian = CivilianManager.getInstance().getCivilian(player.getUniqueId());
long jailTime = ConfigManager.getInstance().getJailTime();
if (civilian.getLastJail() + jailTime < System.currentTimeMillis()) {
return;
}
long timeRemaining = civilian.getLastJail() + jailTime - System.currentTimeMillis();
Region region = RegionManager.getInstance().getRegionAt(location);
if (region == null || !region.getEffects().containsKey("jail")) {
return;
}
event.setCancelled(true);
player.sendMessage(Civs.getPrefix() + LocaleManager.getInstance().getTranslationWithPlaceholders(player,
"no-commands-in-jail").replace("$1", (int) (timeRemaining / 1000) + "s"));
}
public static void handleCommandEvent(@Nonnull Player ply, @Nonnull Chunk chunk, @Nonnull PlayerCommandPreprocessEvent e) {
if (e.isCancelled()) return;
// If the user is an admin, they can run any command.
if (Utils.hasAdmin(ply)) return;
// If the user has permission to edit within this chunk, they can use
// any command they have permissions to use.
if (getCanEdit(chunk, ply.getUniqueId())) return;
// Get the command from the message.
final String[] cmdAndArgs = e.getMessage()
.trim()
.substring(1)
.split(" ", 1);
// Length should never be >1 but it could be 0.
if (cmdAndArgs.length == 1) {
// Cancel the event if the blocked commands list contains this
// command.
if (config.getList("protection", "blockedCmds").contains(cmdAndArgs[0])) e.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.LOWEST)
public void onCmd(PlayerCommandPreprocessEvent e) {
String command = e.getMessage().toLowerCase();
List<String> blockedCmds = wild.getConfig().getStringList("BlockCommands");
if (TeleportTarget.cmdUsed.contains(e.getPlayer().getUniqueId())) {
for (String cmd : blockedCmds) {
if (command.contains(cmd)) {
e.getPlayer().sendMessage(ChatColor.translateAlternateColorCodes('&', wild.getConfig().getString("Blocked_Command_Message")));
e.setCancelled(true);
break;
}
}
}
if (e.getMessage().equalsIgnoreCase("/wild") && wild.getConfig().getBoolean("FBasics") && (wild.usageMode != UsageMode.COMMAND_ONLY && wild.usageMode != UsageMode.BOTH)) {
e.setCancelled(true);
CheckPerms check = new CheckPerms(wild);
Checks checks = new Checks(wild);
Player p = e.getPlayer();
if (!checks.world(p))
p.sendMessage(ChatColor.translateAlternateColorCodes('&', wild.getConfig().getString("WorldMsg")));
else
check.check(p,p.getWorld().getName());
}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerCommand(PlayerCommandPreprocessEvent event) {
String m = event.getMessage();
if(!GameManager.getInstance().isPlayerActive(event.getPlayer()) && !GameManager.getInstance().isPlayerInactive(event.getPlayer()) && !GameManager.getInstance().isSpectator(event.getPlayer()))
return;
if(m.equalsIgnoreCase("/list")){
event.getPlayer().sendMessage(
GameManager.getInstance().getStringList(
GameManager.getInstance().getPlayerGameId(event.getPlayer())));
return;
}
if(!SettingsManager.getInstance().getConfig().getBoolean("disallow-commands"))
return;
if(event.getPlayer().isOp() || event.getPlayer().hasPermission("sg.staff.nocmdblock"))
return;
else if(m.startsWith("/sg") || m.startsWith("/survivalgames")|| m.startsWith("/hg")||m.startsWith("/hungergames")||m.startsWith("/msg")){
return;
}
else if (SettingsManager.getInstance().getConfig().getStringList("cmdwhitelist").contains(m)) {
return;
}
event.setCancelled(true);
}
@EventHandler
public void onInteract(PlayerInteractAtEntityEvent event) {
if (event.getRightClicked() instanceof Player) {
Long last = lastTrigger.get(event.getPlayer().getUniqueId());
if (last != null && System.currentTimeMillis() < last + 5000L) return;
Player player = event.getPlayer();
Player interacted = (Player) event.getRightClicked();
String action = pl.getConfig().getString("action", "").toLowerCase();
if ((action.contains("sneak") || action.contains("crouch") || action.contains("shift"))
&& !player.isSneaking()) return;
if (action.contains("right")) {
event.setCancelled(true);
Bukkit.getPluginManager()
.callEvent(
new PlayerCommandPreprocessEvent(
event.getPlayer(), "/trade " + interacted.getName()));
lastTrigger.put(event.getPlayer().getUniqueId(), System.currentTimeMillis());
}
}
}
@EventHandler(ignoreCancelled = true)
public void onDamage(EntityDamageByEntityEvent event) {
if (event.getDamager() instanceof Player && event.getEntity() instanceof Player) {
Long last = lastTrigger.get(event.getEntity().getUniqueId());
if (last != null && System.currentTimeMillis() < last + 5000L) return;
Player player = (Player) event.getDamager();
Player interacted = (Player) event.getEntity();
String action = pl.getConfig().getString("action", "").toLowerCase();
if ((action.contains("sneak") || action.contains("crouch") || action.contains("shift"))
&& !player.isSneaking()) return;
if (action.contains("left")) {
event.setCancelled(true);
Bukkit.getPluginManager()
.callEvent(
new PlayerCommandPreprocessEvent(
(Player) event.getDamager(), "/trade " + interacted.getName()));
lastTrigger.put(event.getDamager().getUniqueId(), System.currentTimeMillis());
}
}
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onCommand(final PlayerCommandPreprocessEvent e) {
if (!CommandAction.VANISH_SELF.checkPermission(e.getPlayer(), superVanish)) return;
if (superVanish.getVanishStateMgr().isVanished(e.getPlayer().getUniqueId())) return;
String command = e.getMessage().toLowerCase(Locale.ENGLISH).split(" ")[0].replace("/", "")
.toLowerCase(Locale.ENGLISH);
if (command.split(":").length > 1) command = command.split(":")[1];
if (command.equals("supervanish") || command.equals("sv")
|| command.equals("v") || command.equals("vanish")) {
final User user = essentials.getUser(e.getPlayer());
if (user == null || !user.isAfk()) return;
user.setHidden(true);
preVanishHiddenPlayers.add(e.getPlayer().getUniqueId());
superVanish.getServer().getScheduler().runTaskLater(superVanish, new Runnable() {
@Override
public void run() {
if (preVanishHiddenPlayers.remove(e.getPlayer().getUniqueId())) {
user.setHidden(false);
}
}
}, 1);
}
}
@EventHandler(ignoreCancelled = true)
public void onCommandAnswer(PlayerCommandPreprocessEvent event) {
if (!event.getPlayer().equals(player))
return;
if (!event.getMessage().toLowerCase().startsWith("/betonquestanswer "))
return;
event.setCancelled(true);
String[] parts = event.getMessage().split(" ");
if (parts.length != 2)
return;
String hash = parts[1];
for (int j = 1; j <= hashes.size(); j++) {
if (hashes.get(j).equals(hash)) {
conv.sendMessage(answerFormat + options.get(j));
conv.passPlayerAnswer(j);
return;
}
}
}
/**
* Prevents teleporting when falling based on setting by stopping commands
*
* @param e - event
*/
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onPlayerTeleport(final PlayerCommandPreprocessEvent e) {
if (DEBUG) {
plugin.getLogger().info(e.getEventName());
}
if (!IslandGuard.inWorld(e.getPlayer()) || Settings.allowTeleportWhenFalling || e.getPlayer().isOp()
|| !e.getPlayer().getGameMode().equals(GameMode.SURVIVAL)
|| plugin.getPlayers().isInTeleport(e.getPlayer().getUniqueId())) {
return;
}
// Check commands
// plugin.getLogger().info("DEBUG: falling command: '" +
// e.getMessage().substring(1).toLowerCase() + "'");
if (isFalling(e.getPlayer().getUniqueId()) && (Settings.fallingCommandBlockList.contains("*") || Settings.fallingCommandBlockList.contains(e.getMessage().substring(1).toLowerCase()))) {
// Sorry you are going to die
Util.sendMessage(e.getPlayer(), plugin.myLocale(e.getPlayer().getUniqueId()).errorNoPermission);
Util.sendMessage(e.getPlayer(), plugin.myLocale(e.getPlayer().getUniqueId()).islandcannotTeleport);
e.setCancelled(true);
}
}
/**
* Prevents visitors from using commands on islands, like /spawner
* @param e - event
*/
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onVisitorCommand(final PlayerCommandPreprocessEvent e) {
if (DEBUG) {
plugin.getLogger().info("Visitor command " + e.getEventName() + ": " + e.getMessage());
}
if (!IslandGuard.inWorld(e.getPlayer()) || e.getPlayer().isOp()
|| VaultHelper.checkPerm(e.getPlayer(), Settings.PERMPREFIX + "mod.bypassprotect")
|| plugin.getGrid().locationIsOnIsland(e.getPlayer(), e.getPlayer().getLocation())) {
//plugin.getLogger().info("player is not in world or op etc.");
return;
}
// Check banned commands
//plugin.getLogger().info(Settings.visitorCommandBlockList.toString());
String[] args = e.getMessage().substring(1).toLowerCase().split(" ");
if (Settings.visitorCommandBlockList.contains(args[0])) {
Util.sendMessage(e.getPlayer(), ChatColor.RED + plugin.myLocale(e.getPlayer().getUniqueId()).islandProtected);
e.setCancelled(true);
}
}
@EventHandler
public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event) {
FileConfiguration spigot = YamlConfiguration.loadConfiguration(new File(Bukkit.getServer().getWorldContainer(), "spigot.yml"));
if (event.getMessage().equalsIgnoreCase("/reload") && event.getPlayer().hasPermission("bukkit.command.reload")) {
// Restarts server if server is set up for it.
if (spigot.getBoolean("settings.restart-on-crash")) {
Bukkit.getLogger().severe("[Carbon] Restarting server due to reload command!");
Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), "restart");
} else {
// Call to server shutdown on disable.
// Won't hurt if server already disables itself, but will prevent plugin unload/reload.
Bukkit.getLogger().severe("[Carbon] Stopping server due to reload command!");
Bukkit.shutdown();
}
}
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onCommand(PlayerCommandPreprocessEvent event) {
if (ChestCommands.getSettings().use_only_commands_without_args && event.getMessage().contains(" ")) {
return;
}
// Very fast method compared to split & substring
String command = StringUtils.getCleanCommand(event.getMessage());
if (command.isEmpty()) {
return;
}
ExtendedIconMenu menu = ChestCommands.getCommandToMenuMap().get(command);
if (menu != null) {
event.setCancelled(true);
if (event.getPlayer().hasPermission(menu.getPermission())) {
menu.open(event.getPlayer());
} else {
menu.sendNoPermissionMessage(event.getPlayer());
}
}
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST)
public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event) {
String cmd = event.getMessage().split(" ")[0].toLowerCase();
if (settings.getProperty(HooksSettings.USE_ESSENTIALS_MOTD) && "/motd".equals(cmd)) {
return;
}
if (settings.getProperty(RestrictionSettings.ALLOW_COMMANDS).contains(cmd)) {
return;
}
final Player player = event.getPlayer();
if (!quickCommandsProtectionManager.isAllowed(player.getName())) {
event.setCancelled(true);
player.kickPlayer(messages.retrieveSingle(player, MessageKey.QUICK_COMMAND_PROTECTION_KICK));
return;
}
if (listenerService.shouldCancelEvent(player)) {
event.setCancelled(true);
messages.send(player, MessageKey.DENIED_COMMAND);
}
}
@Test
public void shouldNotCancelEventForAuthenticatedPlayer() {
// given
given(settings.getProperty(HooksSettings.USE_ESSENTIALS_MOTD)).willReturn(false);
given(settings.getProperty(RestrictionSettings.ALLOW_COMMANDS)).willReturn(Collections.emptySet());
Player player = playerWithMockedServer();
// PlayerCommandPreprocessEvent#getPlayer is final, so create a spy instead of a mock
PlayerCommandPreprocessEvent event = spy(new PlayerCommandPreprocessEvent(player, "/hub"));
given(listenerService.shouldCancelEvent(player)).willReturn(false);
given(quickCommandsProtectionManager.isAllowed(player.getName())).willReturn(true);
// when
listener.onPlayerCommandPreprocess(event);
// then
verify(event).getMessage();
verifyNoMoreInteractions(event);
verify(listenerService).shouldCancelEvent(player);
verifyNoInteractions(messages);
}
@Test
public void shouldCancelCommandEvent() {
// given
given(settings.getProperty(HooksSettings.USE_ESSENTIALS_MOTD)).willReturn(false);
given(settings.getProperty(RestrictionSettings.ALLOW_COMMANDS)).willReturn(newHashSet("/spawn", "/help"));
Player player = playerWithMockedServer();
PlayerCommandPreprocessEvent event = spy(new PlayerCommandPreprocessEvent(player, "/hub"));
given(listenerService.shouldCancelEvent(player)).willReturn(true);
given(quickCommandsProtectionManager.isAllowed(player.getName())).willReturn(true);
// when
listener.onPlayerCommandPreprocess(event);
// then
verify(listenerService).shouldCancelEvent(player);
verify(event).setCancelled(true);
verify(messages).send(player, MessageKey.DENIED_COMMAND);
}
@Test
public void shouldCancelFastCommandEvent() {
// given
given(settings.getProperty(HooksSettings.USE_ESSENTIALS_MOTD)).willReturn(false);
given(settings.getProperty(RestrictionSettings.ALLOW_COMMANDS)).willReturn(newHashSet("/spawn", "/help"));
Player player = playerWithMockedServer();
PlayerCommandPreprocessEvent event = spy(new PlayerCommandPreprocessEvent(player, "/hub"));
given(quickCommandsProtectionManager.isAllowed(player.getName())).willReturn(false);
// when
listener.onPlayerCommandPreprocess(event);
// then
verify(event).setCancelled(true);
verify(player).kickPlayer(messages.retrieveSingle(player, MessageKey.QUICK_COMMAND_PROTECTION_KICK));
}
@EventHandler
void onPlayerCommand(PlayerCommandPreprocessEvent event) {
if (event.isCancelled() || commandService.isRegistered()) return;
val player = context.getPlayer();
val result = commandExecutor.execute(event.getMessage().substring(1).split(" "));
event.setCancelled(result.isExists());
result.getOutput().forEach(player::sendMessage);
}
@Test
public void shouldDelegatePlayerCommandToExecutorWithContext() {
PlayerCommandPreprocessEvent event = new PlayerCommandPreprocessEvent(player, "/say hello", new HashSet<>());
commandInterceptor.onPlayerCommand(event);
assertTrue(event.isCancelled());
verify(commandExecutor).execute("say", "hello");
verify(player).sendMessage("message1");
verify(player).sendMessage("message2");
}
@Test
public void shouldNotDelegatePlayerCommandIfAlreadyRegistered() {
when(commandService.isRegistered()).thenReturn(true);
PlayerCommandPreprocessEvent event = new PlayerCommandPreprocessEvent(player, "/say hello", new HashSet<>());
commandInterceptor.onPlayerCommand(event);
verify(commandExecutor, never()).execute(any());
}
@EventHandler(priority = EventPriority.HIGH)
public void onPlayerCommand(final PlayerCommandPreprocessEvent event) {
if (freeze.isFrozen(event.getPlayer()) && !event.getPlayer().hasPermission(Permissions.STAFF)) {
boolean allow =
ALLOWED_CMDS.stream()
.filter(cmd -> event.getMessage().startsWith(cmd))
.findAny()
.isPresent();
if (!allow) {
// Don't allow commands except for those related to chat.
event.setCancelled(true);
}
}
}
@EventHandler
public void a(PlayerCommandPreprocessEvent e) {
if (Shared.disabled) return;
if (Configs.bukkitBridgeMode) return;
ITabPlayer sender = Shared.getPlayer(e.getPlayer().getUniqueId());
if (sender == null) return;
if (e.getMessage().equalsIgnoreCase("/tab") || e.getMessage().equalsIgnoreCase("/tab:tab")) {
Shared.sendPluginInfo(sender);
return;
}
for (CommandListener listener : Shared.commandListeners) {
if (listener.onCommand(sender, e.getMessage())) e.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onCommand(PlayerCommandPreprocessEvent e) {
Player p = e.getPlayer();
String[] cmd = e.getMessage().substring(1).split(" ");
if (cmd.length > 0) {
for (int i = 0; i < cmd.length; i++) {
String[] read = read(cmd, i);
String command = read[0];
String[] args = ArrayUtils.remove(read, 0);
Menu menu = TrMenuAPI.getMenuByCommand(command);
if (menu != null) {
if (menu.isTransferArgs()) {
if (args.length < menu.getForceTransferArgsAmount()) {
TLocale.sendTo(p, "MENU.NOT-ENOUGH-ARGS", menu.getForceTransferArgsAmount());
e.setCancelled(true);
return;
}
} else if (args.length > 0) {
return;
}
menu.open(p, args);
e.setCancelled(true);
break;
}
}
}
}
@EventHandler //�������س��˵�¼��������ָ��
public void onPlayerCommand(PlayerCommandPreprocessEvent e) {
if( LoginManager.isLogin(e.getPlayer().getName()) )
return;
e.setCancelled(true);
if( e.getMessage().split(" ")[0].contains("login")
|| e.getMessage().split(" ")[0].contains("register") )
e.setCancelled(false);
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onCommand(@Nonnull PlayerCommandPreprocessEvent event) {
String label = event.getMessage().split(" ")[0].replace("/", "");
if (!commands.containsKey(label)) {
return;
}
if (commands.get(label).stream().noneMatch(phase -> phase.getGame().isPlaying(event.getPlayer().getUniqueId()))) {
event.setCancelled(true);
event.getPlayer().sendMessage("Unknown command. Type \"/help\" for help.");
}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onCommand(PlayerCommandPreprocessEvent event)
{
Player player = event.getPlayer();
UUID uuid = player.getUniqueId();
String command = event.getMessage().toLowerCase();
if(command.startsWith("/help staffplus") || command.startsWith("/help staff+"))
{
sendHelp(player);
event.setCancelled(true);
return;
}
if(options.blockedCommands.contains(command) && permission.hasOnly(player, options.permissionBlock))
{
message.send(player, messages.commandBlocked, messages.prefixGeneral);
event.setCancelled(true);
}else if(modeCoordinator.isInMode(uuid) && options.blockedModeCommands.contains(command))
{
message.send(player, messages.modeCommandBlocked, messages.prefixGeneral);
event.setCancelled(true);
}else if(freezeHandler.isFrozen(uuid) && (!options.modeFreezeChat || (freezeHandler.isLoggedOut(uuid)) && !command.startsWith("/" + options.commandLogin)))
{
message.send(player, messages.chatPrevented, messages.prefixGeneral);
event.setCancelled(true);
}
}
/**
* Auto command listener
*/
@EventHandler
public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event) {
if (!event.isCancelled()) {
String result = super.onPlayerCommandPreprocess(new BukkitUser(plugin, event.getPlayer()), event.getMessage());
if (result != null) {
event.setMessage(result);
}
}
}
@Override
public boolean init(final Expression<?>[] exprs, final int matchedPattern, final Kleenean isDelayed, final ParseResult parseResult) {
what = matchedPattern;
if (!ScriptLoader.isCurrentEvent(PlayerCommandPreprocessEvent.class, ServerCommandEvent.class)) {
if (what != ARGS) // ExprArgument has the same syntax
Skript.error("The 'command' expression can only be used in a command event");
return false;
}
return true;
}