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 = minetest.get_us_time()
79 local success, result = cmd_def.func(name, param)
80 local delay = (minetest.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
95 minetest.colorize("#f3d2ff", " (%.5g s)"):format(delay)
97 result = minetest.colorize("#f3d2ff",
98 "Command execution took %.5f s"):format(delay)
102 core.chat_send_player(name, result)
106 core.chat_send_player(name,
107 S("You don't have permission to run this command "
108 .. "(missing privileges: @1).",
109 table.concat(missing_privs, ", ")))
111 return true -- Handled chat message
114 if core.settings:get_bool("profiler.load") then
115 -- Run after register_chatcommand and its register_on_chat_message
116 -- Before any chatcommands that should be profiled
117 profiler.init_chatcommand()
120 -- Parses a "range" string in the format of "here (number)" or
121 -- "(x1, y1, z1) (x2, y2, z2)", returning two position vectors
122 local function parse_range_str(player_name, str)
124 local args = str:split(" ")
126 if args[1] == "here" then
127 p1, p2 = core.get_player_radius_area(player_name, tonumber(args[2]))
129 return false, S("Unable to get position of player @1.", player_name)
132 p1, p2 = core.string_to_area(str)
134 return false, S("Incorrect area format. "
135 .. "Expected: (x1,y1,z1) (x2,y2,z2)")
145 core.register_chatcommand("me", {
146 params = S("<action>"),
147 description = S("Show chat action (e.g., '/me orders a pizza' "
148 .. "displays '<player name> orders a pizza')"),
149 privs = {shout=true},
150 func = function(name, param)
151 core.chat_send_all("* " .. name .. " " .. param)
156 core.register_chatcommand("admin", {
157 description = S("Show the name of the server owner"),
158 func = function(name)
159 local admin = core.settings:get("name")
161 return true, S("The administrator of this server is @1.", admin)
163 return false, S("There's no administrator named "
164 .. "in the config file.")
169 core.register_chatcommand("privs", {
170 params = S("[<name>]"),
171 description = S("Show privileges of yourself or another player"),
172 func = function(caller, param)
174 local name = (param ~= "" and param or caller)
175 if not core.player_exists(name) then
176 return false, S("Player @1 does not exist.", name)
178 return true, S("Privileges of @1: @2", name,
179 core.privs_to_string(
180 core.get_player_privs(name), ", "))
184 core.register_chatcommand("haspriv", {
185 params = S("<privilege>"),
186 description = S("Return list of all online players with privilege"),
187 privs = {basic_privs = true},
188 func = function(caller, param)
191 return false, S("Invalid parameters (see /help haspriv).")
193 if not core.registered_privileges[param] then
194 return false, S("Unknown privilege!")
196 local privs = core.string_to_privs(param)
197 local players_with_priv = {}
198 for _, player in pairs(core.get_connected_players()) do
199 local player_name = player:get_player_name()
200 if core.check_player_privs(player_name, privs) then
201 table.insert(players_with_priv, player_name)
204 return true, S("Players online with the \"@1\" privilege: @2",
206 table.concat(players_with_priv, ", "))
210 local function handle_grant_command(caller, grantname, grantprivstr)
211 local caller_privs = core.get_player_privs(caller)
212 if not (caller_privs.privs or caller_privs.basic_privs) then
213 return false, S("Your privileges are insufficient.")
216 if not core.get_auth_handler().get_auth(grantname) then
217 return false, S("Player @1 does not exist.", grantname)
219 local grantprivs = core.string_to_privs(grantprivstr)
220 if grantprivstr == "all" then
221 grantprivs = core.registered_privileges
223 local privs = core.get_player_privs(grantname)
224 local privs_unknown = ""
226 core.string_to_privs(core.settings:get("basic_privs") or "interact,shout")
227 for priv, _ in pairs(grantprivs) do
228 if not basic_privs[priv] and not caller_privs.privs then
229 return false, S("Your privileges are insufficient.")
231 if not core.registered_privileges[priv] then
232 privs_unknown = privs_unknown .. S("Unknown privilege: @1", priv) .. "\n"
236 if privs_unknown ~= "" then
237 return false, privs_unknown
239 for priv, _ in pairs(grantprivs) do
240 -- call the on_grant callbacks
241 core.run_priv_callbacks(grantname, priv, caller, "grant")
243 core.set_player_privs(grantname, privs)
244 core.log("action", caller..' granted ('..core.privs_to_string(grantprivs, ', ')..') privileges to '..grantname)
245 if grantname ~= caller then
246 core.chat_send_player(grantname,
247 S("@1 granted you privileges: @2", caller,
248 core.privs_to_string(grantprivs, ' ')))
250 return true, S("Privileges of @1: @2", grantname,
251 core.privs_to_string(
252 core.get_player_privs(grantname), ' '))
255 core.register_chatcommand("grant", {
256 params = S("<name> (<privilege> | all)"),
257 description = S("Give privileges to player"),
258 func = function(name, param)
259 local grantname, grantprivstr = string.match(param, "([^ ]+) (.+)")
260 if not grantname or not grantprivstr then
261 return false, S("Invalid parameters (see /help grant).")
263 return handle_grant_command(name, grantname, grantprivstr)
267 core.register_chatcommand("grantme", {
268 params = S("<privilege> | all"),
269 description = S("Grant privileges to yourself"),
270 func = function(name, param)
272 return false, S("Invalid parameters (see /help grantme).")
274 return handle_grant_command(name, name, param)
278 local function handle_revoke_command(caller, revokename, revokeprivstr)
279 local caller_privs = core.get_player_privs(caller)
280 if not (caller_privs.privs or caller_privs.basic_privs) then
281 return false, S("Your privileges are insufficient.")
284 if not core.get_auth_handler().get_auth(revokename) then
285 return false, S("Player @1 does not exist.", revokename)
288 local revokeprivs = core.string_to_privs(revokeprivstr)
289 local privs = core.get_player_privs(revokename)
291 core.string_to_privs(core.settings:get("basic_privs") or "interact,shout")
292 for priv, _ in pairs(revokeprivs) do
293 if not basic_privs[priv] and not caller_privs.privs then
294 return false, S("Your privileges are insufficient.")
298 if revokeprivstr == "all" then
302 for priv, _ in pairs(revokeprivs) do
307 for priv, _ in pairs(revokeprivs) do
308 -- call the on_revoke callbacks
309 core.run_priv_callbacks(revokename, priv, caller, "revoke")
312 core.set_player_privs(revokename, privs)
313 core.log("action", caller..' revoked ('
314 ..core.privs_to_string(revokeprivs, ', ')
315 ..') privileges from '..revokename)
316 if revokename ~= caller then
317 core.chat_send_player(revokename,
318 S("@1 revoked privileges from you: @2", caller,
319 core.privs_to_string(revokeprivs, ' ')))
321 return true, S("Privileges of @1: @2", revokename,
322 core.privs_to_string(
323 core.get_player_privs(revokename), ' '))
326 core.register_chatcommand("revoke", {
327 params = S("<name> (<privilege> | all)"),
328 description = S("Remove privileges from player"),
330 func = function(name, param)
331 local revokename, revokeprivstr = string.match(param, "([^ ]+) (.+)")
332 if not revokename or not revokeprivstr then
333 return false, S("Invalid parameters (see /help revoke).")
335 return handle_revoke_command(name, revokename, revokeprivstr)
339 core.register_chatcommand("revokeme", {
340 params = S("<privilege> | all"),
341 description = S("Revoke privileges from yourself"),
343 func = function(name, param)
345 return false, S("Invalid parameters (see /help revokeme).")
347 return handle_revoke_command(name, name, param)
351 core.register_chatcommand("setpassword", {
352 params = S("<name> <password>"),
353 description = S("Set player's password"),
354 privs = {password=true},
355 func = function(name, param)
356 local toname, raw_password = string.match(param, "^([^ ]+) +(.+)$")
358 toname = param:match("^([^ ]+) *$")
363 return false, S("Name field required.")
366 local msg_chat, msg_log, msg_ret
367 if not raw_password then
368 core.set_player_password(toname, "")
369 msg_chat = S("Your password was cleared by @1.", name)
370 msg_log = name .. " clears password of " .. toname .. "."
371 msg_ret = S("Password of player \"@1\" cleared.", toname)
373 core.set_player_password(toname,
374 core.get_password_hash(toname,
376 msg_chat = S("Your password was set by @1.", name)
377 msg_log = name .. " sets password of " .. toname .. "."
378 msg_ret = S("Password of player \"@1\" set.", toname)
381 if toname ~= name then
382 core.chat_send_player(toname, msg_chat)
385 core.log("action", msg_log)
391 core.register_chatcommand("clearpassword", {
392 params = S("<name>"),
393 description = S("Set empty password for a player"),
394 privs = {password=true},
395 func = function(name, param)
398 return false, S("Name field required.")
400 core.set_player_password(toname, '')
402 core.log("action", name .. " clears password of " .. toname .. ".")
404 return true, S("Password of player \"@1\" cleared.", toname)
408 core.register_chatcommand("auth_reload", {
410 description = S("Reload authentication data"),
411 privs = {server=true},
412 func = function(name, param)
413 local done = core.auth_reload()
414 return done, (done and S("Done.") or S("Failed."))
418 core.register_chatcommand("remove_player", {
419 params = S("<name>"),
420 description = S("Remove a player's data"),
421 privs = {server=true},
422 func = function(name, param)
425 return false, S("Name field required.")
428 local rc = core.remove_player(toname)
431 core.log("action", name .. " removed player data of " .. toname .. ".")
432 return true, S("Player \"@1\" removed.", toname)
434 return true, S("No such player \"@1\" to remove.", toname)
436 return true, S("Player \"@1\" is connected, cannot remove.", toname)
439 return false, S("Unhandled remove_player return code @1.", tostring(rc))
444 -- pos may be a non-integer position
445 local function find_free_position_near(pos)
452 for _, d in ipairs(tries) do
453 local p = vector.add(pos, d)
454 local n = core.get_node_or_nil(p)
456 local def = core.registered_nodes[n.name]
457 if def and not def.walkable then
465 -- Teleports player <name> to <p> if possible
466 local function teleport_to_pos(name, p)
468 if p.x < -lm or p.x > lm or p.y < -lm or p.y > lm
469 or p.z < -lm or p.z > lm then
470 return false, S("Cannot teleport out of map bounds!")
472 local teleportee = core.get_player_by_name(name)
473 if not teleportee then
474 return false, S("Cannot get player with name @1.", name)
476 if teleportee:get_attach() then
477 return false, S("Cannot teleport, @1 " ..
478 "is attached to an object!", name)
480 teleportee:set_pos(p)
481 return true, S("Teleporting @1 to @2.", name, core.pos_to_string(p, 1))
484 -- Teleports player <name> next to player <target_name> if possible
485 local function teleport_to_player(name, target_name)
486 if name == target_name then
487 return false, S("One does not teleport to oneself.")
489 local teleportee = core.get_player_by_name(name)
490 if not teleportee then
491 return false, S("Cannot get teleportee with name @1.", name)
493 if teleportee:get_attach() then
494 return false, S("Cannot teleport, @1 " ..
495 "is attached to an object!", name)
497 local target = core.get_player_by_name(target_name)
499 return false, S("Cannot get target player with name @1.", target_name)
501 local p = find_free_position_near(target:get_pos())
502 teleportee:set_pos(p)
503 return true, S("Teleporting @1 to @2 at @3.", name, target_name,
504 core.pos_to_string(p, 1))
507 core.register_chatcommand("teleport", {
508 params = S("<X>,<Y>,<Z> | <to_name> | <name> <X>,<Y>,<Z> | <name> <to_name>"),
509 description = S("Teleport to position or player"),
510 privs = {teleport=true},
511 func = function(name, param)
513 p.x, p.y, p.z = param:match("^([%d.-]+)[, ] *([%d.-]+)[, ] *([%d.-]+)$")
514 p = vector.apply(p, tonumber)
515 if p.x and p.y and p.z then
516 return teleport_to_pos(name, p)
519 local target_name = param:match("^([^ ]+)$")
521 return teleport_to_player(name, target_name)
524 local has_bring_priv = core.check_player_privs(name, {bring=true})
525 local missing_bring_msg = S("You don't have permission to teleport " ..
526 "other players (missing privilege: @1).", "bring")
528 local teleportee_name
529 teleportee_name, p.x, p.y, p.z = param:match(
530 "^([^ ]+) +([%d.-]+)[, ] *([%d.-]+)[, ] *([%d.-]+)$")
531 p = vector.apply(p, tonumber)
532 if teleportee_name and p.x and p.y and p.z then
533 if not has_bring_priv then
534 return false, missing_bring_msg
536 return teleport_to_pos(teleportee_name, p)
539 teleportee_name, target_name = string.match(param, "^([^ ]+) +([^ ]+)$")
540 if teleportee_name and target_name then
541 if not has_bring_priv then
542 return false, missing_bring_msg
544 return teleport_to_player(teleportee_name, target_name)
551 core.register_chatcommand("set", {
552 params = S("([-n] <name> <value>) | <name>"),
553 description = S("Set or read server configuration setting"),
554 privs = {server=true},
555 func = function(name, param)
556 local arg, setname, setvalue = string.match(param, "(-[n]) ([^ ]+) (.+)")
557 if arg and arg == "-n" and setname and setvalue then
558 core.settings:set(setname, setvalue)
559 return true, setname .. " = " .. setvalue
562 setname, setvalue = string.match(param, "([^ ]+) (.+)")
563 if setname and setvalue then
564 if not core.settings:get(setname) then
565 return false, S("Failed. Use '/set -n <name> <value>' "
566 .. "to create a new setting.")
568 core.settings:set(setname, setvalue)
569 return true, S("@1 = @2", setname, setvalue)
572 setname = string.match(param, "([^ ]+)")
574 setvalue = core.settings:get(setname)
576 setvalue = S("<not set>")
578 return true, S("@1 = @2", setname, setvalue)
581 return false, S("Invalid parameters (see /help set).")
585 local function emergeblocks_callback(pos, action, num_calls_remaining, ctx)
586 if ctx.total_blocks == 0 then
587 ctx.total_blocks = num_calls_remaining + 1
588 ctx.current_blocks = 0
590 ctx.current_blocks = ctx.current_blocks + 1
592 if ctx.current_blocks == ctx.total_blocks then
593 core.chat_send_player(ctx.requestor_name,
594 S("Finished emerging @1 blocks in @2ms.",
596 string.format("%.2f", (os.clock() - ctx.start_time) * 1000)))
600 local function emergeblocks_progress_update(ctx)
601 if ctx.current_blocks ~= ctx.total_blocks then
602 core.chat_send_player(ctx.requestor_name,
603 S("emergeblocks update: @1/@2 blocks emerged (@3%)",
604 ctx.current_blocks, ctx.total_blocks,
605 string.format("%.1f", (ctx.current_blocks / ctx.total_blocks) * 100)))
607 core.after(2, emergeblocks_progress_update, ctx)
611 core.register_chatcommand("emergeblocks", {
612 params = S("(here [<radius>]) | (<pos1> <pos2>)"),
613 description = S("Load (or, if nonexistent, generate) map blocks contained in "
614 .. "area pos1 to pos2 (<pos1> and <pos2> must be in parentheses)"),
615 privs = {server=true},
616 func = function(name, param)
617 local p1, p2 = parse_range_str(name, param)
625 start_time = os.clock(),
626 requestor_name = name
629 core.emerge_area(p1, p2, emergeblocks_callback, context)
630 core.after(2, emergeblocks_progress_update, context)
632 return true, S("Started emerge of area ranging from @1 to @2.",
633 core.pos_to_string(p1, 1), core.pos_to_string(p2, 1))
637 core.register_chatcommand("deleteblocks", {
638 params = S("(here [<radius>]) | (<pos1> <pos2>)"),
639 description = S("Delete map blocks contained in area pos1 to pos2 "
640 .. "(<pos1> and <pos2> must be in parentheses)"),
641 privs = {server=true},
642 func = function(name, param)
643 local p1, p2 = parse_range_str(name, param)
648 if core.delete_area(p1, p2) then
649 return true, S("Successfully cleared area "
650 .. "ranging from @1 to @2.",
651 core.pos_to_string(p1, 1), core.pos_to_string(p2, 1))
653 return false, S("Failed to clear one or more "
654 .. "blocks in area.")
659 core.register_chatcommand("fixlight", {
660 params = S("(here [<radius>]) | (<pos1> <pos2>)"),
661 description = S("Resets lighting in the area between pos1 and pos2 "
662 .. "(<pos1> and <pos2> must be in parentheses)"),
663 privs = {server = true},
664 func = function(name, param)
665 local p1, p2 = parse_range_str(name, param)
670 if core.fix_light(p1, p2) then
671 return true, S("Successfully reset light in the area "
672 .. "ranging from @1 to @2.",
673 core.pos_to_string(p1, 1), core.pos_to_string(p2, 1))
675 return false, S("Failed to load one or more blocks in area.")
680 core.register_chatcommand("mods", {
682 description = S("List mods installed on the server"),
684 func = function(name, param)
685 return true, table.concat(core.get_modnames(), ", ")
689 local function handle_give_command(cmd, giver, receiver, stackstring)
690 core.log("action", giver .. " invoked " .. cmd
691 .. ', stackstring="' .. stackstring .. '"')
692 local itemstack = ItemStack(stackstring)
693 if itemstack:is_empty() then
694 return false, S("Cannot give an empty item.")
695 elseif (not itemstack:is_known()) or (itemstack:get_name() == "unknown") then
696 return false, S("Cannot give an unknown item.")
697 -- Forbid giving 'ignore' due to unwanted side effects
698 elseif itemstack:get_name() == "ignore" then
699 return false, S("Giving 'ignore' is not allowed.")
701 local receiverref = core.get_player_by_name(receiver)
702 if receiverref == nil then
703 return false, S("@1 is not a known player.", receiver)
705 local leftover = receiverref:get_inventory():add_item("main", itemstack)
707 if leftover:is_empty() then
709 elseif leftover:get_count() == itemstack:get_count() then
714 -- The actual item stack string may be different from what the "giver"
715 -- entered (e.g. big numbers are always interpreted as 2^16-1).
716 stackstring = itemstack:to_string()
718 if partiality == true then
719 msg = S("@1 partially added to inventory.", stackstring)
720 elseif partiality == false then
721 msg = S("@1 could not be added to inventory.", stackstring)
723 msg = S("@1 added to inventory.", stackstring)
725 if giver == receiver then
728 core.chat_send_player(receiver, msg)
730 if partiality == true then
731 msg_other = S("@1 partially added to inventory of @2.",
732 stackstring, receiver)
733 elseif partiality == false then
734 msg_other = S("@1 could not be added to inventory of @2.",
735 stackstring, receiver)
737 msg_other = S("@1 added to inventory of @2.",
738 stackstring, receiver)
740 return true, msg_other
744 core.register_chatcommand("give", {
745 params = S("<name> <ItemString> [<count> [<wear>]]"),
746 description = S("Give item to player"),
748 func = function(name, param)
749 local toname, itemstring = string.match(param, "^([^ ]+) +(.+)$")
750 if not toname or not itemstring then
751 return false, S("Name and ItemString required.")
753 return handle_give_command("/give", name, toname, itemstring)
757 core.register_chatcommand("giveme", {
758 params = S("<ItemString> [<count> [<wear>]]"),
759 description = S("Give item to yourself"),
761 func = function(name, param)
762 local itemstring = string.match(param, "(.+)$")
763 if not itemstring then
764 return false, S("ItemString required.")
766 return handle_give_command("/giveme", name, name, itemstring)
770 core.register_chatcommand("spawnentity", {
771 params = S("<EntityName> [<X>,<Y>,<Z>]"),
772 description = S("Spawn entity at given (or your) position"),
773 privs = {give=true, interact=true},
774 func = function(name, param)
775 local entityname, p = string.match(param, "^([^ ]+) *(.*)$")
776 if not entityname then
777 return false, S("EntityName required.")
779 core.log("action", ("%s invokes /spawnentity, entityname=%q")
780 :format(name, entityname))
781 local player = core.get_player_by_name(name)
782 if player == nil then
783 core.log("error", "Unable to spawn entity, player is nil")
784 return false, S("Unable to spawn entity, player is nil.")
786 if not core.registered_entities[entityname] then
787 return false, S("Cannot spawn an unknown entity.")
792 p = core.string_to_pos(p)
794 return false, S("Invalid parameters (@1).", param)
798 local obj = core.add_entity(p, entityname)
800 return true, S("@1 spawned.", entityname)
802 return true, S("@1 failed to spawn.", entityname)
807 core.register_chatcommand("pulverize", {
809 description = S("Destroy item in hand"),
810 func = function(name, param)
811 local player = core.get_player_by_name(name)
813 core.log("error", "Unable to pulverize, no player.")
814 return false, S("Unable to pulverize, no player.")
816 local wielded_item = player:get_wielded_item()
817 if wielded_item:is_empty() then
818 return false, S("Unable to pulverize, no item in hand.")
820 core.log("action", name .. " pulverized \"" ..
821 wielded_item:get_name() .. " " .. wielded_item:get_count() .. "\"")
822 player:set_wielded_item(nil)
823 return true, S("An item was pulverized.")
828 core.rollback_punch_callbacks = {}
830 core.register_on_punchnode(function(pos, node, puncher)
831 local name = puncher and puncher:get_player_name()
832 if name and core.rollback_punch_callbacks[name] then
833 core.rollback_punch_callbacks[name](pos, node, puncher)
834 core.rollback_punch_callbacks[name] = nil
838 core.register_chatcommand("rollback_check", {
839 params = S("[<range>] [<seconds>] [<limit>]"),
840 description = S("Check who last touched a node or a node near it "
841 .. "within the time specified by <seconds>. "
842 .. "Default: range = 0, seconds = 86400 = 24h, limit = 5. "
843 .. "Set <seconds> to inf for no time limit"),
844 privs = {rollback=true},
845 func = function(name, param)
846 if not core.settings:get_bool("enable_rollback_recording") then
847 return false, S("Rollback functions are disabled.")
849 local range, seconds, limit =
850 param:match("(%d+) *(%d*) *(%d*)")
851 range = tonumber(range) or 0
852 seconds = tonumber(seconds) or 86400
853 limit = tonumber(limit) or 5
855 return false, S("That limit is too high!")
858 core.rollback_punch_callbacks[name] = function(pos, node, puncher)
859 local name = puncher:get_player_name()
860 core.chat_send_player(name, S("Checking @1 ...", core.pos_to_string(pos)))
861 local actions = core.rollback_get_node_actions(pos, range, seconds, limit)
863 core.chat_send_player(name, S("Rollback functions are disabled."))
866 local num_actions = #actions
867 if num_actions == 0 then
868 core.chat_send_player(name,
869 S("Nobody has touched the specified "
870 .. "location in @1 seconds.",
874 local time = os.time()
875 for i = num_actions, 1, -1 do
876 local action = actions[i]
877 core.chat_send_player(name,
878 S("@1 @2 @3 -> @4 @5 seconds ago.",
879 core.pos_to_string(action.pos),
887 return true, S("Punch a node (range=@1, seconds=@2, limit=@3).",
888 range, seconds, limit)
892 core.register_chatcommand("rollback", {
893 params = S("(<name> [<seconds>]) | (:<actor> [<seconds>])"),
894 description = S("Revert actions of a player. "
895 .. "Default for <seconds> is 60. "
896 .. "Set <seconds> to inf for no time limit"),
897 privs = {rollback=true},
898 func = function(name, param)
899 if not core.settings:get_bool("enable_rollback_recording") then
900 return false, S("Rollback functions are disabled.")
902 local target_name, seconds = string.match(param, ":([^ ]+) *(%d*)")
904 if not target_name then
906 player_name, seconds = string.match(param, "([^ ]+) *(%d*)")
907 if not player_name then
908 return false, S("Invalid parameters. "
909 .. "See /help rollback and "
910 .. "/help rollback_check.")
912 seconds = tonumber(seconds) or 60
913 target_name = "player:"..player_name
914 rev_msg = S("Reverting actions of player '@1' since @2 seconds.",
915 player_name, seconds)
917 seconds = tonumber(seconds) or 60
918 rev_msg = S("Reverting actions of @1 since @2 seconds.",
919 target_name, seconds)
921 core.chat_send_player(name, rev_msg)
922 local success, log = core.rollback_revert_actions_by(
923 target_name, seconds)
926 response = S("(log is too long to show)").."\n"
928 for _, line in pairs(log) do
929 response = response .. line .. "\n"
933 response = response .. S("Reverting actions succeeded.")
935 response = response .. S("Reverting actions FAILED.")
937 return success, response
941 core.register_chatcommand("status", {
942 description = S("Show server status"),
943 func = function(name, param)
944 local status = core.get_server_status(name, false)
945 if status and status ~= "" then
948 return false, S("This command was disabled by a mod or game.")
952 core.register_chatcommand("time", {
953 params = S("[<0..23>:<0..59> | <0..24000>]"),
954 description = S("Show or set time of day"),
956 func = function(name, param)
958 local current_time = math.floor(core.get_timeofday() * 1440)
959 local minutes = current_time % 60
960 local hour = (current_time - minutes) / 60
961 return true, S("Current time is @1:@2.",
962 string.format("%d", hour),
963 string.format("%02d", minutes))
965 local player_privs = core.get_player_privs(name)
966 if not player_privs.settime then
967 return false, S("You don't have permission to run "
968 .. "this command (missing privilege: @1).", "settime")
970 local hour, minute = param:match("^(%d+):(%d+)$")
972 local new_time = tonumber(param)
974 return false, S("Invalid time.")
976 -- Backward compatibility.
977 core.set_timeofday((new_time % 24000) / 24000)
978 core.log("action", name .. " sets time to " .. new_time)
979 return true, S("Time of day changed.")
981 hour = tonumber(hour)
982 minute = tonumber(minute)
983 if hour < 0 or hour > 23 then
984 return false, S("Invalid hour (must be between 0 and 23 inclusive).")
985 elseif minute < 0 or minute > 59 then
986 return false, S("Invalid minute (must be between 0 and 59 inclusive).")
988 core.set_timeofday((hour * 60 + minute) / 1440)
989 core.log("action", ("%s sets time to %d:%02d"):format(name, hour, minute))
990 return true, S("Time of day changed.")
994 core.register_chatcommand("days", {
995 description = S("Show day count since world creation"),
996 func = function(name, param)
997 return true, S("Current day is @1.", core.get_day_count())
1001 core.register_chatcommand("shutdown", {
1002 params = S("[<delay_in_seconds> | -1] [reconnect] [<message>]"),
1003 description = S("Shutdown server (-1 cancels a delayed shutdown)"),
1004 privs = {server=true},
1005 func = function(name, param)
1006 local delay, reconnect, message
1007 delay, param = param:match("^%s*(%S+)(.*)")
1009 reconnect, param = param:match("^%s*(%S+)(.*)")
1011 message = param and param:match("^%s*(.+)") or ""
1012 delay = tonumber(delay) or 0
1015 core.log("action", name .. " shuts down server")
1016 core.chat_send_all("*** "..S("Server shutting down (operator request)."))
1018 core.request_shutdown(message:trim(), core.is_yes(reconnect), delay)
1023 core.register_chatcommand("ban", {
1024 params = S("[<name>]"),
1025 description = S("Ban the IP of a player or show the ban list"),
1027 func = function(name, param)
1029 local ban_list = core.get_ban_list()
1030 if ban_list == "" then
1031 return true, S("The ban list is empty.")
1033 return true, S("Ban list: @1", ban_list)
1036 if not core.get_player_by_name(param) then
1037 return false, S("Player is not online.")
1039 if not core.ban_player(param) then
1040 return false, S("Failed to ban player.")
1042 local desc = core.get_ban_description(param)
1043 core.log("action", name .. " bans " .. desc .. ".")
1044 return true, S("Banned @1.", desc)
1048 core.register_chatcommand("unban", {
1049 params = S("<name> | <IP_address>"),
1050 description = S("Remove IP ban belonging to a player/IP"),
1052 func = function(name, param)
1053 if not core.unban_player_or_ip(param) then
1054 return false, S("Failed to unban player/IP.")
1056 core.log("action", name .. " unbans " .. param)
1057 return true, S("Unbanned @1.", param)
1061 core.register_chatcommand("kick", {
1062 params = S("<name> [<reason>]"),
1063 description = S("Kick a player"),
1064 privs = {kick=true},
1065 func = function(name, param)
1066 local tokick, reason = param:match("([^ ]+) (.+)")
1067 tokick = tokick or param
1068 if not core.kick_player(tokick, reason) then
1069 return false, S("Failed to kick player @1.", tokick)
1071 local log_reason = ""
1073 log_reason = " with reason \"" .. reason .. "\""
1075 core.log("action", name .. " kicks " .. tokick .. log_reason)
1076 return true, S("Kicked @1.", tokick)
1080 core.register_chatcommand("clearobjects", {
1081 params = S("[full | quick]"),
1082 description = S("Clear all objects in world"),
1083 privs = {server=true},
1084 func = function(name, param)
1086 if param == "" or param == "quick" then
1087 options.mode = "quick"
1088 elseif param == "full" then
1089 options.mode = "full"
1091 return false, S("Invalid usage, see /help clearobjects.")
1094 core.log("action", name .. " clears objects ("
1095 .. options.mode .. " mode).")
1096 if options.mode == "full" then
1097 core.chat_send_all(S("Clearing all objects. This may take a long time. "
1098 .. "You may experience a timeout. (by @1)", name))
1100 core.clear_objects(options)
1101 core.log("action", "Object clearing done.")
1102 core.chat_send_all("*** "..S("Cleared all objects."))
1107 core.register_chatcommand("msg", {
1108 params = S("<name> <message>"),
1109 description = S("Send a direct message to a player"),
1110 privs = {shout=true},
1111 func = function(name, param)
1112 local sendto, message = param:match("^(%S+)%s(.+)$")
1114 return false, S("Invalid usage, see /help msg.")
1116 if not core.get_player_by_name(sendto) then
1117 return false, S("The player @1 is not online.", sendto)
1119 core.log("action", "DM from " .. name .. " to " .. sendto
1121 core.chat_send_player(sendto, S("DM from @1: @2", name, message))
1122 return true, S("Message sent.")
1126 core.register_chatcommand("last-login", {
1127 params = S("[<name>]"),
1128 description = S("Get the last login time of a player or yourself"),
1129 func = function(name, param)
1133 local pauth = core.get_auth_handler().get_auth(param)
1134 if pauth and pauth.last_login and pauth.last_login ~= -1 then
1135 -- Time in UTC, ISO 8601 format
1136 return true, S("@1's last login time was @2.",
1138 os.date("!%Y-%m-%dT%H:%M:%SZ", pauth.last_login))
1140 return false, S("@1's last login time is unknown.", param)
1144 core.register_chatcommand("clearinv", {
1145 params = S("[<name>]"),
1146 description = S("Clear the inventory of yourself or another player"),
1147 func = function(name, param)
1149 if param and param ~= "" and param ~= name then
1150 if not core.check_player_privs(name, {server=true}) then
1151 return false, S("You don't have permission to "
1152 .. "clear another player's inventory "
1153 .. "(missing privilege: @1).", "server")
1155 player = core.get_player_by_name(param)
1156 core.chat_send_player(param, S("@1 cleared your inventory.", name))
1158 player = core.get_player_by_name(name)
1162 player:get_inventory():set_list("main", {})
1163 player:get_inventory():set_list("craft", {})
1164 player:get_inventory():set_list("craftpreview", {})
1165 core.log("action", name.." clears "..player:get_player_name().."'s inventory")
1166 return true, S("Cleared @1's inventory.", player:get_player_name())
1168 return false, S("Player must be online to clear inventory!")
1173 local function handle_kill_command(killer, victim)
1174 if core.settings:get_bool("enable_damage") == false then
1175 return false, S("Players can't be killed, damage has been disabled.")
1177 local victimref = core.get_player_by_name(victim)
1178 if victimref == nil then
1179 return false, S("Player @1 is not online.", victim)
1180 elseif victimref:get_hp() <= 0 then
1181 if killer == victim then
1182 return false, S("You are already dead.")
1184 return false, S("@1 is already dead.", victim)
1187 if not killer == victim then
1188 core.log("action", string.format("%s killed %s", killer, victim))
1192 return true, S("@1 has been killed.", victim)
1195 core.register_chatcommand("kill", {
1196 params = S("[<name>]"),
1197 description = S("Kill player or yourself"),
1198 privs = {server=true},
1199 func = function(name, param)
1200 return handle_kill_command(name, param == "" and name or param)