How to detect an aliases of a player name?

Hey developers, I have been making a kick command, and I wanted it so that you could only type the first 3, or 4 letters of the name, and the script would detect the rest.

Here is the script.

local kick = '-kick '
game.Players.PlayerAdded:Connect(function(plr)
	plr.Chatted:Connect(function(chat)
		if string.sub(chat, 1, string.len(kick)) == kick then
			local target = string.sub(chat, string.len(kick), string.len(kick) + 4)
			local players = game.Players:GetChildren()
			
			for _, v in pairs(players) do
				if string.sub(v, 1, 4) == target then
					v:Kick()
				end
			end
		end
	end)
end)

I have got 1 error in the output on this line:
Error: invalid argument #1 to 'sub' (string expected, got Instance)
Line:

if string.sub(v, 1, 4) == target then

Any help, tips or suggestions would be greatly appreciated.
Thanks.

The v in the pairs loop is a Player instance, not a string. Simply do v.Name.

Works, but when I do -kick sele, it just prints ‘Player not found’ (because of the print if there is no player, not an error), any solutions?

You’re almost there!

Regarding your error, that’s because you need to use v.Name instead of just v. However, there’s another problem: What if multiple players match? For instance, if you chat “-kick crazy” and there’s a “crazyman32” and a “crazydude64” in the game, it would just kick the first one it finds. Ideally, it should only work if there’s a single match.

Another couple improvements: Use string.match instead, and also make it non-case-sensitive.

You could rewrite it like this:

local kick = "%-kick (.+)"
game.Players.PlayerAdded:Connect(function(plr)
	plr.Chatted:Connect(function(chat)
		chat = chat:lower()
		-- Check if chat matches "-kick NAME"
		local matchPlrName = chat:match(kick)
		if matchPlrName then
			-- Collect matched players:
			local players = game.Players:GetChildren()
			local matchedPlayers = {}
			for _,v in ipairs(players) do
				if v.Name:lower():sub(1, #matchPlrName) == matchPlrName then
					table.insert(matchedPlayers, v)
				end
			end
			-- Only kick if it matched on one player:
			if #matchedPlayers == 1 then
				matchedPlayers[1]:Kick()
			end
		end
	end)
end)

And of course, you’ll want to make sure that only certain players are allowed to run this command. To create a simple permissions list, you could use a table like this:

local admins = {
	[1372033462] = true; -- Your user ID
	[308165] = true; -- My user ID
}
game.Players.PlayerAdded:Connect(function(plr)
	if admins[plr.UserId] then
		plr.Chatted:Connect(function(chat)
			-- ... other code
		end)
	end
end)
2 Likes