My admin keeps saying i don't have permission when i actually do have permission?

  1. i’m trying to make the logs command work correctly allowing me to use it but it just throws lies lol

  2. some reason it keeps telling me when i try to use the “logs” command it keeps saying Permission denied even though i am the owner and clearly do have permission? i don’t understand what’s wrong

  3. i tried changing the execute function and the logs function multiple different ways and i’m just tired of it i’m pretty much giving up at this point cause i don’t know what to do anymore. i don’t see where the problem is coming from or why it’s even doing this i even make the LocalScript part better and work better and it still has the issue. the localscript is completely fine it’s this main script that the issue is coming from and i can’t figure out why or how. i even added error handling and there is nothing wrong?

local replicatedStorage = game:GetService("ReplicatedStorage")
local remoteEvent = replicatedStorage.ExecuteCMD

-- Table to store players with permission levels
local playerPermissions = {
	["jjphariss"] = "Owner", -- Replace with player usernames and their respective permission levels
	["Username2"] = "Admin",
	-- Add more usernames and permission levels as needed
}
local commandLogs = {}
-- Table to store command handlers
local commandHandlers = {}

-- Define permission levels and their associated commands
local permissionLevels = {
	Owner = {"kill", "noclip", "hello", "info", "fire", "cmds","admin", "kick", "ban","unban","logs"}, -- Owner can use all commands
	Admin = {"kill", "hello", "info"}, -- Admin can use these commands
	Moderator = {"hello", "info"}, -- Moderator can use these commands
}

-- Function to check if a player has permission to use a command
local function hasPermission(player, command)
	local permissionLevel = playerPermissions[player.Name]
	if permissionLevel then
		local allowedCommands = permissionLevels[permissionLevel]
		if allowedCommands then
			for _, allowedCommand in ipairs(allowedCommands) do
				if allowedCommand == command then
					return true
				end
			end
		end
	end
	return false
end

-- Function to execute a command
-- Modify the executeCommand function to log command usage
local function executeCommand(player, command, partialName)
	-- Check if the player has permission to use the command
	if not hasPermission(player, command) then
		-- Send a permission denied message to the client
		remoteEvent:FireClient(player, "Permission denied.")
		return
	end

	-- Log the executed command with player's name and timestamp
	local timestamp = os.time()
	table.insert(commandLogs, {
		Player = player.Name,
		Command = command,
		Timestamp = timestamp
	})

	-- Find and execute the command handler
	local handler = commandHandlers[command]
	if handler then
		-- Check if the handler expects a partialName argument
		if partialName and handler(player, partialName) or not partialName and handler(player) then
			-- Command executed successfully
		else
			-- Send an error message if the command handler returns false or nil
			remoteEvent:FireClient(player, "Error executing the command: " .. command)
		end
	else
		-- Send an error message for unknown commands
		remoteEvent:FireClient(player, "Unknown command: " .. command)
	end
end



-- Register a new command handler
function registerCommand(command, handler)
	commandHandlers[command] = handler
end

-- Function to find a player by partial name
local function findPlayerByPartialName(partialName)
	for _, player in ipairs(game.Players:GetPlayers()) do
		if player.Name:lower():match(partialName:lower()) then
			return player
		end
	end
	return nil
end


-- Register the "logs" command handler
-- Register the "logs" command handler with error handling
registerCommand("logs", function(player)
	-- Check if the player has permission to use the "logs" command
	if not hasPermission(player, "logs") then
		-- Send a permission denied message to the client
		remoteEvent:FireClient(player, "Permission denied.")
		return
	end

	-- Attempt to retrieve and send the global command history to the player
	local success, errorMessage = pcall(function()
		for _, log in ipairs(commandLogs) do
			local timestamp = os.date("%c", log.Timestamp)
			local message = string.format("[%s] %s used %s at %s", timestamp, log.Player, log.Command, timestamp)
			remoteEvent:FireClient(player, message)
		end
	end)

	-- Handle any potential errors
	if not success then
		-- Send an error message to the client with the error details
		remoteEvent:FireClient(player, "Error retrieving command history: " .. errorMessage)
	end
end)



-- kill command
registerCommand("kill", function(player, partialName)
	-- Find the target player by partial name
	local targetPlayer = findPlayerByPartialName(partialName)
	if targetPlayer then
		-- Destroy the target player's character
		local character = targetPlayer.Character
		if character then
			character:BreakJoints()
			remoteEvent:FireClient(player, "Successfully killed: " .. partialName)
		end
	else
		-- Send an error message if the target player is not found
		remoteEvent:FireClient(player, "Player not found: " .. partialName)
	end
end)

