Datastore with username?

I am trying to make a ban datastore that takes in some value from an admin console GUI. The admin console is designed to ban players based off of their username. After digging around devforum, I noticed that datastores require a player’s predefined ID. More specificly:

player.UserId -- in my case its 609345911

My data store script (partial):

local DataStoreService = game:GetService("DataStoreService")
local BanDataStore = DataStoreService:GetDataStore("BanDataStore")

game.ReplicatedStorage.BanPlayer.OnServerEvent:Connect(function(player, username)
	BanDataStore:SetAsync(username.UserId, true)
end)

game.ReplicatedStorage.UnbanPlayer.OnServerEvent:Connect(function(player, username)
	BanDataStore:SetAsync(username.UserId, false)
end)

It currently throws an error because the username of that player is not indexed properly. I want to change my script to this:

local DataStoreService = game:GetService("DataStoreService")
local BanDataStore = DataStoreService:GetDataStore("BanDataStore")

game.ReplicatedStorage.BanPlayer.OnServerEvent:Connect(function(player, username)
	BanDataStore:SetAsync(game.Players[username.Name].UserId, true) -- notice: this line changed
end)

game.ReplicatedStorage.UnbanPlayer.OnServerEvent:Connect(function(player, username)
	BanDataStore:SetAsync(username.UserId, true)
end)

It also throws an error because the player that I am trying to ban is not in the game. Therefore, the server cannot find the specified username. Is there a way to ban with a username or does it have to be player ID? Second question: If I have to use player’s ID to ban them, how to I find some player’s ID? (ik that i can search their username up, but some usernames are obscure and will result in ###########)

1 Like

You can do the game.Players:GetNameFromUserIdAsync(userID) or game.Players:GetUserIdFromNameAsync(name)

(As expected the first one returns the name of the person that has that userID and the second gives the user ID for the person that has that name)

4 Likes

If you use the player username, they can change it and they will be unbanned.

1 Like

So If I do

game.Players:GetUserIdFromNameAsync(name)

It will give me the respective user ID? What happens if the player is not in my server?

It checks the user ID of the person with the respective username in the site therefore it checks at the website.

To be more specific,

local someoneUserId = game.Players:GetUserIdFromNameAsync("ROBLOX")
local someoneName = game.Players:GetNameFromUserIdAsync(1)
print(someoneUserId) --Prints the UserId of the user named ROBLOX
print(someoneName) --Prints the name of the person that has 1 as their userId

--If there are no players named ROBLOX or no players with 1 as user id it will return nil