How can I make this work for only players that have a badge?

I’m trying to make admin commands work with only players with a certain badge. Can someone help me? I’m not good at scripting. (The top is fine I just need help with the bottom.)

BadgeId = 7941246

function onChatted(msg, speaker)
	local source = string.lower(speaker.Name)
	msg = string.lower(msg)
	if msg == "!respawn" then
		speaker:LoadCharacter()
	elseif msg == "!sparkles" then
		Instance.new("Sparkles", speaker.Character.HumanoidRootPart)
	elseif msg == "!ff" then
		Instance.new("ForceField", speaker.Character)
	elseif msg == "!run" then
		speaker.Character.Humanoid.WalkSpeed = 25
	elseif msg == "!walk" then
		speaker.Character.Humanoid.WalkSpeed = 16
	elseif msg == "!sit" then
		speaker.Character.Humanoid.Sit = true
	end
end

game.Players.PlayerAdded:connect(function(player)
	game:GetService("Players").PlayerAdded:Connect(function(player)
		if BadgeService:UserHasBadge(player.UserId, BadgeId) then
			player.Chatted:connect(function(msg) onChatted(msg, player) end)
		end
	end)
end
game.Players.PlayerAdded:connect(function(player)
		if BadgeService:UserHasBadge(player.UserId, BadgeId) then
			player.Chatted:Connect(onChatted(msg, player))
		end
end)
  • Do not include the function(msg) nor the end) if you already defined a function.

You are connecting the PlayerAdded signal twice. This should work:

game:GetService("Players").PlayerAdded:Connect(function(player)
	if BadgeService:UserHasBadge(player.UserId, BadgeId) then
		player.Chatted:Connect(onChatted(msg, player))
	end
end)