How would you make a script that kicks afk players after a certain amount of time?

Hello! The title pretty much speaks for itself. Could anyone point me in the direction on how to detect when a player is afk, then kick them? Thanks a lot! (not asking for a full script, but just knowing where to begin would be nice!)

I have tried a few scripts from other dev forum posts, but none of them have worked for me. If anyone could help, that would be amazing!

WindowFocused is what you need.
Notice you’ll need a remote event, since you can only detect when a player is afk from the client.
And from there, you should kick them from the server if they’ve been afk for too long.

You could count the time from the moment they went afk.

local ReplicatedStorage = game:GetService("ReplicatedStorage")
local AfkEvent = ReplicatedStorage:FindFirstChild("AfkEvent")

local MaxTimeToBeAfk = 10
local Players = {}
local players = game:GetService("Players")
local initiate 

local function setAfk(player, afk)
	if afk then
		initiate = os.time()
		if not Players[player.Name] then
			Players[player.Name] = true	
			spawn(function()
				while Players[player.Name] do
					task.wait()
					if os.time() - 10 > initiate then
						player:Kick("Afk too long")
						break
					end
				end 
			end)
		end
		print(player.Name.." is AFK")
	else
		print(player.Name.." is Back")
		if  Players[player.Name] then
			initiate = os.time()
			Players[player.Name] = nil	
		end
	end
end

AfkEvent.OnServerEvent:Connect(setAfk)

players.PlayerRemoving:Connect(function(Player)
	if  Players[Player.Name] then
		Players[Player.Name] = nil	
	end
end)
-- LocalScript
local Players = game:GetService("Players")
local player = Players.LocalPlayer

local UserInputService = game:GetService("UserInputService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")

local AfkEvent = ReplicatedStorage:WaitForChild("AfkEvent")

local function focusGained()
	AfkEvent:FireServer(false)
end

local function focusReleased()
	AfkEvent:FireServer(true)
end

UserInputService.WindowFocused:Connect(focusGained)
UserInputService.WindowFocusReleased:Connect(focusReleased)

Something like this.
You might need to change it a little.

1 Like

Got it, I will certainly try that out! Thanks for the help!

Just wanted to mention that the local player can be kicked from the client.

LocalPlayer:Kick() --Valid in local scripts (the client can kick itself).
OtherPlayer:Kick() --Invalid in local scripts (the client can't kick other clients).
3 Likes

Right.

Tho I thought it would be “safer” to do that from server.

where do i put the scripts bro? Please help me.