-- Table to store players who are in "NoClip" mode
local noclipPlayers = {}

-- Function to toggle NoClip mode for a player
local function toggleNoClip(player)
	if noclipPlayers[player] then
		-- Disable NoClip mode
		noclipPlayers[player] = nil
		player:LoadCharacter()
		remoteEvent:FireClient(player, "NoClip disabled.")
	else
		-- Enable NoClip mode
		noclipPlayers[player] = true
		local character = player.Character
		if character then
			-- Disable collisions for the player's character
			for _, object in ipairs(character:GetDescendants()) do
				if object:IsA("BasePart") then
					object.CanCollide = false
				end
			end
		end
		remoteEvent:FireClient(player, "NoClip enabled.")
	end
end


-- ...

-- ban command
registerCommand("ban", function(player, partialName)
	-- Check if the player has permission to use the command
	if not hasPermission(player, "ban") then
		-- Send a permission denied message to the client
		remoteEvent:FireClient(player, "Permission denied.")
		return
	end

	-- Find the target player by partial name
	local targetPlayer = findPlayerByPartialName(partialName)
	if targetPlayer then
		-- Record the ban time using os.time()
		local banTime = os.time()

		-- Generate a unique ban key for the target player
		local banKey = "ban_" .. targetPlayer.UserId

		-- Store the ban information in a data store with the unique key
		local dataStore = game:GetService("DataStoreService"):GetDataStore("banData")
		local success, error = pcall(function()
			dataStore:SetAsync(banKey, {
				Kicker = player.Name,
				BanTime = banTime
			})
		end)

		if not success then
			print("Error saving ban player data:", error)
		end

		-- Kick the target player from the game
		targetPlayer:Kick(":Staff Member: >" .. player.Name .. "< banned you from the game")
		remoteEvent:FireClient(player, "Successfully banned: " .. partialName)
	else
		-- Send an error message if the target player is not found
		remoteEvent:FireClient(player, "Player not found: " .. partialName)
	end
end)

-- unban command
registerCommand("unban", function(player, partialName)
	-- Check if the player has permission to use the command
	if not hasPermission(player, "unban") then
		-- Send a permission denied message to the client
		remoteEvent:FireClient(player, "Permission denied.")
		return
	end

	-- Convert the partialName (username) to a UserId
	local targetUserId = nil
	local success, errorMessage = pcall(function()
		targetUserId = game:GetService("Players"):GetUserIdFromNameAsync(partialName)
	end)

	if not success or not targetUserId then
		-- Send an error message if the username is not found
		remoteEvent:FireClient(player, "Error: Username not found or invalid.")
		return
	end

	-- Generate the ban key for the target player
	local banKey = "ban_" .. targetUserId

	-- Attempt to remove the ban information from the data store
	local dataStore = game:GetService("DataStoreService"):GetDataStore("banData")
	local removeSuccess, removeError = pcall(function()
		dataStore:RemoveAsync(banKey)
	end)

	if removeSuccess then
		-- Send a message indicating that the player has been unbanned
		remoteEvent:FireClient(player, "Successfully unbanned: " .. partialName)
	else
		-- Send an error message if there was an issue removing the ban information
		remoteEvent:FireClient(player, "Error while trying to unban: " .. removeError)
	end
end)




-- ...

-- Function to check if a player is banned
local function isPlayerBanned(player)
	local banKey = "ban_" .. player.UserId
	local dataStore = game:GetService("DataStoreService"):GetDataStore("banData")
	local success, data = pcall(function()
		return dataStore:GetAsync(banKey)
	end)
	return success and data
end

-- PlayerAdded event handler
game.Players.PlayerAdded:Connect(function(player)
	if isPlayerBanned(player) then
		-- The player is banned, get the ban timestamp
		local banKey = "ban_" .. player.UserId
		local dataStore = game:GetService("DataStoreService"):GetDataStore("banData")
		local success, data = pcall(function()
			return dataStore:GetAsync(banKey)
		end)

		if success and data then
			local kickerName = data.Kicker
			local banTime = os.date("%c", data.BanTime)
			player:Kick(":Staff Member: >" .. kickerName .. "< banned you from the game at " .. banTime)
		else
			print("Error retrieving ban record for", player.Name)
			player:Kick("You are banned from the game.")
		end
	end
end)

