Creating an Anti-Swear Listener

Feb 24, 2020
Creating an Anti-Swear Listener
  • Here is a snippet for creating a basic anti-swear plugin. First, create a config which contains a list of words to detect:
    Code (YAML):
    Blocked-Words:
    - badWord
    - certainlyNot
    - majorNoNo
    Once that's settled, use the following code (don't forget to register the event in your main class!):
    Code (Java):
    package example;

    import org.bukkit.ChatColor;
    import org.bukkit.entity.Player;
    import org.bukkit.event.EventHandler;
    import org.bukkit.event.Listener;
    import org.bukkit.event.player.AsyncPlayerChatEvent;

    public class AntiSwear implements Listener {

        @EventHandler // Listening for the event.
        public void onChat(AsyncPlayerChatEvent event) {
            // Called when a player sends a chat message.
            Player player = event.getPlayer(); // Getting the player who sent the message.
            String message = event.getMessage().toLowerCase(); // Getting the message, and making it lowercase.

            for(String blockedWord : getConfig().getStringList("Blocked-Words")) { // Looping through all the blocked words in the string list.
                if(message.contains(blockedWord.toLowerCase())) { // If the message contains one or more blocked word
                    player.sendMessage(ChatColor.RED + "Your message was cancelled because it had a blocked word in it!"); //  Inform the player their message couldn't go through.
                    event.setCancelled(true); // Cancel the message from being sent
                    break; // No need to continue checking
                }
            }
        }

    }
    Code (Kotlin):
    package your.package.name

    import org.bukkit.ChatColor
    import org.bukkit.entity.Player
    import org.bukkit.event.EventHandler
    import org.bukkit.event.Listener
    import org.bukkit.event.player.AsyncPlayerChatEvent

    class AntiSwear : Listener {

        @EventHandler // Listening for the event.
        fun onChat(event: AsyncPlayerChatEvent) {
            // When the event is called the code inside this will run.
            val player = event.player // Getting the player who sent the message.
            val message = event.message.toLowerCase() // Getting the message, and making it lowercase.

            for (blockedWords in config.getStringList("Blocked-Words")) { // Looping through all the blocked words in the string list.
                if (message.contains(blockedWords)) { // If the message contains one or more blocked word
                    player.sendMessage(ChatColor.RED.toString() + "Your message was cancelled because it had a blocked word in it!") // Tell the player their message was blocked.
                    event.isCancelled = true // Cancel the message from being sent
                }
            }
        }

    }
  • Loading...
  • Loading...