Search code examples
javaminecraftspigot

Cancelling an event spigot 1.19


I have written an event called JoinEvent that when an player joins the minecraft server it called. The event checks to see if the player is banned. If it is then it checks my mongodb database for the name to get the staff member and the reason then its meant to kick the member with my custom message but it fails to do so.
JoinEvent:

package xyz.foresthosting.testplugin.events;

import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import xyz.foresthosting.testplugin.TestPlugin;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;

import javax.print.Doc;

public class PlayerJoin implements Listener
{
    private final TestPlugin plugin;
    public PlayerJoin(TestPlugin plugin)
    {
        this.plugin = plugin;
    }

    @EventHandler
    public void onPlayerJoin(PlayerJoinEvent event)
    {
        Player player = event.getPlayer();
        if(!player.hasPlayedBefore()) {
            event.setJoinMessage(ChatColor.GREEN + "Welcome to the server " + player.getName() + "! We hope you enjoy your stay.");
        } else if(player.hasPlayedBefore()) {
            event.setJoinMessage(ChatColor.GREEN + "Welcome back to the server " + player.getName() + "!");
        } else if(player.isBanned()) {
            MongoClient mongoClient = new MongoClient("mongodb://admin:<nopasswordforyou>@185.209.223.136:2002");
            MongoDatabase database = mongoClient.getDatabase("test");
            MongoCollection<Document> collection = database.getCollection("bans");
            Document query = new Document("name", event.getPlayer());

            MongoCursor<Document> cursor = collection.find(query).projection(new Document("staff", 1).append("reason", 1)).iterator();
            while(cursor.hasNext()) {
                Document document = cursor.next();
                String staff = document.getString("staff");
                String reason = document.getString("reason");
                player.kickPlayer(ChatColor.RED + "You have been banned from this server!\nReason: " + reason + "\nStaff: " + staff);
            }
        }
    }
}

Solution

  • Your code is never reaching the statement where it is connecting to the Database.

    The first two if-Statements are blocking it, as one of them definitely gets executed, as they are the opposite of each other.

    To fix this, you would need to change the "else if" in front of the "player.isBanned()" to a normal if, so it gets separated from the other cases.