-- ...

-- ...


--admin command
registerCommand("admin", function(player, partialName)
	-- Check if the player has permission to use the command
	if not hasPermission(player, "admin") then
		-- Send a permission denied message to the client
		remoteEvent:FireClient(player, "Permission denied.")
		return
	end

	-- Find the target player by partial name
	local targetPlayer = findPlayerByPartialName(partialName)
	if targetPlayer then
		-- Grant admin rank to the target player
		playerPermissions[targetPlayer.Name] = "Admin"  -- Fixed this line to update the target player's permission level
		remoteEvent:FireClient(player, "Admin rank given to: " .. partialName)
		targetPlayer.PlayerGui.AdminUI.OpenClose.Visible = true
	else
		-- Send an error message if the target player is not found
		remoteEvent:FireClient(player, "Player not found: " .. partialName)
	end
end)

--kick command
registerCommand("kick", function(player, partialName)
	-- Check if the player has permission to use the command
	if not hasPermission(player, "kick") then
		-- Send a permission denied message to the client
		remoteEvent:FireClient(player, "Permission denied.")
		return
	end

	-- Find the target player by partial name
	local targetPlayer = findPlayerByPartialName(partialName)
	if targetPlayer then
		-- Kick the target player from the game
		targetPlayer:Kick(":Staff Member: >" .. player.Name .. "< kicked you from the game")
		remoteEvent:FireClient(player, "Successfully kicked: " .. partialName)
	else
		-- Send an error message if the target player is not found
		remoteEvent:FireClient(player, "Player not found: " .. partialName)
	end
end)

-- noclip command
registerCommand("noclip", function(player)
	-- Check if the player has permission to use the command
	if not hasPermission(player, "noclip") then
		-- Send a permission denied message to the client
		remoteEvent:FireClient(player, "Permission denied.")
		return
	end

	-- Toggle NoClip mode for the player
	toggleNoClip(player)
end)







-- Example command handler for "hello" command
registerCommand("hello", function(player)
	-- Send a message back to the client
	remoteEvent:FireClient(player, "Hello, player!")
end)

--fire command
registerCommand("fire", function(player, partialName)
	-- Send a message back to the client
	local targetPlayer = findPlayerByPartialName(partialName)
	if targetPlayer then
		-- Destroy the target player's character
		local character = targetPlayer.Character
		if character then
			--add fire
			local fire = Instance.new("Fire")
			fire.Color = Color3.new(math.random(), math.random(), math.random()) --change fire color
			fire.Size = 10
			fire.Parent = character.HumanoidRootPart
		end
	end
end)

-- Example command handler for "info" command
registerCommand("cmds", function(player)
	-- Construct a list of available commands based on the player's permission level
	local permissionLevel = playerPermissions[player.Name]
	local availableCommands = {}

	if permissionLevel then
		local allowedCommands = permissionLevels[permissionLevel]
		if allowedCommands then
			for _, command in ipairs(allowedCommands) do
				table.insert(availableCommands, command)
			end
		end
	end

	-- Send an info message back to the client with the list of available commands
	local message = "Available commands: " .. table.concat(availableCommands, ", ")
	remoteEvent:FireClient(player, message)
end)



-- Example command handler for "info" command
registerCommand("info", function(player)
	-- Send an info message back to the client
	remoteEvent:FireClient(player, "This is an info message.")
end)




-- Function to send a message to a target player using a TextBox in ScreenGui
local function sendMessageToPlayer(player, partialName, message)
	-- Find the target player by partial name
	local targetPlayer = findPlayerByPartialName(partialName)
	if targetPlayer then
		-- Get the player's PlayerGui
		local playerGui = targetPlayer:FindFirstChild("PlayerGui")
		if playerGui then
			-- Find the ScreenGui, Frame, and TextBox
			local screenGui = playerGui:FindFirstChild("MessageUI")
			local frame = screenGui:FindFirstChild("Frame")
			local textBox = frame:FindFirstChild("Message")

			if screenGui and frame and textBox then
				-- Show the ScreenGui and set the message in the TextBox
				frame.Visible = true
				textBox.Text = message
				remoteEvent:FireClient(player, "Message sent to " .. partialName)
			else
				-- Send an error message if the UI components are not found
				remoteEvent:FireClient(player, "Error: UI components not found for " .. partialName)
			end
		else
			-- Send an error message if PlayerGui is not found
			remoteEvent:FireClient(player, "Error: PlayerGui not found for " .. partialName)
		end
	else
		-- Send an error message if the target player is not found
		remoteEvent:FireClient(player, "Player not found: " .. partialName)
	end
