I need help making a ban script

Hello! My name is F_xnn and I’m making a custom admin gui for my game:
02%20PM
Everything else works fine, but I can’t figure out how to make the ban script.
I want to make it using a textbox with a script similar to my kick script:

local TextBox = script.Parent.Parent.TextBox

script.parent.MouseButton1Click:Connect(function()

if game.Players[TextBox.Text] then

game.Players[TextBox.Text]:Kick()

end

end)

I just dont have any idea on how to do it. I’ve looked on YouTube and this forum but couldn’t find anything on it. If anyone could leave any suggestions or tips that would be very much appreciated!

Thanks in advance!

– F_xnn

18 Likes

To make a ban script, just save the player’s UserId with DataStoreService, and when a new player joins the server, check if they are on the ban list.

local function ban(player)
    player:Kick("You have been banned.")
    
    banEvent:FireServer(player) --On the server, save the player's UserId
end
6 Likes

I make a quick simple ban script, edit as please! :smiley:

--// Client
local TextBox = script.Parent.Parent.TextBox;
local banremote = game:GetService("ReplicatedStorage"):WaitForChild("Ban Remote");

script.parent.MouseButton1Click:Connect(function()
	if game.Players[TextBox.Text] then
		banremote:FireServer(game.Players[TextBox.Text]);
	end
end)
--// Server
local datastoreservice = game:GetService("DataStoreService");
local bandata = datastoreservice:GetDataStore("BanData");
local banremote = Instance.new("RemoteEvent");
banremote.Parent = game:GetService("ReplicatedStorage");
banremote.Name = "Ban Remote"; --// edit as you please

local admins = { --// Admin script, you can edit as pleased, as long as it is a table and has the userid!
	-1 --// Player1
	-2 --// Player2
}

local function getban(player)
	if bandata:GetAsync(player.UserId) then
		return true
	end
	return false
end

local function getadmins(player)
	for i,v in pairs(admins) do
		if v == player.UserId then
			return true
		end
	end
	return false
end

banremote.OnServerEvent:connect(function(player, user)
	if getadmins(player) then
		if not bandata:GetAsync(user.UserId) then
			bandata:SetAsync(user.UserId, true);
			user:kick("You have been banned!");
			print(user.Name .. " Was banned!");
		end
	else
		player:kick("Nice try bud.");
	end
end)

game:GetService("Players").PlayerAdded:Connect(function(player)
	if getban(player) then
		player:kick("You are banned from this game!");
		return
	end
end)

PS: DataStoreService can only be used in servers unless you allow it through your games page.

If you find any other errors than that @ me and I’ll help you.

If you don’t want to use this script then you can freely take it as an example :smiley:

EDIT: Performance updates to the server script, the error was admin script wasn’t working, hope you enjoy :smiley:

14 Likes

Edit 15th September 2024

Glitch does not allow you to keep your project online 24/7 anymore without paying. They will go out of their way to permanently suspend your project(s) for that.

You shouldn’t use the free database site I recommended in this post. You shouldn’t use any free database hosting for production. These free services are not reliable, can fail at any moment, and your data can be purged at any time without warning.

The Express.js code in this post is plain and unsecured. It is an example of how-to and should not be used in production without any changes.

I strongly recommend using Roblox’s Ban API unless you absolutely need to store the bans in an external database.


Making a Ban Script is not easy like making a Kick script because when you kick a player, you kick a player from the server but bans must be stored. There are many ways to do it, from a simple script to a database. It’s up to you.
You can use a Table to add the bans directly from Roblox Studio but the server needs a shutdown to update.
Here is an example:

-- Module Script

local Bans = {
["JakyeRU"] = "Exploiting!",
["Player"] = "Exploiting!",
["Player"] = "Exploiting!",
["Player"] = "Exploiting!",
["Player"] = "Exploiting!"
}

return Bans
-- Script

local Bans = require(game.ServerScriptService.ModuleScript)

game.Players.PlayerAdded:Connect(function(player)
	if Bans[player.Name] then
		player:Kick(Bans[player.Name])
	end
end)

image

Now, if you want to ban the players in-game and store the bans you have to use DataStoreService. You have an example above.

But, if you want to make a ban-system to update in ALL servers, you’ll have to use HttpService, a MySQL Database and a REST API. Here’s how to do it:

// Before anything make sure you have installed these packages. 
//(What is in require('packagename' is a package). 
//If not go to package.json in your project, click AddPackage and search for them.

