1 -- Minetest: builtin/game/chat.lua
3 local S = core.get_translator("__builtin")
5 -- Helper function that implements search and replace without pattern matching
6 -- Returns the string and a boolean indicating whether or not the string was modified
7 local function safe_gsub(s, replace, with)
8 local i1, i2 = s:find(replace, 1, true)
13 return s:sub(1, i1 - 1) .. with .. s:sub(i2 + 1), true
17 -- Chat message formatter
20 -- Implemented in Lua to allow redefinition
21 function core.format_chat_message(name, message)
22 local error_str = "Invalid chat message format - missing %s"
23 local str = core.settings:get("chat_message_format")
27 str, replaced = safe_gsub(str, "@name", name)
29 error(error_str:format("@name"), 2)
33 str = safe_gsub(str, "@timestamp", os.date("%H:%M:%S", os.time()))
35 -- Insert the message into the string only after finishing all other processing
36 str, replaced = safe_gsub(str, "@message", message)
38 error(error_str:format("@message"), 2)
45 -- Chat command handler
48 core.chatcommands = core.registered_chatcommands -- BACKWARDS COMPATIBILITY
50 local msg_time_threshold =
51 tonumber(core.settings:get("chatcommand_msg_time_threshold")) or 0.1
52 core.register_on_chat_message(function(name, message)
53 if message:sub(1,1) ~= "/" then
57 local cmd, param = string.match(message, "^/([^ ]+) *(.*)")
59 core.chat_send_player(name, "-!- "..S("Empty command."))
65 -- Run core.registered_on_chatcommands callbacks.
66 if core.run_callbacks(core.registered_on_chatcommands, 5, name, cmd, param) then
70 local cmd_def = core.registered_chatcommands[cmd]
72 core.chat_send_player(name, "-!- "..S("Invalid command: @1", cmd))
75 local has_privs, missing_privs = core.check_player_privs(name, cmd_def.privs)
77 core.set_last_run_mod(cmd_def.mod_origin)
78 local t_before = core.get_us_time()
79 local success, result = cmd_def.func(name, param)
80 local delay = (core.get_us_time() - t_before) / 1000000
81 if success == false and result == nil then
82 core.chat_send_player(name, "-!- "..S("Invalid command usage."))
83 local help_def = core.registered_chatcommands["help"]
85 local _, helpmsg = help_def.func(name, cmd)
87 core.chat_send_player(name, helpmsg)
91 if delay > msg_time_threshold then
92 -- Show how much time it took to execute the command
94 result = result .. core.colorize("#f3d2ff", S(" (@1 s)",
95 string.format("%.5f", delay)))
97 result = core.colorize("#f3d2ff", S(
98 "Command execution took @1 s",
99 string.format("%.5f", delay)))
103 core.chat_send_player(name, result)
107 core.chat_send_player(name,
108 S("You don't have permission to run this command "
109 .. "(missing privileges: @1).",
110 table.concat(missing_privs, ", ")))
112 return true -- Handled chat message
115 if core.settings:get_bool("profiler.load") then
116 -- Run after register_chatcommand and its register_on_chat_message
117 -- Before any chatcommands that should be profiled
118 profiler.init_chatcommand()
121 -- Parses a "range" string in the format of "here (number)" or
122 -- "(x1, y1, z1) (x2, y2, z2)", returning two position vectors
123 local function parse_range_str(player_name, str)
125 local args = str:split(" ")
127 if args[1] == "here" then
128 p1, p2 = core.get_player_radius_area(player_name, tonumber(args[2]))
130 return false, S("Unable to get position of player @1.", player_name)
133 p1, p2 = core.string_to_area(str)
135 return false, S("Incorrect area format. "
136 .. "Expected: (x1,y1,z1) (x2,y2,z2)")
146 core.register_chatcommand("me", {
147 params = S("<action>"),
148 description = S("Show chat action (e.g., '/me orders a pizza' "
149 .. "displays '<player name> orders a pizza')"),
150 privs = {shout=true},
151 func = function(name, param)
152 core.chat_send_all("* " .. name .. " " .. param)
157 core.register_chatcommand("admin", {
158 description = S("Show the name of the server owner"),
159 func = function(name)
160 local admin = core.settings:get("name")
162 return true, S("The administrator of this server is @1.", admin)
164 return false, S("There's no administrator named "
165 .. "in the config file.")
170 local function privileges_of(name, privs)
172 privs = core.get_player_privs(name)
174 local privstr = core.privs_to_string(privs, ", ")
175 if privstr == "" then
176 return S("@1 does not have any privileges.", name)
178 return S("Privileges of @1: @2", name, privstr)
182 core.register_chatcommand("privs", {
183 params = S("[<name>]"),
184 description = S("Show privileges of yourself or another player"),
185 func = function(caller, param)
187 local name = (param ~= "" and param or caller)
188 if not core.player_exists(name) then
189 return false, S("Player @1 does not exist.", name)
191 return true, privileges_of(name)
195 core.register_chatcommand("haspriv", {
196 params = S("<privilege>"),
197 description = S("Return list of all online players with privilege"),
198 privs = {basic_privs = true},
199 func = function(caller, param)
202 return false, S("Invalid parameters (see /help haspriv).")
204 if not core.registered_privileges[param] then
205 return false, S("Unknown privilege!")
207 local privs = core.string_to_privs(param)
208 local players_with_priv = {}
209 for _, player in pairs(core.get_connected_players()) do
210 local player_name = player:get_player_name()
211 if core.check_player_privs(player_name, privs) then
212 table.insert(players_with_priv, player_name)
215 return true, S("Players online with the \"@1\" privilege: @2",
217 table.concat(players_with_priv, ", "))
221 local function handle_grant_command(caller, grantname, grantprivstr)
222 local caller_privs = core.get_player_privs(caller)
223 if not (caller_privs.privs or caller_privs.basic_privs) then
224 return false, S("Your privileges are insufficient.")
227 if not core.get_auth_handler().get_auth(grantname) then
228 return false, S("Player @1 does not exist.", grantname)
230 local grantprivs = core.string_to_privs(grantprivstr)
231 if grantprivstr == "all" then
232 grantprivs = core.registered_privileges
234 local privs = core.get_player_privs(grantname)
235 local privs_unknown = ""
237 core.string_to_privs(core.settings:get("basic_privs") or "interact,shout")
238 for priv, _ in pairs(grantprivs) do
239 if not basic_privs[priv] and not caller_privs.privs then
240 return false, S("Your privileges are insufficient. "..
241 "'@1' only allows you to grant: @2",
243 core.privs_to_string(basic_privs, ', '))
245 if not core.registered_privileges[priv] then
246 privs_unknown = privs_unknown .. S("Unknown privilege: @1", priv) .. "\n"
250 if privs_unknown ~= "" then
251 return false, privs_unknown
253 for priv, _ in pairs(grantprivs) do
254 -- call the on_grant callbacks
255 core.run_priv_callbacks(grantname, priv, caller, "grant")
257 core.set_player_privs(grantname, privs)
258 core.log("action", caller..' granted ('..core.privs_to_string(grantprivs, ', ')..') privileges to '..grantname)
259 if grantname ~= caller then
260 core.chat_send_player(grantname,
261 S("@1 granted you privileges: @2", caller,
262 core.privs_to_string(grantprivs, ', ')))
264 return true, privileges_of(grantname)
267 core.register_chatcommand("grant", {
268 params = S("<name> (<privilege> [, <privilege2> [<...>]] | all)"),
269 description = S("Give privileges to player"),
270 func = function(name, param)
271 local grantname, grantprivstr = string.match(param, "([^ ]+) (.+)")
272 if not grantname or not grantprivstr then
273 return false, S("Invalid parameters (see /help grant).")
275 return handle_grant_command(name, grantname, grantprivstr)
279 core.register_chatcommand("grantme", {
280 params = S("<privilege> [, <privilege2> [<...>]] | all"),
281 description = S("Grant privileges to yourself"),
282 func = function(name, param)
284 return false, S("Invalid parameters (see /help grantme).")
286 return handle_grant_command(name, name, param)
290 local function handle_revoke_command(caller, revokename, revokeprivstr)
291 local caller_privs = core.get_player_privs(caller)
292 if not (caller_privs.privs or caller_privs.basic_privs) then
293 return false, S("Your privileges are insufficient.")
296 if not core.get_auth_handler().get_auth(revokename) then
297 return false, S("Player @1 does not exist.", revokename)
300 local privs = core.get_player_privs(revokename)
302 local revokeprivs = core.string_to_privs(revokeprivstr)
303 local is_singleplayer = core.is_singleplayer()
304 local is_admin = not is_singleplayer
305 and revokename == core.settings:get("name")
307 if revokeprivstr == "all" then
311 for priv, _ in pairs(revokeprivs) do
316 local privs_unknown = ""
318 core.string_to_privs(core.settings:get("basic_privs") or "interact,shout")
319 local irrevokable = {}
320 local has_irrevokable_priv = false
321 for priv, _ in pairs(revokeprivs) do
322 if not basic_privs[priv] and not caller_privs.privs then
323 return false, S("Your privileges are insufficient. "..
324 "'@1' only allows you to revoke: @2",
326 core.privs_to_string(basic_privs, ', '))
328 local def = core.registered_privileges[priv]
330 privs_unknown = privs_unknown .. S("Unknown privilege: @1", priv) .. "\n"
331 elseif is_singleplayer and def.give_to_singleplayer then
332 irrevokable[priv] = true
333 elseif is_admin and def.give_to_admin then
334 irrevokable[priv] = true
337 for priv, _ in pairs(irrevokable) do
338 revokeprivs[priv] = nil
339 has_irrevokable_priv = true
341 if privs_unknown ~= "" then
342 return false, privs_unknown
344 if has_irrevokable_priv then
345 if is_singleplayer then
346 core.chat_send_player(caller,
347 S("Note: Cannot revoke in singleplayer: @1",
348 core.privs_to_string(irrevokable, ', ')))
350 core.chat_send_player(caller,
351 S("Note: Cannot revoke from admin: @1",
352 core.privs_to_string(irrevokable, ', ')))
356 local revokecount = 0
357 for priv, _ in pairs(revokeprivs) do
358 -- call the on_revoke callbacks
359 core.run_priv_callbacks(revokename, priv, caller, "revoke")
360 revokecount = revokecount + 1
363 core.set_player_privs(revokename, privs)
364 local new_privs = core.get_player_privs(revokename)
366 if revokecount == 0 then
367 return false, S("No privileges were revoked.")
370 core.log("action", caller..' revoked ('
371 ..core.privs_to_string(revokeprivs, ', ')
372 ..') privileges from '..revokename)
373 if revokename ~= caller then
374 core.chat_send_player(revokename,
375 S("@1 revoked privileges from you: @2", caller,
376 core.privs_to_string(revokeprivs, ', ')))
378 return true, privileges_of(revokename, new_privs)
381 core.register_chatcommand("revoke", {
382 params = S("<name> (<privilege> [, <privilege2> [<...>]] | all)"),
383 description = S("Remove privileges from player"),
385 func = function(name, param)
386 local revokename, revokeprivstr = string.match(param, "([^ ]+) (.+)")
387 if not revokename or not revokeprivstr then
388 return false, S("Invalid parameters (see /help revoke).")
390 return handle_revoke_command(name, revokename, revokeprivstr)
394 core.register_chatcommand("revokeme", {
395 params = S("<privilege> [, <privilege2> [<...>]] | all"),
396 description = S("Revoke privileges from yourself"),
398 func = function(name, param)
400 return false, S("Invalid parameters (see /help revokeme).")
402 return handle_revoke_command(name, name, param)
406 core.register_chatcommand("setpassword", {
407 params = S("<name> <password>"),
408 description = S("Set player's password"),
409 privs = {password=true},
410 func = function(name, param)
411 local toname, raw_password = string.match(param, "^([^ ]+) +(.+)$")
413 toname = param:match("^([^ ]+) *$")
418 return false, S("Name field required.")
421 local msg_chat, msg_log, msg_ret
422 if not raw_password then
423 core.set_player_password(toname, "")
424 msg_chat = S("Your password was cleared by @1.", name)
425 msg_log = name .. " clears password of " .. toname .. "."
426 msg_ret = S("Password of player \"@1\" cleared.", toname)
428 core.set_player_password(toname,
429 core.get_password_hash(toname,
431 msg_chat = S("Your password was set by @1.", name)
432 msg_log = name .. " sets password of " .. toname .. "."
433 msg_ret = S("Password of player \"@1\" set.", toname)
436 if toname ~= name then
437 core.chat_send_player(toname, msg_chat)
440 core.log("action", msg_log)
446 core.register_chatcommand("clearpassword", {
447 params = S("<name>"),
448 description = S("Set empty password for a player"),
449 privs = {password=true},
450 func = function(name, param)
453 return false, S("Name field required.")
455 core.set_player_password(toname, '')
457 core.log("action", name .. " clears password of " .. toname .. ".")
459 return true, S("Password of player \"@1\" cleared.", toname)
463 core.register_chatcommand("auth_reload", {
465 description = S("Reload authentication data"),
466 privs = {server=true},
467 func = function(name, param)
468 local done = core.auth_reload()
469 return done, (done and S("Done.") or S("Failed."))
473 core.register_chatcommand("remove_player", {
474 params = S("<name>"),
475 description = S("Remove a player's data"),
476 privs = {server=true},
477 func = function(name, param)
480 return false, S("Name field required.")
483 local rc = core.remove_player(toname)
486 core.log("action", name .. " removed player data of " .. toname .. ".")
487 return true, S("Player \"@1\" removed.", toname)
489 return true, S("No such player \"@1\" to remove.", toname)
491 return true, S("Player \"@1\" is connected, cannot remove.", toname)
494 return false, S("Unhandled remove_player return code @1.", tostring(rc))
499 -- pos may be a non-integer position
500 local function find_free_position_near(pos)
507 for _, d in ipairs(tries) do
508 local p = vector.add(pos, d)
509 local n = core.get_node_or_nil(p)
511 local def = core.registered_nodes[n.name]
512 if def and not def.walkable then
520 -- Teleports player <name> to <p> if possible
521 local function teleport_to_pos(name, p)
523 if p.x < -lm or p.x > lm or p.y < -lm or p.y > lm
524 or p.z < -lm or p.z > lm then
525 return false, S("Cannot teleport out of map bounds!")
527 local teleportee = core.get_player_by_name(name)
528 if not teleportee then
529 return false, S("Cannot get player with name @1.", name)
531 if teleportee:get_attach() then
532 return false, S("Cannot teleport, @1 " ..
533 "is attached to an object!", name)
535 teleportee:set_pos(p)
536 return true, S("Teleporting @1 to @2.", name, core.pos_to_string(p, 1))
539 -- Teleports player <name> next to player <target_name> if possible
540 local function teleport_to_player(name, target_name)
541 if name == target_name then
542 return false, S("One does not teleport to oneself.")
544 local teleportee = core.get_player_by_name(name)
545 if not teleportee then
546 return false, S("Cannot get teleportee with name @1.", name)
548 if teleportee:get_attach() then
549 return false, S("Cannot teleport, @1 " ..
550 "is attached to an object!", name)
552 local target = core.get_player_by_name(target_name)
554 return false, S("Cannot get target player with name @1.", target_name)
556 local p = find_free_position_near(target:get_pos())
557 teleportee:set_pos(p)
558 return true, S("Teleporting @1 to @2 at @3.", name, target_name,
559 core.pos_to_string(p, 1))
562 core.register_chatcommand("teleport", {
563 params = S("<X>,<Y>,<Z> | <to_name> | <name> <X>,<Y>,<Z> | <name> <to_name>"),
564 description = S("Teleport to position or player"),
565 privs = {teleport=true},
566 func = function(name, param)
568 p.x, p.y, p.z = param:match("^([%d.-]+)[, ] *([%d.-]+)[, ] *([%d.-]+)$")
569 p = vector.apply(p, tonumber)
570 if p.x and p.y and p.z then
571 return teleport_to_pos(name, p)
574 local target_name = param:match("^([^ ]+)$")
576 return teleport_to_player(name, target_name)
579 local has_bring_priv = core.check_player_privs(name, {bring=true})
580 local missing_bring_msg = S("You don't have permission to teleport " ..
581 "other players (missing privilege: @1).", "bring")
583 local teleportee_name
584 teleportee_name, p.x, p.y, p.z = param:match(
585 "^([^ ]+) +([%d.-]+)[, ] *([%d.-]+)[, ] *([%d.-]+)$")
586 p = vector.apply(p, tonumber)
587 if teleportee_name and p.x and p.y and p.z then
588 if not has_bring_priv then
589 return false, missing_bring_msg
591 return teleport_to_pos(teleportee_name, p)
594 teleportee_name, target_name = string.match(param, "^([^ ]+) +([^ ]+)$")
595 if teleportee_name and target_name then
596 if not has_bring_priv then
597 return false, missing_bring_msg
599 return teleport_to_player(teleportee_name, target_name)
606 core.register_chatcommand("set", {
607 params = S("([-n] <name> <value>) | <name>"),
608 description = S("Set or read server configuration setting"),
609 privs = {server=true},
610 func = function(name, param)
611 local arg, setname, setvalue = string.match(param, "(-[n]) ([^ ]+) (.+)")
612 if arg and arg == "-n" and setname and setvalue then
613 core.settings:set(setname, setvalue)
614 return true, setname .. " = " .. setvalue
617 setname, setvalue = string.match(param, "([^ ]+) (.+)")
618 if setname and setvalue then
619 if not core.settings:get(setname) then
620 return false, S("Failed. Use '/set -n <name> <value>' "
621 .. "to create a new setting.")
623 core.settings:set(setname, setvalue)
624 return true, S("@1 = @2", setname, setvalue)
627 setname = string.match(param, "([^ ]+)")
629 setvalue = core.settings:get(setname)
631 setvalue = S("<not set>")
633 return true, S("@1 = @2", setname, setvalue)
636 return false, S("Invalid parameters (see /help set).")
640 local function emergeblocks_callback(pos, action, num_calls_remaining, ctx)
641 if ctx.total_blocks == 0 then
642 ctx.total_blocks = num_calls_remaining + 1
643 ctx.current_blocks = 0
645 ctx.current_blocks = ctx.current_blocks + 1
647 if ctx.current_blocks == ctx.total_blocks then
648 core.chat_send_player(ctx.requestor_name,
649 S("Finished emerging @1 blocks in @2ms.",
651 string.format("%.2f", (os.clock() - ctx.start_time) * 1000)))
655 local function emergeblocks_progress_update(ctx)
656 if ctx.current_blocks ~= ctx.total_blocks then
657 core.chat_send_player(ctx.requestor_name,
658 S("emergeblocks update: @1/@2 blocks emerged (@3%)",
659 ctx.current_blocks, ctx.total_blocks,
660 string.format("%.1f", (ctx.current_blocks / ctx.total_blocks) * 100)))
662 core.after(2, emergeblocks_progress_update, ctx)
666 core.register_chatcommand("emergeblocks", {
667 params = S("(here [<radius>]) | (<pos1> <pos2>)"),
668 description = S("Load (or, if nonexistent, generate) map blocks contained in "
669 .. "area pos1 to pos2 (<pos1> and <pos2> must be in parentheses)"),
670 privs = {server=true},
671 func = function(name, param)
672 local p1, p2 = parse_range_str(name, param)
680 start_time = os.clock(),
681 requestor_name = name
684 core.emerge_area(p1, p2, emergeblocks_callback, context)
685 core.after(2, emergeblocks_progress_update, context)
687 return true, S("Started emerge of area ranging from @1 to @2.",
688 core.pos_to_string(p1, 1), core.pos_to_string(p2, 1))
692 core.register_chatcommand("deleteblocks", {
693 params = S("(here [<radius>]) | (<pos1> <pos2>)"),
694 description = S("Delete map blocks contained in area pos1 to pos2 "
695 .. "(<pos1> and <pos2> must be in parentheses)"),
696 privs = {server=true},
697 func = function(name, param)
698 local p1, p2 = parse_range_str(name, param)
703 if core.delete_area(p1, p2) then
704 return true, S("Successfully cleared area "
705 .. "ranging from @1 to @2.",
706 core.pos_to_string(p1, 1), core.pos_to_string(p2, 1))
708 return false, S("Failed to clear one or more "
709 .. "blocks in area.")
714 core.register_chatcommand("fixlight", {
715 params = S("(here [<radius>]) | (<pos1> <pos2>)"),
716 description = S("Resets lighting in the area between pos1 and pos2 "
717 .. "(<pos1> and <pos2> must be in parentheses)"),
718 privs = {server = true},
719 func = function(name, param)
720 local p1, p2 = parse_range_str(name, param)
725 if core.fix_light(p1, p2) then
726 return true, S("Successfully reset light in the area "
727 .. "ranging from @1 to @2.",
728 core.pos_to_string(p1, 1), core.pos_to_string(p2, 1))
730 return false, S("Failed to load one or more blocks in area.")
735 core.register_chatcommand("mods", {
737 description = S("List mods installed on the server"),
739 func = function(name, param)
740 return true, table.concat(core.get_modnames(), ", ")
744 local function handle_give_command(cmd, giver, receiver, stackstring)
745 core.log("action", giver .. " invoked " .. cmd
746 .. ', stackstring="' .. stackstring .. '"')
747 local itemstack = ItemStack(stackstring)
748 if itemstack:is_empty() then
749 return false, S("Cannot give an empty item.")
750 elseif (not itemstack:is_known()) or (itemstack:get_name() == "unknown") then
751 return false, S("Cannot give an unknown item.")
752 -- Forbid giving 'ignore' due to unwanted side effects
753 elseif itemstack:get_name() == "ignore" then
754 return false, S("Giving 'ignore' is not allowed.")
756 local receiverref = core.get_player_by_name(receiver)
757 if receiverref == nil then
758 return false, S("@1 is not a known player.", receiver)
760 local leftover = receiverref:get_inventory():add_item("main", itemstack)
762 if leftover:is_empty() then
764 elseif leftover:get_count() == itemstack:get_count() then
769 -- The actual item stack string may be different from what the "giver"
770 -- entered (e.g. big numbers are always interpreted as 2^16-1).
771 stackstring = itemstack:to_string()
773 if partiality == true then
774 msg = S("@1 partially added to inventory.", stackstring)
775 elseif partiality == false then
776 msg = S("@1 could not be added to inventory.", stackstring)
778 msg = S("@1 added to inventory.", stackstring)
780 if giver == receiver then
783 core.chat_send_player(receiver, msg)
785 if partiality == true then
786 msg_other = S("@1 partially added to inventory of @2.",
787 stackstring, receiver)
788 elseif partiality == false then
789 msg_other = S("@1 could not be added to inventory of @2.",
790 stackstring, receiver)
792 msg_other = S("@1 added to inventory of @2.",
793 stackstring, receiver)
795 return true, msg_other
799 core.register_chatcommand("give", {
800 params = S("<name> <ItemString> [<count> [<wear>]]"),
801 description = S("Give item to player"),
803 func = function(name, param)
804 local toname, itemstring = string.match(param, "^([^ ]+) +(.+)$")
805 if not toname or not itemstring then
806 return false, S("Name and ItemString required.")
808 return handle_give_command("/give", name, toname, itemstring)
812 core.register_chatcommand("giveme", {
813 params = S("<ItemString> [<count> [<wear>]]"),
814 description = S("Give item to yourself"),
816 func = function(name, param)
817 local itemstring = string.match(param, "(.+)$")
818 if not itemstring then
819 return false, S("ItemString required.")
821 return handle_give_command("/giveme", name, name, itemstring)
825 core.register_chatcommand("spawnentity", {
826 params = S("<EntityName> [<X>,<Y>,<Z>]"),
827 description = S("Spawn entity at given (or your) position"),
828 privs = {give=true, interact=true},
829 func = function(name, param)
830 local entityname, p = string.match(param, "^([^ ]+) *(.*)$")
831 if not entityname then
832 return false, S("EntityName required.")
834 core.log("action", ("%s invokes /spawnentity, entityname=%q")
835 :format(name, entityname))
836 local player = core.get_player_by_name(name)
837 if player == nil then
838 core.log("error", "Unable to spawn entity, player is nil")
839 return false, S("Unable to spawn entity, player is nil.")
841 if not core.registered_entities[entityname] then
842 return false, S("Cannot spawn an unknown entity.")
847 p = core.string_to_pos(p)
849 return false, S("Invalid parameters (@1).", param)
853 local obj = core.add_entity(p, entityname)
855 return true, S("@1 spawned.", entityname)
857 return true, S("@1 failed to spawn.", entityname)
862 core.register_chatcommand("pulverize", {
864 description = S("Destroy item in hand"),
865 func = function(name, param)
866 local player = core.get_player_by_name(name)
868 core.log("error", "Unable to pulverize, no player.")
869 return false, S("Unable to pulverize, no player.")
871 local wielded_item = player:get_wielded_item()
872 if wielded_item:is_empty() then
873 return false, S("Unable to pulverize, no item in hand.")
875 core.log("action", name .. " pulverized \"" ..
876 wielded_item:get_name() .. " " .. wielded_item:get_count() .. "\"")
877 player:set_wielded_item(nil)
878 return true, S("An item was pulverized.")
883 core.rollback_punch_callbacks = {}
885 core.register_on_punchnode(function(pos, node, puncher)
886 local name = puncher and puncher:get_player_name()
887 if name and core.rollback_punch_callbacks[name] then
888 core.rollback_punch_callbacks[name](pos, node, puncher)
889 core.rollback_punch_callbacks[name] = nil
893 core.register_chatcommand("rollback_check", {
894 params = S("[<range>] [<seconds>] [<limit>]"),
895 description = S("Check who last touched a node or a node near it "
896 .. "within the time specified by <seconds>. "
897 .. "Default: range = 0, seconds = 86400 = 24h, limit = 5. "
898 .. "Set <seconds> to inf for no time limit"),
899 privs = {rollback=true},
900 func = function(name, param)
901 if not core.settings:get_bool("enable_rollback_recording") then
902 return false, S("Rollback functions are disabled.")
904 local range, seconds, limit =
905 param:match("(%d+) *(%d*) *(%d*)")
906 range = tonumber(range) or 0
907 seconds = tonumber(seconds) or 86400
908 limit = tonumber(limit) or 5
910 return false, S("That limit is too high!")
913 core.rollback_punch_callbacks[name] = function(pos, node, puncher)
914 local name = puncher:get_player_name()
915 core.chat_send_player(name, S("Checking @1 ...", core.pos_to_string(pos)))
916 local actions = core.rollback_get_node_actions(pos, range, seconds, limit)
918 core.chat_send_player(name, S("Rollback functions are disabled."))
921 local num_actions = #actions
922 if num_actions == 0 then
923 core.chat_send_player(name,
924 S("Nobody has touched the specified "
925 .. "location in @1 seconds.",
929 local time = os.time()
930 for i = num_actions, 1, -1 do
931 local action = actions[i]
932 core.chat_send_player(name,
933 S("@1 @2 @3 -> @4 @5 seconds ago.",
934 core.pos_to_string(action.pos),
942 return true, S("Punch a node (range=@1, seconds=@2, limit=@3).",
943 range, seconds, limit)
947 core.register_chatcommand("rollback", {
948 params = S("(<name> [<seconds>]) | (:<actor> [<seconds>])"),
949 description = S("Revert actions of a player. "
950 .. "Default for <seconds> is 60. "
951 .. "Set <seconds> to inf for no time limit"),
952 privs = {rollback=true},
953 func = function(name, param)
954 if not core.settings:get_bool("enable_rollback_recording") then
955 return false, S("Rollback functions are disabled.")
957 local target_name, seconds = string.match(param, ":([^ ]+) *(%d*)")
959 if not target_name then
961 player_name, seconds = string.match(param, "([^ ]+) *(%d*)")
962 if not player_name then
963 return false, S("Invalid parameters. "
964 .. "See /help rollback and "
965 .. "/help rollback_check.")
967 seconds = tonumber(seconds) or 60
968 target_name = "player:"..player_name
969 rev_msg = S("Reverting actions of player '@1' since @2 seconds.",
970 player_name, seconds)
972 seconds = tonumber(seconds) or 60
973 rev_msg = S("Reverting actions of @1 since @2 seconds.",
974 target_name, seconds)
976 core.chat_send_player(name, rev_msg)
977 local success, log = core.rollback_revert_actions_by(
978 target_name, seconds)
981 response = S("(log is too long to show)").."\n"
983 for _, line in pairs(log) do
984 response = response .. line .. "\n"
988 response = response .. S("Reverting actions succeeded.")
990 response = response .. S("Reverting actions FAILED.")
992 return success, response
996 core.register_chatcommand("status", {
997 description = S("Show server status"),
998 func = function(name, param)
999 local status = core.get_server_status(name, false)
1000 if status and status ~= "" then
1003 return false, S("This command was disabled by a mod or game.")
1007 core.register_chatcommand("time", {
1008 params = S("[<0..23>:<0..59> | <0..24000>]"),
1009 description = S("Show or set time of day"),
1011 func = function(name, param)
1013 local current_time = math.floor(core.get_timeofday() * 1440)
1014 local minutes = current_time % 60
1015 local hour = (current_time - minutes) / 60
1016 return true, S("Current time is @1:@2.",
1017 string.format("%d", hour),
1018 string.format("%02d", minutes))
1020 local player_privs = core.get_player_privs(name)
1021 if not player_privs.settime then
1022 return false, S("You don't have permission to run "
1023 .. "this command (missing privilege: @1).", "settime")
1025 local hour, minute = param:match("^(%d+):(%d+)$")
1027 local new_time = tonumber(param)
1028 if not new_time then
1029 return false, S("Invalid time.")
1031 -- Backward compatibility.
1032 core.set_timeofday((new_time % 24000) / 24000)
1033 core.log("action", name .. " sets time to " .. new_time)
1034 return true, S("Time of day changed.")
1036 hour = tonumber(hour)
1037 minute = tonumber(minute)
1038 if hour < 0 or hour > 23 then
1039 return false, S("Invalid hour (must be between 0 and 23 inclusive).")
1040 elseif minute < 0 or minute > 59 then
1041 return false, S("Invalid minute (must be between 0 and 59 inclusive).")
1043 core.set_timeofday((hour * 60 + minute) / 1440)
1044 core.log("action", ("%s sets time to %d:%02d"):format(name, hour, minute))
1045 return true, S("Time of day changed.")
1049 core.register_chatcommand("days", {
1050 description = S("Show day count since world creation"),
1051 func = function(name, param)
1052 return true, S("Current day is @1.", core.get_day_count())
1056 core.register_chatcommand("shutdown", {
1057 params = S("[<delay_in_seconds> | -1] [reconnect] [<message>]"),
1058 description = S("Shutdown server (-1 cancels a delayed shutdown)"),
1059 privs = {server=true},
1060 func = function(name, param)
1061 local delay, reconnect, message
1062 delay, param = param:match("^%s*(%S+)(.*)")
1064 reconnect, param = param:match("^%s*(%S+)(.*)")
1066 message = param and param:match("^%s*(.+)") or ""
1067 delay = tonumber(delay) or 0
1070 core.log("action", name .. " shuts down server")
1071 core.chat_send_all("*** "..S("Server shutting down (operator request)."))
1073 core.request_shutdown(message:trim(), core.is_yes(reconnect), delay)
1078 core.register_chatcommand("ban", {
1079 params = S("[<name>]"),
1080 description = S("Ban the IP of a player or show the ban list"),
1082 func = function(name, param)
1084 local ban_list = core.get_ban_list()
1085 if ban_list == "" then
1086 return true, S("The ban list is empty.")
1088 return true, S("Ban list: @1", ban_list)
1091 if not core.get_player_by_name(param) then
1092 return false, S("Player is not online.")
1094 if not core.ban_player(param) then
1095 return false, S("Failed to ban player.")
1097 local desc = core.get_ban_description(param)
1098 core.log("action", name .. " bans " .. desc .. ".")
1099 return true, S("Banned @1.", desc)
1103 core.register_chatcommand("unban", {
1104 params = S("<name> | <IP_address>"),
1105 description = S("Remove IP ban belonging to a player/IP"),
1107 func = function(name, param)
1108 if not core.unban_player_or_ip(param) then
1109 return false, S("Failed to unban player/IP.")
1111 core.log("action", name .. " unbans " .. param)
1112 return true, S("Unbanned @1.", param)
1116 core.register_chatcommand("kick", {
1117 params = S("<name> [<reason>]"),
1118 description = S("Kick a player"),
1119 privs = {kick=true},
1120 func = function(name, param)
1121 local tokick, reason = param:match("([^ ]+) (.+)")
1122 tokick = tokick or param
1123 if not core.kick_player(tokick, reason) then
1124 return false, S("Failed to kick player @1.", tokick)
1126 local log_reason = ""
1128 log_reason = " with reason \"" .. reason .. "\""
1130 core.log("action", name .. " kicks " .. tokick .. log_reason)
1131 return true, S("Kicked @1.", tokick)
1135 core.register_chatcommand("clearobjects", {
1136 params = S("[full | quick]"),
1137 description = S("Clear all objects in world"),
1138 privs = {server=true},
1139 func = function(name, param)
1141 if param == "" or param == "quick" then
1142 options.mode = "quick"
1143 elseif param == "full" then
1144 options.mode = "full"
1146 return false, S("Invalid usage, see /help clearobjects.")
1149 core.log("action", name .. " clears objects ("
1150 .. options.mode .. " mode).")
1151 if options.mode == "full" then
1152 core.chat_send_all(S("Clearing all objects. This may take a long time. "
1153 .. "You may experience a timeout. (by @1)", name))
1155 core.clear_objects(options)
1156 core.log("action", "Object clearing done.")
1157 core.chat_send_all("*** "..S("Cleared all objects."))
1162 core.register_chatcommand("msg", {
1163 params = S("<name> <message>"),
1164 description = S("Send a direct message to a player"),
1165 privs = {shout=true},
1166 func = function(name, param)
1167 local sendto, message = param:match("^(%S+)%s(.+)$")
1169 return false, S("Invalid usage, see /help msg.")
1171 if not core.get_player_by_name(sendto) then
1172 return false, S("The player @1 is not online.", sendto)
1174 core.log("action", "DM from " .. name .. " to " .. sendto
1176 core.chat_send_player(sendto, S("DM from @1: @2", name, message))
1177 return true, S("Message sent.")
1181 core.register_chatcommand("last-login", {
1182 params = S("[<name>]"),
1183 description = S("Get the last login time of a player or yourself"),
1184 func = function(name, param)
1188 local pauth = core.get_auth_handler().get_auth(param)
1189 if pauth and pauth.last_login and pauth.last_login ~= -1 then
1190 -- Time in UTC, ISO 8601 format
1191 return true, S("@1's last login time was @2.",
1193 os.date("!%Y-%m-%dT%H:%M:%SZ", pauth.last_login))
1195 return false, S("@1's last login time is unknown.", param)
1199 core.register_chatcommand("clearinv", {
1200 params = S("[<name>]"),
1201 description = S("Clear the inventory of yourself or another player"),
1202 func = function(name, param)
1204 if param and param ~= "" and param ~= name then
1205 if not core.check_player_privs(name, {server=true}) then
1206 return false, S("You don't have permission to "
1207 .. "clear another player's inventory "
1208 .. "(missing privilege: @1).", "server")
1210 player = core.get_player_by_name(param)
1211 core.chat_send_player(param, S("@1 cleared your inventory.", name))
1213 player = core.get_player_by_name(name)
1217 player:get_inventory():set_list("main", {})
1218 player:get_inventory():set_list("craft", {})
1219 player:get_inventory():set_list("craftpreview", {})
1220 core.log("action", name.." clears "..player:get_player_name().."'s inventory")
1221 return true, S("Cleared @1's inventory.", player:get_player_name())
1223 return false, S("Player must be online to clear inventory!")
1228 local function handle_kill_command(killer, victim)
1229 if core.settings:get_bool("enable_damage") == false then
1230 return false, S("Players can't be killed, damage has been disabled.")
1232 local victimref = core.get_player_by_name(victim)
1233 if victimref == nil then
1234 return false, S("Player @1 is not online.", victim)
1235 elseif victimref:get_hp() <= 0 then
1236 if killer == victim then
1237 return false, S("You are already dead.")
1239 return false, S("@1 is already dead.", victim)
1242 if not killer == victim then
1243 core.log("action", string.format("%s killed %s", killer, victim))
1247 return true, S("@1 has been killed.", victim)
1250 core.register_chatcommand("kill", {
1251 params = S("[<name>]"),
1252 description = S("Kill player or yourself"),
1253 privs = {server=true},
1254 func = function(name, param)
1255 return handle_kill_command(name, param == "" and name or param)