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 if #players_with_priv == 0 then
216 return true, S("No online player has the \"@1\" privilege.",
219 return true, S("Players online with the \"@1\" privilege: @2",
221 table.concat(players_with_priv, ", "))
226 local function handle_grant_command(caller, grantname, grantprivstr)
227 local caller_privs = core.get_player_privs(caller)
228 if not (caller_privs.privs or caller_privs.basic_privs) then
229 return false, S("Your privileges are insufficient.")
232 if not core.get_auth_handler().get_auth(grantname) then
233 return false, S("Player @1 does not exist.", grantname)
235 local grantprivs = core.string_to_privs(grantprivstr)
236 if grantprivstr == "all" then
237 grantprivs = core.registered_privileges
239 local privs = core.get_player_privs(grantname)
240 local privs_unknown = ""
242 core.string_to_privs(core.settings:get("basic_privs") or "interact,shout")
243 for priv, _ in pairs(grantprivs) do
244 if not basic_privs[priv] and not caller_privs.privs then
245 return false, S("Your privileges are insufficient. "..
246 "'@1' only allows you to grant: @2",
248 core.privs_to_string(basic_privs, ', '))
250 if not core.registered_privileges[priv] then
251 privs_unknown = privs_unknown .. S("Unknown privilege: @1", priv) .. "\n"
255 if privs_unknown ~= "" then
256 return false, privs_unknown
258 core.set_player_privs(grantname, privs)
259 for priv, _ in pairs(grantprivs) do
260 -- call the on_grant callbacks
261 core.run_priv_callbacks(grantname, priv, caller, "grant")
263 core.log("action", caller..' granted ('..core.privs_to_string(grantprivs, ', ')..') privileges to '..grantname)
264 if grantname ~= caller then
265 core.chat_send_player(grantname,
266 S("@1 granted you privileges: @2", caller,
267 core.privs_to_string(grantprivs, ', ')))
269 return true, privileges_of(grantname)
272 core.register_chatcommand("grant", {
273 params = S("<name> (<privilege> [, <privilege2> [<...>]] | all)"),
274 description = S("Give privileges to player"),
275 func = function(name, param)
276 local grantname, grantprivstr = string.match(param, "([^ ]+) (.+)")
277 if not grantname or not grantprivstr then
278 return false, S("Invalid parameters (see /help grant).")
280 return handle_grant_command(name, grantname, grantprivstr)
284 core.register_chatcommand("grantme", {
285 params = S("<privilege> [, <privilege2> [<...>]] | all"),
286 description = S("Grant privileges to yourself"),
287 func = function(name, param)
289 return false, S("Invalid parameters (see /help grantme).")
291 return handle_grant_command(name, name, param)
295 local function handle_revoke_command(caller, revokename, revokeprivstr)
296 local caller_privs = core.get_player_privs(caller)
297 if not (caller_privs.privs or caller_privs.basic_privs) then
298 return false, S("Your privileges are insufficient.")
301 if not core.get_auth_handler().get_auth(revokename) then
302 return false, S("Player @1 does not exist.", revokename)
305 local privs = core.get_player_privs(revokename)
307 local revokeprivs = core.string_to_privs(revokeprivstr)
308 local is_singleplayer = core.is_singleplayer()
309 local is_admin = not is_singleplayer
310 and revokename == core.settings:get("name")
312 if revokeprivstr == "all" then
316 for priv, _ in pairs(revokeprivs) do
321 local privs_unknown = ""
323 core.string_to_privs(core.settings:get("basic_privs") or "interact,shout")
324 local irrevokable = {}
325 local has_irrevokable_priv = false
326 for priv, _ in pairs(revokeprivs) do
327 if not basic_privs[priv] and not caller_privs.privs then
328 return false, S("Your privileges are insufficient. "..
329 "'@1' only allows you to revoke: @2",
331 core.privs_to_string(basic_privs, ', '))
333 local def = core.registered_privileges[priv]
335 privs_unknown = privs_unknown .. S("Unknown privilege: @1", priv) .. "\n"
336 elseif is_singleplayer and def.give_to_singleplayer then
337 irrevokable[priv] = true
338 elseif is_admin and def.give_to_admin then
339 irrevokable[priv] = true
342 for priv, _ in pairs(irrevokable) do
343 revokeprivs[priv] = nil
344 has_irrevokable_priv = true
346 if privs_unknown ~= "" then
347 return false, privs_unknown
349 if has_irrevokable_priv then
350 if is_singleplayer then
351 core.chat_send_player(caller,
352 S("Note: Cannot revoke in singleplayer: @1",
353 core.privs_to_string(irrevokable, ', ')))
355 core.chat_send_player(caller,
356 S("Note: Cannot revoke from admin: @1",
357 core.privs_to_string(irrevokable, ', ')))
361 local revokecount = 0
363 core.set_player_privs(revokename, privs)
364 for priv, _ in pairs(revokeprivs) do
365 -- call the on_revoke callbacks
366 core.run_priv_callbacks(revokename, priv, caller, "revoke")
367 revokecount = revokecount + 1
369 local new_privs = core.get_player_privs(revokename)
371 if revokecount == 0 then
372 return false, S("No privileges were revoked.")
375 core.log("action", caller..' revoked ('
376 ..core.privs_to_string(revokeprivs, ', ')
377 ..') privileges from '..revokename)
378 if revokename ~= caller then
379 core.chat_send_player(revokename,
380 S("@1 revoked privileges from you: @2", caller,
381 core.privs_to_string(revokeprivs, ', ')))
383 return true, privileges_of(revokename, new_privs)
386 core.register_chatcommand("revoke", {
387 params = S("<name> (<privilege> [, <privilege2> [<...>]] | all)"),
388 description = S("Remove privileges from player"),
390 func = function(name, param)
391 local revokename, revokeprivstr = string.match(param, "([^ ]+) (.+)")
392 if not revokename or not revokeprivstr then
393 return false, S("Invalid parameters (see /help revoke).")
395 return handle_revoke_command(name, revokename, revokeprivstr)
399 core.register_chatcommand("revokeme", {
400 params = S("<privilege> [, <privilege2> [<...>]] | all"),
401 description = S("Revoke privileges from yourself"),
403 func = function(name, param)
405 return false, S("Invalid parameters (see /help revokeme).")
407 return handle_revoke_command(name, name, param)
411 core.register_chatcommand("setpassword", {
412 params = S("<name> <password>"),
413 description = S("Set player's password"),
414 privs = {password=true},
415 func = function(name, param)
416 local toname, raw_password = string.match(param, "^([^ ]+) +(.+)$")
418 toname = param:match("^([^ ]+) *$")
423 return false, S("Name field required.")
426 local msg_chat, msg_log, msg_ret
427 if not raw_password then
428 core.set_player_password(toname, "")
429 msg_chat = S("Your password was cleared by @1.", name)
430 msg_log = name .. " clears password of " .. toname .. "."
431 msg_ret = S("Password of player \"@1\" cleared.", toname)
433 core.set_player_password(toname,
434 core.get_password_hash(toname,
436 msg_chat = S("Your password was set by @1.", name)
437 msg_log = name .. " sets password of " .. toname .. "."
438 msg_ret = S("Password of player \"@1\" set.", toname)
441 if toname ~= name then
442 core.chat_send_player(toname, msg_chat)
445 core.log("action", msg_log)
451 core.register_chatcommand("clearpassword", {
452 params = S("<name>"),
453 description = S("Set empty password for a player"),
454 privs = {password=true},
455 func = function(name, param)
458 return false, S("Name field required.")
460 core.set_player_password(toname, '')
462 core.log("action", name .. " clears password of " .. toname .. ".")
464 return true, S("Password of player \"@1\" cleared.", toname)
468 core.register_chatcommand("auth_reload", {
470 description = S("Reload authentication data"),
471 privs = {server=true},
472 func = function(name, param)
473 local done = core.auth_reload()
474 return done, (done and S("Done.") or S("Failed."))
478 core.register_chatcommand("remove_player", {
479 params = S("<name>"),
480 description = S("Remove a player's data"),
481 privs = {server=true},
482 func = function(name, param)
485 return false, S("Name field required.")
488 local rc = core.remove_player(toname)
491 core.log("action", name .. " removed player data of " .. toname .. ".")
492 return true, S("Player \"@1\" removed.", toname)
494 return true, S("No such player \"@1\" to remove.", toname)
496 return true, S("Player \"@1\" is connected, cannot remove.", toname)
499 return false, S("Unhandled remove_player return code @1.", tostring(rc))
504 -- pos may be a non-integer position
505 local function find_free_position_near(pos)
507 vector.new( 1, 0, 0),
508 vector.new(-1, 0, 0),
509 vector.new( 0, 0, 1),
510 vector.new( 0, 0, -1),
512 for _, d in ipairs(tries) do
513 local p = vector.add(pos, d)
514 local n = core.get_node_or_nil(p)
516 local def = core.registered_nodes[n.name]
517 if def and not def.walkable then
525 -- Teleports player <name> to <p> if possible
526 local function teleport_to_pos(name, p)
527 local lm = 31007 -- equals MAX_MAP_GENERATION_LIMIT in C++
528 if p.x < -lm or p.x > lm or p.y < -lm or p.y > lm
529 or p.z < -lm or p.z > lm then
530 return false, S("Cannot teleport out of map bounds!")
532 local teleportee = core.get_player_by_name(name)
533 if not teleportee then
534 return false, S("Cannot get player with name @1.", name)
536 if teleportee:get_attach() then
537 return false, S("Cannot teleport, @1 " ..
538 "is attached to an object!", name)
540 teleportee:set_pos(p)
541 return true, S("Teleporting @1 to @2.", name, core.pos_to_string(p, 1))
544 -- Teleports player <name> next to player <target_name> if possible
545 local function teleport_to_player(name, target_name)
546 if name == target_name then
547 return false, S("One does not teleport to oneself.")
549 local teleportee = core.get_player_by_name(name)
550 if not teleportee then
551 return false, S("Cannot get teleportee with name @1.", name)
553 if teleportee:get_attach() then
554 return false, S("Cannot teleport, @1 " ..
555 "is attached to an object!", name)
557 local target = core.get_player_by_name(target_name)
559 return false, S("Cannot get target player with name @1.", target_name)
561 local p = find_free_position_near(target:get_pos())
562 teleportee:set_pos(p)
563 return true, S("Teleporting @1 to @2 at @3.", name, target_name,
564 core.pos_to_string(p, 1))
567 core.register_chatcommand("teleport", {
568 params = S("<X>,<Y>,<Z> | <to_name> | <name> <X>,<Y>,<Z> | <name> <to_name>"),
569 description = S("Teleport to position or player"),
570 privs = {teleport=true},
571 func = function(name, param)
573 p.x, p.y, p.z = param:match("^([%d.-]+)[, ] *([%d.-]+)[, ] *([%d.-]+)$")
574 p = vector.apply(p, tonumber)
575 if p.x and p.y and p.z then
576 return teleport_to_pos(name, p)
579 local target_name = param:match("^([^ ]+)$")
581 return teleport_to_player(name, target_name)
584 local has_bring_priv = core.check_player_privs(name, {bring=true})
585 local missing_bring_msg = S("You don't have permission to teleport " ..
586 "other players (missing privilege: @1).", "bring")
588 local teleportee_name
589 teleportee_name, p.x, p.y, p.z = param:match(
590 "^([^ ]+) +([%d.-]+)[, ] *([%d.-]+)[, ] *([%d.-]+)$")
591 p = vector.apply(p, tonumber)
592 if teleportee_name and p.x and p.y and p.z then
593 if not has_bring_priv then
594 return false, missing_bring_msg
596 return teleport_to_pos(teleportee_name, p)
599 teleportee_name, target_name = string.match(param, "^([^ ]+) +([^ ]+)$")
600 if teleportee_name and target_name then
601 if not has_bring_priv then
602 return false, missing_bring_msg
604 return teleport_to_player(teleportee_name, target_name)
611 core.register_chatcommand("set", {
612 params = S("([-n] <name> <value>) | <name>"),
613 description = S("Set or read server configuration setting"),
614 privs = {server=true},
615 func = function(name, param)
616 local arg, setname, setvalue = string.match(param, "(-[n]) ([^ ]+) (.+)")
617 if arg and arg == "-n" and setname and setvalue then
618 core.settings:set(setname, setvalue)
619 return true, setname .. " = " .. setvalue
622 setname, setvalue = string.match(param, "([^ ]+) (.+)")
623 if setname and setvalue then
624 if not core.settings:get(setname) then
625 return false, S("Failed. Use '/set -n <name> <value>' "
626 .. "to create a new setting.")
628 core.settings:set(setname, setvalue)
629 return true, S("@1 = @2", setname, setvalue)
632 setname = string.match(param, "([^ ]+)")
634 setvalue = core.settings:get(setname)
636 setvalue = S("<not set>")
638 return true, S("@1 = @2", setname, setvalue)
641 return false, S("Invalid parameters (see /help set).")
645 local function emergeblocks_callback(pos, action, num_calls_remaining, ctx)
646 if ctx.total_blocks == 0 then
647 ctx.total_blocks = num_calls_remaining + 1
648 ctx.current_blocks = 0
650 ctx.current_blocks = ctx.current_blocks + 1
652 if ctx.current_blocks == ctx.total_blocks then
653 core.chat_send_player(ctx.requestor_name,
654 S("Finished emerging @1 blocks in @2ms.",
656 string.format("%.2f", (os.clock() - ctx.start_time) * 1000)))
660 local function emergeblocks_progress_update(ctx)
661 if ctx.current_blocks ~= ctx.total_blocks then
662 core.chat_send_player(ctx.requestor_name,
663 S("emergeblocks update: @1/@2 blocks emerged (@3%)",
664 ctx.current_blocks, ctx.total_blocks,
665 string.format("%.1f", (ctx.current_blocks / ctx.total_blocks) * 100)))
667 core.after(2, emergeblocks_progress_update, ctx)
671 core.register_chatcommand("emergeblocks", {
672 params = S("(here [<radius>]) | (<pos1> <pos2>)"),
673 description = S("Load (or, if nonexistent, generate) map blocks contained in "
674 .. "area pos1 to pos2 (<pos1> and <pos2> must be in parentheses)"),
675 privs = {server=true},
676 func = function(name, param)
677 local p1, p2 = parse_range_str(name, param)
685 start_time = os.clock(),
686 requestor_name = name
689 core.emerge_area(p1, p2, emergeblocks_callback, context)
690 core.after(2, emergeblocks_progress_update, context)
692 return true, S("Started emerge of area ranging from @1 to @2.",
693 core.pos_to_string(p1, 1), core.pos_to_string(p2, 1))
697 core.register_chatcommand("deleteblocks", {
698 params = S("(here [<radius>]) | (<pos1> <pos2>)"),
699 description = S("Delete map blocks contained in area pos1 to pos2 "
700 .. "(<pos1> and <pos2> must be in parentheses)"),
701 privs = {server=true},
702 func = function(name, param)
703 local p1, p2 = parse_range_str(name, param)
708 if core.delete_area(p1, p2) then
709 return true, S("Successfully cleared area "
710 .. "ranging from @1 to @2.",
711 core.pos_to_string(p1, 1), core.pos_to_string(p2, 1))
713 return false, S("Failed to clear one or more "
714 .. "blocks in area.")
719 core.register_chatcommand("fixlight", {
720 params = S("(here [<radius>]) | (<pos1> <pos2>)"),
721 description = S("Resets lighting in the area between pos1 and pos2 "
722 .. "(<pos1> and <pos2> must be in parentheses)"),
723 privs = {server = true},
724 func = function(name, param)
725 local p1, p2 = parse_range_str(name, param)
730 if core.fix_light(p1, p2) then
731 return true, S("Successfully reset light in the area "
732 .. "ranging from @1 to @2.",
733 core.pos_to_string(p1, 1), core.pos_to_string(p2, 1))
735 return false, S("Failed to load one or more blocks in area.")
740 core.register_chatcommand("mods", {
742 description = S("List mods installed on the server"),
744 func = function(name, param)
745 local mods = core.get_modnames()
747 return true, S("No mods installed.")
749 return true, table.concat(core.get_modnames(), ", ")
754 local function handle_give_command(cmd, giver, receiver, stackstring)
755 core.log("action", giver .. " invoked " .. cmd
756 .. ', stackstring="' .. stackstring .. '"')
757 local itemstack = ItemStack(stackstring)
758 if itemstack:is_empty() then
759 return false, S("Cannot give an empty item.")
760 elseif (not itemstack:is_known()) or (itemstack:get_name() == "unknown") then
761 return false, S("Cannot give an unknown item.")
762 -- Forbid giving 'ignore' due to unwanted side effects
763 elseif itemstack:get_name() == "ignore" then
764 return false, S("Giving 'ignore' is not allowed.")
766 local receiverref = core.get_player_by_name(receiver)
767 if receiverref == nil then
768 return false, S("@1 is not a known player.", receiver)
770 local leftover = receiverref:get_inventory():add_item("main", itemstack)
772 if leftover:is_empty() then
774 elseif leftover:get_count() == itemstack:get_count() then
779 -- The actual item stack string may be different from what the "giver"
780 -- entered (e.g. big numbers are always interpreted as 2^16-1).
781 stackstring = itemstack:to_string()
783 if partiality == true then
784 msg = S("@1 partially added to inventory.", stackstring)
785 elseif partiality == false then
786 msg = S("@1 could not be added to inventory.", stackstring)
788 msg = S("@1 added to inventory.", stackstring)
790 if giver == receiver then
793 core.chat_send_player(receiver, msg)
795 if partiality == true then
796 msg_other = S("@1 partially added to inventory of @2.",
797 stackstring, receiver)
798 elseif partiality == false then
799 msg_other = S("@1 could not be added to inventory of @2.",
800 stackstring, receiver)
802 msg_other = S("@1 added to inventory of @2.",
803 stackstring, receiver)
805 return true, msg_other
809 core.register_chatcommand("give", {
810 params = S("<name> <ItemString> [<count> [<wear>]]"),
811 description = S("Give item to player"),
813 func = function(name, param)
814 local toname, itemstring = string.match(param, "^([^ ]+) +(.+)$")
815 if not toname or not itemstring then
816 return false, S("Name and ItemString required.")
818 return handle_give_command("/give", name, toname, itemstring)
822 core.register_chatcommand("giveme", {
823 params = S("<ItemString> [<count> [<wear>]]"),
824 description = S("Give item to yourself"),
826 func = function(name, param)
827 local itemstring = string.match(param, "(.+)$")
828 if not itemstring then
829 return false, S("ItemString required.")
831 return handle_give_command("/giveme", name, name, itemstring)
835 core.register_chatcommand("spawnentity", {
836 params = S("<EntityName> [<X>,<Y>,<Z>]"),
837 description = S("Spawn entity at given (or your) position"),
838 privs = {give=true, interact=true},
839 func = function(name, param)
840 local entityname, p = string.match(param, "^([^ ]+) *(.*)$")
841 if not entityname then
842 return false, S("EntityName required.")
844 core.log("action", ("%s invokes /spawnentity, entityname=%q")
845 :format(name, entityname))
846 local player = core.get_player_by_name(name)
847 if player == nil then
848 core.log("error", "Unable to spawn entity, player is nil")
849 return false, S("Unable to spawn entity, player is nil.")
851 if not core.registered_entities[entityname] then
852 return false, S("Cannot spawn an unknown entity.")
857 p = core.string_to_pos(p)
859 return false, S("Invalid parameters (@1).", param)
863 local obj = core.add_entity(p, entityname)
865 return true, S("@1 spawned.", entityname)
867 return true, S("@1 failed to spawn.", entityname)
872 core.register_chatcommand("pulverize", {
874 description = S("Destroy item in hand"),
875 func = function(name, param)
876 local player = core.get_player_by_name(name)
878 core.log("error", "Unable to pulverize, no player.")
879 return false, S("Unable to pulverize, no player.")
881 local wielded_item = player:get_wielded_item()
882 if wielded_item:is_empty() then
883 return false, S("Unable to pulverize, no item in hand.")
885 core.log("action", name .. " pulverized \"" ..
886 wielded_item:get_name() .. " " .. wielded_item:get_count() .. "\"")
887 player:set_wielded_item(nil)
888 return true, S("An item was pulverized.")
893 core.rollback_punch_callbacks = {}
895 core.register_on_punchnode(function(pos, node, puncher)
896 local name = puncher and puncher:get_player_name()
897 if name and core.rollback_punch_callbacks[name] then
898 core.rollback_punch_callbacks[name](pos, node, puncher)
899 core.rollback_punch_callbacks[name] = nil
903 core.register_chatcommand("rollback_check", {
904 params = S("[<range>] [<seconds>] [<limit>]"),
905 description = S("Check who last touched a node or a node near it "
906 .. "within the time specified by <seconds>. "
907 .. "Default: range = 0, seconds = 86400 = 24h, limit = 5. "
908 .. "Set <seconds> to inf for no time limit"),
909 privs = {rollback=true},
910 func = function(name, param)
911 if not core.settings:get_bool("enable_rollback_recording") then
912 return false, S("Rollback functions are disabled.")
914 local range, seconds, limit =
915 param:match("(%d+) *(%d*) *(%d*)")
916 range = tonumber(range) or 0
917 seconds = tonumber(seconds) or 86400
918 limit = tonumber(limit) or 5
920 return false, S("That limit is too high!")
923 core.rollback_punch_callbacks[name] = function(pos, node, puncher)
924 local name = puncher:get_player_name()
925 core.chat_send_player(name, S("Checking @1 ...", core.pos_to_string(pos)))
926 local actions = core.rollback_get_node_actions(pos, range, seconds, limit)
928 core.chat_send_player(name, S("Rollback functions are disabled."))
931 local num_actions = #actions
932 if num_actions == 0 then
933 core.chat_send_player(name,
934 S("Nobody has touched the specified "
935 .. "location in @1 seconds.",
939 local time = os.time()
940 for i = num_actions, 1, -1 do
941 local action = actions[i]
942 core.chat_send_player(name,
943 S("@1 @2 @3 -> @4 @5 seconds ago.",
944 core.pos_to_string(action.pos),
952 return true, S("Punch a node (range=@1, seconds=@2, limit=@3).",
953 range, seconds, limit)
957 core.register_chatcommand("rollback", {
958 params = S("(<name> [<seconds>]) | (:<actor> [<seconds>])"),
959 description = S("Revert actions of a player. "
960 .. "Default for <seconds> is 60. "
961 .. "Set <seconds> to inf for no time limit"),
962 privs = {rollback=true},
963 func = function(name, param)
964 if not core.settings:get_bool("enable_rollback_recording") then
965 return false, S("Rollback functions are disabled.")
967 local target_name, seconds = string.match(param, ":([^ ]+) *(%d*)")
969 if not target_name then
971 player_name, seconds = string.match(param, "([^ ]+) *(%d*)")
972 if not player_name then
973 return false, S("Invalid parameters. "
974 .. "See /help rollback and "
975 .. "/help rollback_check.")
977 seconds = tonumber(seconds) or 60
978 target_name = "player:"..player_name
979 rev_msg = S("Reverting actions of player '@1' since @2 seconds.",
980 player_name, seconds)
982 seconds = tonumber(seconds) or 60
983 rev_msg = S("Reverting actions of @1 since @2 seconds.",
984 target_name, seconds)
986 core.chat_send_player(name, rev_msg)
987 local success, log = core.rollback_revert_actions_by(
988 target_name, seconds)
991 response = S("(log is too long to show)").."\n"
993 for _, line in pairs(log) do
994 response = response .. line .. "\n"
998 response = response .. S("Reverting actions succeeded.")
1000 response = response .. S("Reverting actions FAILED.")
1002 return success, response
1006 core.register_chatcommand("status", {
1007 description = S("Show server status"),
1008 func = function(name, param)
1009 local status = core.get_server_status(name, false)
1010 if status and status ~= "" then
1013 return false, S("This command was disabled by a mod or game.")
1017 core.register_chatcommand("time", {
1018 params = S("[<0..23>:<0..59> | <0..24000>]"),
1019 description = S("Show or set time of day"),
1021 func = function(name, param)
1023 local current_time = math.floor(core.get_timeofday() * 1440)
1024 local minutes = current_time % 60
1025 local hour = (current_time - minutes) / 60
1026 return true, S("Current time is @1:@2.",
1027 string.format("%d", hour),
1028 string.format("%02d", minutes))
1030 local player_privs = core.get_player_privs(name)
1031 if not player_privs.settime then
1032 return false, S("You don't have permission to run "
1033 .. "this command (missing privilege: @1).", "settime")
1035 local hour, minute = param:match("^(%d+):(%d+)$")
1037 local new_time = tonumber(param) or -1
1038 if new_time ~= new_time or new_time < 0 or new_time > 24000 then
1039 return false, S("Invalid time (must be between 0 and 24000).")
1041 core.set_timeofday(new_time / 24000)
1042 core.log("action", name .. " sets time to " .. new_time)
1043 return true, S("Time of day changed.")
1045 hour = tonumber(hour)
1046 minute = tonumber(minute)
1047 if hour < 0 or hour > 23 then
1048 return false, S("Invalid hour (must be between 0 and 23 inclusive).")
1049 elseif minute < 0 or minute > 59 then
1050 return false, S("Invalid minute (must be between 0 and 59 inclusive).")
1052 core.set_timeofday((hour * 60 + minute) / 1440)
1053 core.log("action", ("%s sets time to %d:%02d"):format(name, hour, minute))
1054 return true, S("Time of day changed.")
1058 core.register_chatcommand("days", {
1059 description = S("Show day count since world creation"),
1060 func = function(name, param)
1061 return true, S("Current day is @1.", core.get_day_count())
1065 local function parse_shutdown_param(param)
1066 local delay, reconnect, message
1067 local one, two, three
1068 one, two, three = param:match("^(%S+) +(%-r) +(.*)")
1069 if one and two and three then
1070 -- 3 arguments: delay, reconnect and message
1071 return one, two, three
1074 one, two = param:match("^(%S+) +(.*)")
1076 if tonumber(one) then
1083 elseif one == "-r" then
1084 reconnect, message = one, two
1086 return delay, reconnect, message
1089 one = param:match("(.*)")
1090 if tonumber(one) then
1092 elseif one == "-r" then
1097 return delay, reconnect, message
1100 core.register_chatcommand("shutdown", {
1101 params = S("[<delay_in_seconds> | -1] [-r] [<message>]"),
1102 description = S("Shutdown server (-1 cancels a delayed shutdown, -r allows players to reconnect)"),
1103 privs = {server=true},
1104 func = function(name, param)
1105 local delay, reconnect, message = parse_shutdown_param(param)
1106 local bool_reconnect = reconnect == "-r"
1110 delay = tonumber(delay) or 0
1113 core.log("action", name .. " shuts down server")
1114 core.chat_send_all("*** "..S("Server shutting down (operator request)."))
1116 core.request_shutdown(message:trim(), bool_reconnect, delay)
1121 core.register_chatcommand("ban", {
1122 params = S("[<name>]"),
1123 description = S("Ban the IP of a player or show the ban list"),
1125 func = function(name, param)
1127 local ban_list = core.get_ban_list()
1128 if ban_list == "" then
1129 return true, S("The ban list is empty.")
1131 return true, S("Ban list: @1", ban_list)
1134 if not core.get_player_by_name(param) then
1135 return false, S("Player is not online.")
1137 if not core.ban_player(param) then
1138 return false, S("Failed to ban player.")
1140 local desc = core.get_ban_description(param)
1141 core.log("action", name .. " bans " .. desc .. ".")
1142 return true, S("Banned @1.", desc)
1146 core.register_chatcommand("unban", {
1147 params = S("<name> | <IP_address>"),
1148 description = S("Remove IP ban belonging to a player/IP"),
1150 func = function(name, param)
1151 if not core.unban_player_or_ip(param) then
1152 return false, S("Failed to unban player/IP.")
1154 core.log("action", name .. " unbans " .. param)
1155 return true, S("Unbanned @1.", param)
1159 core.register_chatcommand("kick", {
1160 params = S("<name> [<reason>]"),
1161 description = S("Kick a player"),
1162 privs = {kick=true},
1163 func = function(name, param)
1164 local tokick, reason = param:match("([^ ]+) (.+)")
1165 tokick = tokick or param
1166 if not core.kick_player(tokick, reason) then
1167 return false, S("Failed to kick player @1.", tokick)
1169 local log_reason = ""
1171 log_reason = " with reason \"" .. reason .. "\""
1173 core.log("action", name .. " kicks " .. tokick .. log_reason)
1174 return true, S("Kicked @1.", tokick)
1178 core.register_chatcommand("clearobjects", {
1179 params = S("[full | quick]"),
1180 description = S("Clear all objects in world"),
1181 privs = {server=true},
1182 func = function(name, param)
1184 if param == "" or param == "quick" then
1185 options.mode = "quick"
1186 elseif param == "full" then
1187 options.mode = "full"
1189 return false, S("Invalid usage, see /help clearobjects.")
1192 core.log("action", name .. " clears objects ("
1193 .. options.mode .. " mode).")
1194 if options.mode == "full" then
1195 core.chat_send_all(S("Clearing all objects. This may take a long time. "
1196 .. "You may experience a timeout. (by @1)", name))
1198 core.clear_objects(options)
1199 core.log("action", "Object clearing done.")
1200 core.chat_send_all("*** "..S("Cleared all objects."))
1205 core.register_chatcommand("msg", {
1206 params = S("<name> <message>"),
1207 description = S("Send a direct message to a player"),
1208 privs = {shout=true},
1209 func = function(name, param)
1210 local sendto, message = param:match("^(%S+)%s(.+)$")
1212 return false, S("Invalid usage, see /help msg.")
1214 if not core.get_player_by_name(sendto) then
1215 return false, S("The player @1 is not online.", sendto)
1217 core.log("action", "DM from " .. name .. " to " .. sendto
1219 core.chat_send_player(sendto, S("DM from @1: @2", name, message))
1220 return true, S("Message sent.")
1224 core.register_chatcommand("last-login", {
1225 params = S("[<name>]"),
1226 description = S("Get the last login time of a player or yourself"),
1227 func = function(name, param)
1231 local pauth = core.get_auth_handler().get_auth(param)
1232 if pauth and pauth.last_login and pauth.last_login ~= -1 then
1233 -- Time in UTC, ISO 8601 format
1234 return true, S("@1's last login time was @2.",
1236 os.date("!%Y-%m-%dT%H:%M:%SZ", pauth.last_login))
1238 return false, S("@1's last login time is unknown.", param)
1242 core.register_chatcommand("clearinv", {
1243 params = S("[<name>]"),
1244 description = S("Clear the inventory of yourself or another player"),
1245 func = function(name, param)
1247 if param and param ~= "" and param ~= name then
1248 if not core.check_player_privs(name, {server=true}) then
1249 return false, S("You don't have permission to "
1250 .. "clear another player's inventory "
1251 .. "(missing privilege: @1).", "server")
1253 player = core.get_player_by_name(param)
1254 core.chat_send_player(param, S("@1 cleared your inventory.", name))
1256 player = core.get_player_by_name(name)
1260 player:get_inventory():set_list("main", {})
1261 player:get_inventory():set_list("craft", {})
1262 player:get_inventory():set_list("craftpreview", {})
1263 core.log("action", name.." clears "..player:get_player_name().."'s inventory")
1264 return true, S("Cleared @1's inventory.", player:get_player_name())
1266 return false, S("Player must be online to clear inventory!")
1271 local function handle_kill_command(killer, victim)
1272 if core.settings:get_bool("enable_damage") == false then
1273 return false, S("Players can't be killed, damage has been disabled.")
1275 local victimref = core.get_player_by_name(victim)
1276 if victimref == nil then
1277 return false, S("Player @1 is not online.", victim)
1278 elseif victimref:get_hp() <= 0 then
1279 if killer == victim then
1280 return false, S("You are already dead.")
1282 return false, S("@1 is already dead.", victim)
1285 if not killer == victim then
1286 core.log("action", string.format("%s killed %s", killer, victim))
1290 return true, S("@1 has been killed.", victim)
1293 core.register_chatcommand("kill", {
1294 params = S("[<name>]"),
1295 description = S("Kill player or yourself"),
1296 privs = {server=true},
1297 func = function(name, param)
1298 return handle_kill_command(name, param == "" and name or param)