const express = require('express')
const morgan = require('morgan')
const mysql = require('mysql')
const bodyParser = require('body-parser')
const app = express()
const keepalive = require('express-glitch-keepalive');
app.use(morgan('short'))
app.use(express.static('./public'))
app.use(bodyParser.urlencoded({extended: false}))
// ------------------------------------------------------------------------------------------------------------------------------------------------ //
app.use(keepalive);
app.get('/', (req, res) => {
res.json('Online');
});
app.get("/", (request, response) => {
response.sendStatus(200);
});
app.listen(process.env.PORT);

const connection =  mysql.createConnection({
        host: 'remotemysql.com',
        user: 'REPLACE THIS',
        password: 'REPLACE THIS',
        database: 'REPLACE THIS'
    })

app.get("/users/:username", (request, response) => {
    const queryString = "SELECT * FROM users WHERE username = ?"
    connection.query(queryString, [request.params.username], (error, rows, fields) => {
        if (error) {
            console.log("Failed to query for user! " + error)
            response.sendStatus(500)
            response.end()
            return
        }
        response.json(rows)
    })
})

Now, you have a REST API that is getting information from the MySQL Database for you.
If you access http://[projectname - replace].glitch.me/users/YourRobloxName and you get something like this:


Then you did everything correctly.
Now, try to insert something to test it.


Then it should look something like this.

Ignore the Moderator and ModeratorID. I am using a Discord Bot to add bans.

Congratulations! Now, we are going to the LUA part.
We are going to check if they are banned every time they join and every 30 seconds because of the HttpService limits. Make a Script inside of a Script. I know it’s not the best method but it works for me. In the first Script Write:

game.Players.PlayerAdded:Connect(function(player)
	local URL = "http://[CHANGE THIS].glitch.me/users/"..player.Name
	local ReceivedData = HttpService:GetAsync(URL)
	local Data = HttpService:JSONDecode(ReceivedData)
	
	if ReceivedData == "[]" then
		
	elseif
		Data[1].username == player.Name then
			player:Kick("You have been banned! | "..Data[1].reason)
	end
end)

In the second Script write:

local HttpService = game:GetService("HttpService")

game.Players.PlayerAdded:Connect(function(player)
	local URL = "http://[CHANGE THIS].glitch.me/users/"..player.Name
	
	while true do
		wait(30)
		local ReceivedData = HttpService:GetAsync(URL)
		local Data = HttpService:JSONDecode(ReceivedData)
		
		if ReceivedData == "[]" then
			
		elseif
			Data[1].username == player.Name then
				player:Kick("You have been banned! | "..Data[1].reason)
		end
	end
end)

That’s it!
Note: You can manually insert data in the Database or you can use Discord bots, for example, an HTML Form or anything else.

EDIT:
As you can see in the back-end code I did response.sendStatus(500). 500 means Internal Server Error
Here are all HTML Status Codes if you’re curious.

EDIT 2:
The Rest API unsecured. Secure it with a code that you know in the headers.

Mention me (@JakyeRU) if there is something wrong and I will fix it.

74 Likes

If you still need help other then what is here, I do have a open source admin panel found here if you want to take a look at our ban functions. Though I do plan on remaking it soon.

2 Likes

Slightly of topic but that kick script won’t work. You will need to use a RemoteEvent.

2 Likes

I would suggest using datastores for this. It will probably be the most reliable if glitch goes down or something. For my banlist I currently use the roblox datastores as well as messagingservice to communicate between each servers to update their ban list, and ofc update the datastore whenever a new person is banned/unbanned.

6 Likes

There are many ways to do this, and it’s up to you to use whichever you want. This is a walkthrough on the datastore way, so let’s begin.

First, let’s create a script in ServerScriptService and get the DataStoreService from the game. (You do not have to read the comments I put in if you are experienced at scripting.)

local DSS = game:GetService("DataStoreService")

Alright, now, let’s get a datastore from DataStoreService called “Bans” (you may change this at your own will)

local bansDataStore = DSS:GetDataStore("Bans")

Now, let’s stop a bit here and think;
What do we want the game to do with those 2 variables?

We want the game to check if a player is banned or not, EVERY SINGLE TIME they join the game. We can use PlayerAdded to do that. So, so far we got:

local DSS = game:GetService("DataStoreService")
local bansDataStore = DSS:GetDataStore("Bans")

game.Players.PlayerAdded:Connect(function(player)

end)

Now you might be saying: “This is not checking if a player is banned or not?”
That’s where GetAsync() comes in. Let’s add that to the script.

local DSS = game:GetService("DataStoreService")
local bansDataStore = DSS:GetDataStore("Bans")

