此示例展示如何在文本输入字段上实现每分钟限制1条的速率限制,该字段允许玩家在社区公告板上发布备注。
将以下内容添加到 Script 中的 ServerScriptService:
Server
local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
-- 创建用于通信的 RemoteEvent
local postNoteEvent = Instance.new("RemoteEvent")
postNoteEvent.Name = "PostNoteEvent"
postNoteEvent.Parent = ReplicatedStorage
-- 每位玩家每分钟仅允许发布一条备注的速率限制
local COOLDOWN_TIME = 60 -- 时间(以秒为单位)
local lastPostTime = {}
local function canPlayerPost(player)
local userId = player.UserId
local currentTime = tick()
if lastPostTime[userId] then
local timeSinceLastPost = currentTime - lastPostTime[userId]
if timeSinceLastPost < COOLDOWN_TIME then
return false, COOLDOWN_TIME - timeSinceLastPost
end
end
return true, 0
end
-- 处理带速率限制和文本过滤的发布请求
postNoteEvent.OnServerEvent:Connect(function(player, noteData)
local canPost, cooldown = canPlayerPost(player)
if not canPost then
postNoteEvent:FireClient(player, "冷却中", math.ceil(cooldown))
return
end
-- 所有公开分享的文本都必须经过文本过滤
local filterResult = getFilterResult(noteData.text, player.UserId)
if filterResult then
local success, filteredText = pcall(function()
return filterResult:GetNonChatStringForBroadcastAsync()
end)
if success then
-- 创建备注
local note = {
text = filteredText
}
-- 更新最后发布的时间
lastPostTime[player.UserId] = tick()
-- 发送成功响应
postNoteEvent:FireClient(player, "成功", note)
-- 向所有玩家广播新备注
postNoteEvent:FireAllClients("新备注", note)
else
warn("过滤文本时出错!")
end
end)
-- 玩家离开时进行清理
Players.PlayerRemoving:Connect(function(player)
lastPostTime[player.UserId] = nil
end)