end

-- Register the new command handler
registerCommand("message", function(player, partialName, message)
	-- Check if the player has permission to use the command
	if not hasPermission(player, "message") then
		-- Send a permission denied message to the client
		remoteEvent:FireClient(player, "Permission denied.")
		return
	end

	-- Call the sendMessageToPlayer function to send the message
	sendMessageToPlayer(player, partialName, message)
end)




-- Listen for commands from clients
remoteEvent.OnServerEvent:Connect(function(player, command, partialName)
	executeCommand(player, command, partialName)
end)
1 Like

Can you please add print statements on every input value. In your hasPermission command, add print after fetching every table value. Also share your input reading code (client sided).

I’d like to comment that you have to work more on code organisation. There are unnecessary comments everywhere; code is overcommented. Some logic can be reduced majorly and can be cleaned up.

Above code could just be reduced to:

local permissionLevels = {
	Owner = {"kill", "noclip", "hello", "info", "fire", "cmds","admin", "kick", "ban","unban","logs"}, -- Owner can use all commands
	Admin = {"kill", "hello", "info"}, -- Admin can use these commands
	Moderator = {"hello", "info"}, -- Moderator can use these commands
        [""] = {},
}

local function hasPermission(player, command)
    -- `not not` casts your value to boolean, but you can omit that with no functional difference.
    return not not table.find(command, permissionLevels[playerPermissions[player.Name] or ""]
end

Moreover, you should reorganize admin features in a module. Each function should go into a separate module and be loaded from there.

Alternatively, one module can be used to store all functions to be loaded.

It might help to add the print statement here and just make sure you are getting the values for player, command, and partialName you are expecting.

i did that and everything worked fine still, but the thing that is weird is i tried just removing everything that said “permission denied” to the output window screenUI and um some weird reason it still says Permission denied even though i removed it from the script completely? how is it even doing that? i even checked the local script here…??

btw here is the part i removed from the server script provided in post " if not hasPermission(player, “some command”) then
– Send a permission denied message to the client
remoteEvent:FireClient(player, “Permission denied.”)
return
end"

local textbox = frame.TextBox
local output = frame.Output
local remoteEvent = game.ReplicatedStorage.ExecuteCMD

-- Function to handle user input and send commands to the server
local function handleCommandInput()
	local input = textbox.Text
	if input ~= "" then
		local command, playerName = input:match("(%S+)%s+(%S+)")

		-- Check if a player name is provided, and adjust the command accordingly
		if command and playerName then
			-- Send the command and player name to the server using a RemoteEvent
			remoteEvent:FireServer(command, playerName)
		else
			-- If no player name is provided, send the command as is
			remoteEvent:FireServer(command)
		end

		-- Clear the textbox
		textbox.Text = ""
	end
end

-- Listen for the Enter key press
textbox.FocusLost:Connect(function(enterPressed)
	if enterPressed then
		handleCommandInput()
	end
end)

-- Function to display output messages
function displayOutput(message)
	output.Text = message
end

-- Listen for output messages from the server
remoteEvent.OnClientEvent:Connect(displayOutput)

also it still says permission denied even if the command didn’t exist, i even tried changing to say something else still not working. but i’m really confused on why when i removed that from the script entirely it still says permission denied??? i removed that why is it still saying it?

Please share the properties of the UI. I think you left it as “permission denied” there. Somehow it just doesn’t change.

i never changed the properties of the ui it’s set as default so there won’t be anything to show? i may just give up on it and try making a new one with different methods. also the output text says “output” it has nothing to say that says “permission denied” the output text is showing what was used basically. that text is basically blank with .text saying “output” thats all you’d see if i showed you lol

Did you do this already or no?

i did and nothing was wrong. but idk i’ll try again

ok maybe i did use it wrong lol but i think i figured out why now, the command Logs is expecting 3 parameters when it should just be 1 but problem is, i already tried making it 1 parameters before… but hmm least i know what the issue is so i can see what i can do now. but then again i figured that was the problem before. and i tried before. soooooo idk i may like said give it up and start from scratch again. this is just pathetic how it’s not working when it should. i rather just give it up cause it’s just not worth my time at this point.

i figured it out. finally made a better error handling and now i saw what the problem was for once. it’s cause it’s trying to pass other arguments even when the command didn’t need them.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.