-- Minetest: builtin/game/chat.lua
local S = core.get_translator("__builtin")
-- Helper function that implements search and replace without pattern matching
-- Returns the string and a boolean indicating whether or not the string was modified
local function safe_gsub(s, replace, with)
local i1, i2 = s:find(replace, 1, true)
if not i1 then
return s, false
end
return s:sub(1, i1 - 1) .. with .. s:sub(i2 + 1), true
end
--
-- Chat message formatter
--
-- Implemented in Lua to allow redefinition
function core.format_chat_message(name, message)
local error_str = "Invalid chat message format - missing %s"
local str = core.settings:get("chat_message_format")
local replaced
-- Name
str, replaced = safe_gsub(str, "@name", name)
if not replaced then
error(error_str:format("@name"), 2)
end
-- Timestamp
str = safe_gsub(str, "@timestamp", os.date("%H:%M:%S", os.time()))
-- Insert the message into the string only after finishing all other processing
str, replaced = safe_gsub(str, "@message", message)
if not replaced then
error(error_str:format("@message"), 2)
end
return str
end
--
-- Chat command handler
--
core.chatcommands = core.registered_chatcommands -- BACKWARDS COMPATIBILITY
local msg_time_threshold =
tonumber(core.settings:get("chatcommand_msg_time_threshold")) or 0.1
core.register_on_chat_message(function(name, message)
if message:sub(1,1) ~= "/" then
return
end
local cmd, param = string.match(message, "^/([^ ]+) *(.*)")
if not cmd then
core.chat_send_player(name, "-!- "..S("Empty command."))
return true
end
param = param or ""
-- Run core.registered_on_chatcommands callbacks.
if core.run_callbacks(core.registered_on_chatcommands, 5, name, cmd, param) then
return true
end
local cmd_def = core.registered_chatcommands[cmd]
if not cmd_def then
core.chat_send_player(name, "-!- "..S("Invalid command: @1", cmd))
return true
|