這個示例展示了如何在文本輸入字段上實施每分鐘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, "cooldown", 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, "success", note)
-- 向所有玩家廣播新備忘錄
postNoteEvent:FireAllClients("newNote", note)
else
warn("過濾文本時出錯!")
end
end)
-- 玩家離開時進行清理
Players.PlayerRemoving:Connect(function(player)
lastPostTime[player.UserId] = nil
end)