game.Players.PlayerAdded:Connect(function(player)
bansDataStore:GetAsync("banstatus_"..player.UserId) -- You may change banstatus_ and player.UserId (limited) at your own will, but it is STRONGLY recommended to use UserIds in order to check for bans.
end)

But all we did here was to check if the value existed or not. That’s where we gotta use Kick().

Let’s use some logic first, if you don’t set any keys to a datastore, then the value is obviously going to be nil. Let’s make it, so that if the value is NOT nil, kick the player everytime they join.

And now we have:

local DSS = game:GetService("DataStoreService")
local bansDataStore = DSS:GetDataStore("Bans")

game.Players.PlayerAdded:Connect(function(player)
if bansDataStore:GetAsync("banstatus_"..player.UserId) then
player:Kick("put reason here") -- This'll be the kick reason for ALL PLAYERS that are banned, NOT individually.
end
end)

Wait! We aren’t done yet! We gotta use SetAsync() on your admin panel to actually ban the player, this is the most important part yet!

Alright, let’s calm down a little bit. THIS is our current script INSIDE THE ADMIN PANEL, right?

local TextBox = script.Parent.Parent.TextBox

script.parent.MouseButton1Click:Connect(function()

if game.Players[TextBox.Text] then

game.Players[TextBox.Text]:Kick()

end

end)

Wow, it actually wasn’t gonna be that hard I guess… we just have to add the same variables to this script, add SetAsync(), annnnd;

local DSS = game:GetService("DataStoreService")
local bansDataStore = DSS:GetDataStore("Bans")
local TextBox = script.Parent.Parent.TextBox

script.parent.MouseButton1Click:Connect(function()

if game.Players[TextBox.Text] then

local playertoban = game.Players[TextBox.Text] -- To specify the Player instance.
bansDataStore:SetAsync("banstatus_"..playertoban.UserId,1) -- Make sure the values inside this is the same within the ones inside the script we just made!

game.Players[TextBox.Text]:Kick()

end

end)

You can set the “1” to anything you want, because the game is not checking for a specific value, it only checks if the value is nil, or not.

And now, a very important note here: If you want to UNBAN the player, you gotta make an unban script and set the value to nil, you can also use RemoveAsync(), which is a much better option.

If you have been following this step-by-step (without changing anything), then you must know the player’s UserId in order to unban them. If you’re gonna put an unban section inside the same script, use this:

bansDataStore:RemoveAsync("banstatus_"..playertounban.UserId) -- Remember to set the playertounban using a variable!

But if you’re gonna use a seperate script, or just unban the player using the command bar, use this:

local DSS = game:GetService("DataStoreService")
local bansDataStore = DSS:GetDataStore("Bans")

bansDataStore:RemoveAsync("banstatus_"..playertounban.UserId) -- WARNING: If you are using the command bar in order to unban the player, you will need to specify the UserId yourself without using commas! If you are using a seperate script, you will have to set playertounban using a variable!
11 Likes

When I try to add some of these packages in Glitch, it ends up suspending my project for whatever reason

What packages do you have? This happened to me too, it was because I was using a package that would constantly keep Glitch up.

I made a tutorial that shows how to make a simple ban command/system! Check it out here!

express-glitch-keepalive is banned because it was used to keep projects from going to sleep. But now, you have to pay to keep it alive. But you don’t need that since it is a website. You will be alright.

A simple ban script I came up with is this. (It uses remotes)

local prefix, ds, banstore = "user_", game:GetService("DataStoreService"), ds:GetDataStore("Bans")

local plr = Player
local p = Mod
		local args = {}
		args.reason = "Reason here (Presumably sent with the remote)"
		args.plr = plr
		banStore:SetAsync(prefix.. tostring(plr.UserId), {
			true--[[if they are banned]]--, 
            args.msg--[[Reason]]--, 
            p.Name --[[Person who banned them]]---
		})
		plr:Kick('You have been banned by: '..p.Name..' for: '..args.msg)
	end

And Like wise with unban (same thing but I just skipped all of that other stuff)

		banStore:SetAsync(prefix.. tostring(pid), {
			false, "", ""
		})
		log(data)
	end

And then you need to check on join.

game.Players.PlayerAdded:Connect(function(plr)
local plrData = banStore:GetAsync(prefix.. tostring(plr.UserId) --Fetching data
if plrData[1] == true then 
--[[1 is the value that says if it is true or not]]--
Kick('You have been banned by: '..p.Name..' for: '..args.msg)
end)

And that’s a complete set for your ban. Put it in ServerScriptService or else it won’t work.

Good luck and happy scripting. :smiley:

3 Likes