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
313 revokeprivs = table.copy(privs)
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 -- Old/removed privileges might still be granted to certain players
331 if not privs[priv] then
332 privs_unknown = privs_unknown .. S("Unknown privilege: @1", priv) .. "\n"
334 elseif is_singleplayer and def.give_to_singleplayer then
335 irrevokable[priv] = true
336 elseif is_admin and def.give_to_admin then
337 irrevokable[priv] = true
340 for priv, _ in pairs(irrevokable) do
341 revokeprivs[priv] = nil
342 has_irrevokable_priv = true
344 if privs_unknown ~= "" then
345 return false, privs_unknown
347 if has_irrevokable_priv then
348 if is_singleplayer then
349 core.chat_send_player(caller,
350 S("Note: Cannot revoke in singleplayer: @1",
351 core.privs_to_string(irrevokable, ', ')))
353 core.chat_send_player(caller,
354 S("Note: Cannot revoke from admin: @1",
355 core.privs_to_string(irrevokable, ', ')))
359 local revokecount = 0
360 for priv, _ in pairs(revokeprivs) do
362 revokecount = revokecount + 1
365 if revokecount == 0 then
366 return false, S("No privileges were revoked.")
369 core.set_player_privs(revokename, privs)
370 for priv, _ in pairs(revokeprivs) do
371 -- call the on_revoke callbacks
372 core.run_priv_callbacks(revokename, priv, caller, "revoke")
374 local new_privs = core.get_player_privs(revokename)
376 core.log("action", caller..' revoked ('
377 ..core.privs_to_string(revokeprivs, ', ')
378 ..') privileges from '..revokename)
379 if revokename ~= caller then
380 core.chat_send_player(revokename,
381 S("@1 revoked privileges from you: @2", caller,
382 core.privs_to_string(revokeprivs, ', ')))
384 return true, privileges_of(revokename, new_privs)
387 core.register_chatcommand("revoke", {
388 params = S("<name> (<privilege> [, <privilege2> [<...>]] | all)"),
389 description = S("Remove privileges from player"),
391 func = function(name, param)
392 local revokename, revokeprivstr = string.match(param, "([^ ]+) (.+)")
393 if not revokename or not revokeprivstr then
394 return false, S("Invalid parameters (see /help revoke).")
396 return handle_revoke_command(name, revokename, revokeprivstr)
400 core.register_chatcommand("revokeme", {
401 params = S("<privilege> [, <privilege2> [<...>]] | all"),
402 description = S("Revoke privileges from yourself"),
404 func = function(name, param)
406 return false, S("Invalid parameters (see /help revokeme).")
408 return handle_revoke_command(name, name, param)
412 core.register_chatcommand("setpassword", {
413 params = S("<name> <password>"),
414 description = S("Set player's password"),
415 privs = {password=true},
416 func = function(name, param)
417 local toname, raw_password = string.match(param, "^([^ ]+) +(.+)$")
419 toname = param:match("^([^ ]+) *$")
424 return false, S("Name field required.")
427 local msg_chat, msg_log, msg_ret
428 if not raw_password then
429 core.set_player_password(toname, "")
430 msg_chat = S("Your password was cleared by @1.", name)
431 msg_log = name .. " clears password of " .. toname .. "."
432 msg_ret = S("Password of player \"@1\" cleared.", toname)
434 core.set_player_password(toname,
435 core.get_password_hash(toname,
437 msg_chat = S("Your password was set by @1.", name)
438 msg_log = name .. " sets password of " .. toname .. "."
439 msg_ret = S("Password of player \"@1\" set.", toname)
442 if toname ~= name then
443 core.chat_send_player(toname, msg_chat)
446 core.log("action", msg_log)
452 core.register_chatcommand("clearpassword", {
453 params = S("<name>"),
454 description = S("Set empty password for a player"),
455 privs = {password=true},
456 func = function(name, param)
459 return false, S("Name field required.")
461 core.set_player_password(toname, '')
463 core.log("action", name .. " clears password of " .. toname .. ".")
465 return true, S("Password of player \"@1\" cleared.", toname)
469 core.register_chatcommand("auth_reload", {
471 description = S("Reload authentication data"),
472 privs = {server=true},
473 func = function(name, param)
474 local done = core.auth_reload()
475 return done, (done and S("Done.") or S("Failed."))
479 core.register_chatcommand("remove_player", {
480 params = S("<name>"),
481 description = S("Remove a player's data"),
482 privs = {server=true},
483 func = function(name, param)
486 return false, S("Name field required.")
489 local rc = core.remove_player(toname)
492 core.log("action", name .. " removed player data of " .. toname .. ".")
493 return true, S("Player \"@1\" removed.", toname)
495 return true, S("No such player \"@1\" to remove.", toname)
497 return true, S("Player \"@1\" is connected, cannot remove.", toname)
500 return false, S("Unhandled remove_player return code @1.", tostring(rc))
505 -- pos may be a non-integer position
506 local function find_free_position_near(pos)
508 vector.new( 1, 0, 0),
509 vector.new(-1, 0, 0),
510 vector.new( 0, 0, 1),
511 vector.new( 0, 0, -1),
513 for _, d in ipairs(tries) do
514 local p = vector.add(pos, d)
515 local n = core.get_node_or_nil(p)
517 local def = core.registered_nodes[n.name]
518 if def and not def.walkable then
526 -- Teleports player <name> to <p> if possible
527 local function teleport_to_pos(name, p)
528 local lm = 31007 -- equals MAX_MAP_GENERATION_LIMIT in C++
529 if p.x < -lm or p.x > lm or p.y < -lm or p.y > lm
530 or p.z < -lm or p.z > lm then
531 return false, S("Cannot teleport out of map bounds!")
533 local teleportee = core.get_player_by_name(name)
534 if not teleportee then
535 return false, S("Cannot get player with name @1.", name)
537 if teleportee:get_attach() then
538 return false, S("Cannot teleport, @1 " ..
539 "is attached to an object!", name)
541 teleportee:set_pos(p)
542 return true, S("Teleporting @1 to @2.", name, core.pos_to_string(p, 1))
545 -- Teleports player <name> next to player <target_name> if possible
546 local function teleport_to_player(name, target_name)
547 if name == target_name then
548 return false, S("One does not teleport to oneself.")
550 local teleportee = core.get_player_by_name(name)
551 if not teleportee then
552 return false, S("Cannot get teleportee with name @1.", name)
554 if teleportee:get_attach() then
555 return false, S("Cannot teleport, @1 " ..
556 "is attached to an object!", name)
558 local target = core.get_player_by_name(target_name)
560 return false, S("Cannot get target player with name @1.", target_name)
562 local p = find_free_position_near(target:get_pos())
563 teleportee:set_pos(p)
564 return true, S("Teleporting @1 to @2 at @3.", name, target_name,
565 core.pos_to_string(p, 1))
568 core.register_chatcommand("teleport", {
569 params = S("<X>,<Y>,<Z> | <to_name> | <name> <X>,<Y>,<Z> | <name> <to_name>"),
570 description = S("Teleport to position or player"),
571 privs = {teleport=true},
572 func = function(name, param)
574 p.x, p.y, p.z = param:match("^([%d.-]+)[, ] *([%d.-]+)[, ] *([%d.-]+)$")
575 p = vector.apply(p, tonumber)
576 if p.x and p.y and p.z then
577 return teleport_to_pos(name, p)
580 local target_name = param:match("^([^ ]+)$")
582 return teleport_to_player(name, target_name)
585 local has_bring_priv = core.check_player_privs(name, {bring=true})
586 local missing_bring_msg = S("You don't have permission to teleport " ..
587 "other players (missing privilege: @1).", "bring")
589 local teleportee_name
590 teleportee_name, p.x, p.y, p.z = param:match(
591 "^([^ ]+) +([%d.-]+)[, ] *([%d.-]+)[, ] *([%d.-]+)$")
592 p = vector.apply(p, tonumber)
593 if teleportee_name and p.x and p.y and p.z then
594 if not has_bring_priv then
595 return false, missing_bring_msg
597 return teleport_to_pos(teleportee_name, p)
600 teleportee_name, target_name = string.match(param, "^([^ ]+) +([^ ]+)$")
601 if teleportee_name and target_name then
602 if not has_bring_priv then
603 return false, missing_bring_msg
605 return teleport_to_player(teleportee_name, target_name)
612 core.register_chatcommand("set", {
613 params = S("([-n] <name> <value>) | <name>"),
614 description = S("Set or read server configuration setting"),
615 privs = {server=true},
616 func = function(name, param)
617 local arg, setname, setvalue = string.match(param, "(-[n]) ([^ ]+) (.+)")
618 if arg and arg == "-n" and setname and setvalue then
619 core.settings:set(setname, setvalue)
620 return true, setname .. " = " .. setvalue
623 setname, setvalue = string.match(param, "([^ ]+) (.+)")
624 if setname and setvalue then
625 if setname:sub(1, 7) == "secure." then
626 return false, S("Failed. Cannot modify secure settings. "
627 .. "Edit the settings file manually.")
629 if not core.settings:get(setname) then
630 return false, S("Failed. Use '/set -n <name> <value>' "
631 .. "to create a new setting.")
633 core.settings:set(setname, setvalue)
634 return true, S("@1 = @2", setname, setvalue)
637 setname = string.match(param, "([^ ]+)")
639 setvalue = core.settings:get(setname)
641 setvalue = S("<not set>")
643 return true, S("@1 = @2", setname, setvalue)
646 return false, S("Invalid parameters (see /help set).")
650 local function emergeblocks_callback(pos, action, num_calls_remaining, ctx)
651 if ctx.total_blocks == 0 then
652 ctx.total_blocks = num_calls_remaining + 1
653 ctx.current_blocks = 0
655 ctx.current_blocks = ctx.current_blocks + 1
657 if ctx.current_blocks == ctx.total_blocks then
658 core.chat_send_player(ctx.requestor_name,
659 S("Finished emerging @1 blocks in @2ms.",
661 string.format("%.2f", (os.clock() - ctx.start_time) * 1000)))
665 local function emergeblocks_progress_update(ctx)
666 if ctx.current_blocks ~= ctx.total_blocks then
667 core.chat_send_player(ctx.requestor_name,
668 S("emergeblocks update: @1/@2 blocks emerged (@3%)",
669 ctx.current_blocks, ctx.total_blocks,
670 string.format("%.1f", (ctx.current_blocks / ctx.total_blocks) * 100)))
672 core.after(2, emergeblocks_progress_update, ctx)
676 core.register_chatcommand("emergeblocks", {
677 params = S("(here [<radius>]) | (<pos1> <pos2>)"),
678 description = S("Load (or, if nonexistent, generate) map blocks contained in "
679 .. "area pos1 to pos2 (<pos1> and <pos2> must be in parentheses)"),
680 privs = {server=true},
681 func = function(name, param)
682 local p1, p2 = parse_range_str(name, param)
690 start_time = os.clock(),
691 requestor_name = name
694 core.emerge_area(p1, p2, emergeblocks_callback, context)
695 core.after(2, emergeblocks_progress_update, context)
697 return true, S("Started emerge of area ranging from @1 to @2.",
698 core.pos_to_string(p1, 1), core.pos_to_string(p2, 1))
702 core.register_chatcommand("deleteblocks", {
703 params = S("(here [<radius>]) | (<pos1> <pos2>)"),
704 description = S("Delete map blocks contained in area pos1 to pos2 "
705 .. "(<pos1> and <pos2> must be in parentheses)"),
706 privs = {server=true},
707 func = function(name, param)
708 local p1, p2 = parse_range_str(name, param)
713 if core.delete_area(p1, p2) then
714 return true, S("Successfully cleared area "
715 .. "ranging from @1 to @2.",
716 core.pos_to_string(p1, 1), core.pos_to_string(p2, 1))
718 return false, S("Failed to clear one or more "
719 .. "blocks in area.")
724 core.register_chatcommand("fixlight", {
725 params = S("(here [<radius>]) | (<pos1> <pos2>)"),
726 description = S("Resets lighting in the area between pos1 and pos2 "
727 .. "(<pos1> and <pos2> must be in parentheses)"),
728 privs = {server = true},
729 func = function(name, param)
730 local p1, p2 = parse_range_str(name, param)
735 if core.fix_light(p1, p2) then
736 return true, S("Successfully reset light in the area "
737 .. "ranging from @1 to @2.",
738 core.pos_to_string(p1, 1), core.pos_to_string(p2, 1))
740 return false, S("Failed to load one or more blocks in area.")
745 core.register_chatcommand("mods", {
747 description = S("List mods installed on the server"),
749 func = function(name, param)
750 local mods = core.get_modnames()
752 return true, S("No mods installed.")
754 return true, table.concat(core.get_modnames(), ", ")
759 local function handle_give_command(cmd, giver, receiver, stackstring)
760 core.log("action", giver .. " invoked " .. cmd
761 .. ', stackstring="' .. stackstring .. '"')
762 local itemstack = ItemStack(stackstring)
763 if itemstack:is_empty() then
764 return false, S("Cannot give an empty item.")
765 elseif (not itemstack:is_known()) or (itemstack:get_name() == "unknown") then
766 return false, S("Cannot give an unknown item.")
767 -- Forbid giving 'ignore' due to unwanted side effects
768 elseif itemstack:get_name() == "ignore" then
769 return false, S("Giving 'ignore' is not allowed.")
771 local receiverref = core.get_player_by_name(receiver)
772 if receiverref == nil then
773 return false, S("@1 is not a known player.", receiver)
775 local leftover = receiverref:get_inventory():add_item("main", itemstack)
777 if leftover:is_empty() then
779 elseif leftover:get_count() == itemstack:get_count() then
784 -- The actual item stack string may be different from what the "giver"
785 -- entered (e.g. big numbers are always interpreted as 2^16-1).
786 stackstring = itemstack:to_string()
788 if partiality == true then
789 msg = S("@1 partially added to inventory.", stackstring)
790 elseif partiality == false then
791 msg = S("@1 could not be added to inventory.", stackstring)
793 msg = S("@1 added to inventory.", stackstring)
795 if giver == receiver then
798 core.chat_send_player(receiver, msg)
800 if partiality == true then
801 msg_other = S("@1 partially added to inventory of @2.",
802 stackstring, receiver)
803 elseif partiality == false then
804 msg_other = S("@1 could not be added to inventory of @2.",
805 stackstring, receiver)
807 msg_other = S("@1 added to inventory of @2.",
808 stackstring, receiver)
810 return true, msg_other
814 core.register_chatcommand("give", {
815 params = S("<name> <ItemString> [<count> [<wear>]]"),
816 description = S("Give item to player"),
818 func = function(name, param)
819 local toname, itemstring = string.match(param, "^([^ ]+) +(.+)$")
820 if not toname or not itemstring then
821 return false, S("Name and ItemString required.")
823 return handle_give_command("/give", name, toname, itemstring)
827 core.register_chatcommand("giveme", {
828 params = S("<ItemString> [<count> [<wear>]]"),
829 description = S("Give item to yourself"),
831 func = function(name, param)
832 local itemstring = string.match(param, "(.+)$")
833 if not itemstring then
834 return false, S("ItemString required.")
836 return handle_give_command("/giveme", name, name, itemstring)
840 core.register_chatcommand("spawnentity", {
841 params = S("<EntityName> [<X>,<Y>,<Z>]"),
842 description = S("Spawn entity at given (or your) position"),
843 privs = {give=true, interact=true},
844 func = function(name, param)
845 local entityname, p = string.match(param, "^([^ ]+) *(.*)$")
846 if not entityname then
847 return false, S("EntityName required.")
849 core.log("action", ("%s invokes /spawnentity, entityname=%q")
850 :format(name, entityname))
851 local player = core.get_player_by_name(name)
852 if player == nil then
853 core.log("error", "Unable to spawn entity, player is nil")
854 return false, S("Unable to spawn entity, player is nil.")
856 if not core.registered_entities[entityname] then
857 return false, S("Cannot spawn an unknown entity.")
862 p = core.string_to_pos(p)
864 return false, S("Invalid parameters (@1).", param)
868 local obj = core.add_entity(p, entityname)
870 return true, S("@1 spawned.", entityname)
872 return true, S("@1 failed to spawn.", entityname)
877 core.register_chatcommand("pulverize", {
879 description = S("Destroy item in hand"),
880 func = function(name, param)
881 local player = core.get_player_by_name(name)
883 core.log("error", "Unable to pulverize, no player.")
884 return false, S("Unable to pulverize, no player.")
886 local wielded_item = player:get_wielded_item()
887 if wielded_item:is_empty() then
888 return false, S("Unable to pulverize, no item in hand.")
890 core.log("action", name .. " pulverized \"" ..
891 wielded_item:get_name() .. " " .. wielded_item:get_count() .. "\"")
892 player:set_wielded_item(nil)
893 return true, S("An item was pulverized.")
898 core.rollback_punch_callbacks = {}
900 core.register_on_punchnode(function(pos, node, puncher)
901 local name = puncher and puncher:get_player_name()
902 if name and core.rollback_punch_callbacks[name] then
903 core.rollback_punch_callbacks[name](pos, node, puncher)
904 core.rollback_punch_callbacks[name] = nil
908 core.register_chatcommand("rollback_check", {
909 params = S("[<range>] [<seconds>] [<limit>]"),
910 description = S("Check who last touched a node or a node near it "
911 .. "within the time specified by <seconds>. "
912 .. "Default: range = 0, seconds = 86400 = 24h, limit = 5. "
913 .. "Set <seconds> to inf for no time limit"),
914 privs = {rollback=true},
915 func = function(name, param)
916 if not core.settings:get_bool("enable_rollback_recording") then
917 return false, S("Rollback functions are disabled.")
919 local range, seconds, limit =
920 param:match("(%d+) *(%d*) *(%d*)")
921 range = tonumber(range) or 0
922 seconds = tonumber(seconds) or 86400
923 limit = tonumber(limit) or 5
925 return false, S("That limit is too high!")
928 core.rollback_punch_callbacks[name] = function(pos, node, puncher)
929 local name = puncher:get_player_name()
930 core.chat_send_player(name, S("Checking @1 ...", core.pos_to_string(pos)))
931 local actions = core.rollback_get_node_actions(pos, range, seconds, limit)
933 core.chat_send_player(name, S("Rollback functions are disabled."))
936 local num_actions = #actions
937 if num_actions == 0 then
938 core.chat_send_player(name,
939 S("Nobody has touched the specified "
940 .. "location in @1 seconds.",
944 local time = os.time()
945 for i = num_actions, 1, -1 do
946 local action = actions[i]
947 core.chat_send_player(name,
948 S("@1 @2 @3 -> @4 @5 seconds ago.",
949 core.pos_to_string(action.pos),
957 return true, S("Punch a node (range=@1, seconds=@2, limit=@3).",
958 range, seconds, limit)
962 core.register_chatcommand("rollback", {
963 params = S("(<name> [<seconds>]) | (:<actor> [<seconds>])"),
964 description = S("Revert actions of a player. "
965 .. "Default for <seconds> is 60. "
966 .. "Set <seconds> to inf for no time limit"),
967 privs = {rollback=true},
968 func = function(name, param)
969 if not core.settings:get_bool("enable_rollback_recording") then
970 return false, S("Rollback functions are disabled.")
972 local target_name, seconds = string.match(param, ":([^ ]+) *(%d*)")
974 if not target_name then
976 player_name, seconds = string.match(param, "([^ ]+) *(%d*)")
977 if not player_name then
978 return false, S("Invalid parameters. "
979 .. "See /help rollback and "
980 .. "/help rollback_check.")
982 seconds = tonumber(seconds) or 60
983 target_name = "player:"..player_name
984 rev_msg = S("Reverting actions of player '@1' since @2 seconds.",
985 player_name, seconds)
987 seconds = tonumber(seconds) or 60
988 rev_msg = S("Reverting actions of @1 since @2 seconds.",
989 target_name, seconds)
991 core.chat_send_player(name, rev_msg)
992 local success, log = core.rollback_revert_actions_by(
993 target_name, seconds)
996 response = S("(log is too long to show)").."\n"
998 for _, line in pairs(log) do
999 response = response .. line .. "\n"
1003 response = response .. S("Reverting actions succeeded.")
1005 response = response .. S("Reverting actions FAILED.")
1007 return success, response
1011 core.register_chatcommand("status", {
1012 description = S("Show server status"),
1013 func = function(name, param)
1014 local status = core.get_server_status(name, false)
1015 if status and status ~= "" then
1018 return false, S("This command was disabled by a mod or game.")
1022 core.register_chatcommand("time", {
1023 params = S("[<0..23>:<0..59> | <0..24000>]"),
1024 description = S("Show or set time of day"),
1026 func = function(name, param)
1028 local current_time = math.floor(core.get_timeofday() * 1440)
1029 local minutes = current_time % 60
1030 local hour = (current_time - minutes) / 60
1031 return true, S("Current time is @1:@2.",
1032 string.format("%d", hour),
1033 string.format("%02d", minutes))
1035 local player_privs = core.get_player_privs(name)
1036 if not player_privs.settime then
1037 return false, S("You don't have permission to run "
1038 .. "this command (missing privilege: @1).", "settime")
1040 local hour, minute = param:match("^(%d+):(%d+)$")
1042 local new_time = tonumber(param) or -1
1043 if new_time ~= new_time or new_time < 0 or new_time > 24000 then
1044 return false, S("Invalid time (must be between 0 and 24000).")
1046 core.set_timeofday(new_time / 24000)
1047 core.log("action", name .. " sets time to " .. new_time)
1048 return true, S("Time of day changed.")
1050 hour = tonumber(hour)
1051 minute = tonumber(minute)
1052 if hour < 0 or hour > 23 then
1053 return false, S("Invalid hour (must be between 0 and 23 inclusive).")
1054 elseif minute < 0 or minute > 59 then
1055 return false, S("Invalid minute (must be between 0 and 59 inclusive).")
1057 core.set_timeofday((hour * 60 + minute) / 1440)
1058 core.log("action", ("%s sets time to %d:%02d"):format(name, hour, minute))
1059 return true, S("Time of day changed.")
1063 core.register_chatcommand("days", {
1064 description = S("Show day count since world creation"),
1065 func = function(name, param)
1066 return true, S("Current day is @1.", core.get_day_count())
1070 local function parse_shutdown_param(param)
1071 local delay, reconnect, message
1072 local one, two, three
1073 one, two, three = param:match("^(%S+) +(%-r) +(.*)")
1074 if one and two and three then
1075 -- 3 arguments: delay, reconnect and message
1076 return one, two, three
1079 one, two = param:match("^(%S+) +(.*)")
1081 if tonumber(one) then
1088 elseif one == "-r" then
1089 reconnect, message = one, two
1091 return delay, reconnect, message
1094 one = param:match("(.*)")
1095 if tonumber(one) then
1097 elseif one == "-r" then
1102 return delay, reconnect, message
1105 core.register_chatcommand("shutdown", {
1106 params = S("[<delay_in_seconds> | -1] [-r] [<message>]"),
1107 description = S("Shutdown server (-1 cancels a delayed shutdown, -r allows players to reconnect)"),
1108 privs = {server=true},
1109 func = function(name, param)
1110 local delay, reconnect, message = parse_shutdown_param(param)
1111 local bool_reconnect = reconnect == "-r"
1115 delay = tonumber(delay) or 0
1118 core.log("action", name .. " shuts down server")
1119 core.chat_send_all("*** "..S("Server shutting down (operator request)."))
1121 core.request_shutdown(message:trim(), bool_reconnect, delay)
1126 core.register_chatcommand("ban", {
1127 params = S("[<name>]"),
1128 description = S("Ban the IP of a player or show the ban list"),
1130 func = function(name, param)
1132 local ban_list = core.get_ban_list()
1133 if ban_list == "" then
1134 return true, S("The ban list is empty.")
1136 return true, S("Ban list: @1", ban_list)
1139 if not core.get_player_by_name(param) then
1140 return false, S("Player is not online.")
1142 if not core.ban_player(param) then
1143 return false, S("Failed to ban player.")
1145 local desc = core.get_ban_description(param)
1146 core.log("action", name .. " bans " .. desc .. ".")
1147 return true, S("Banned @1.", desc)
1151 core.register_chatcommand("unban", {
1152 params = S("<name> | <IP_address>"),
1153 description = S("Remove IP ban belonging to a player/IP"),
1155 func = function(name, param)
1156 if not core.unban_player_or_ip(param) then
1157 return false, S("Failed to unban player/IP.")
1159 core.log("action", name .. " unbans " .. param)
1160 return true, S("Unbanned @1.", param)
1164 core.register_chatcommand("kick", {
1165 params = S("<name> [<reason>]"),
1166 description = S("Kick a player"),
1167 privs = {kick=true},
1168 func = function(name, param)
1169 local tokick, reason = param:match("([^ ]+) (.+)")
1170 tokick = tokick or param
1171 if not core.kick_player(tokick, reason) then
1172 return false, S("Failed to kick player @1.", tokick)
1174 local log_reason = ""
1176 log_reason = " with reason \"" .. reason .. "\""
1178 core.log("action", name .. " kicks " .. tokick .. log_reason)
1179 return true, S("Kicked @1.", tokick)
1183 core.register_chatcommand("clearobjects", {
1184 params = S("[full | quick]"),
1185 description = S("Clear all objects in world"),
1186 privs = {server=true},
1187 func = function(name, param)
1189 if param == "" or param == "quick" then
1190 options.mode = "quick"
1191 elseif param == "full" then
1192 options.mode = "full"
1194 return false, S("Invalid usage, see /help clearobjects.")
1197 core.log("action", name .. " clears objects ("
1198 .. options.mode .. " mode).")
1199 if options.mode == "full" then
1200 core.chat_send_all(S("Clearing all objects. This may take a long time. "
1201 .. "You may experience a timeout. (by @1)", name))
1203 core.clear_objects(options)
1204 core.log("action", "Object clearing done.")
1205 core.chat_send_all("*** "..S("Cleared all objects."))
1210 core.register_chatcommand("msg", {
1211 params = S("<name> <message>"),
1212 description = S("Send a direct message to a player"),
1213 privs = {shout=true},
1214 func = function(name, param)
1215 local sendto, message = param:match("^(%S+)%s(.+)$")
1217 return false, S("Invalid usage, see /help msg.")
1219 if not core.get_player_by_name(sendto) then
1220 return false, S("The player @1 is not online.", sendto)
1222 core.log("action", "DM from " .. name .. " to " .. sendto
1224 core.chat_send_player(sendto, S("DM from @1: @2", name, message))
1225 return true, S("Message sent.")
1229 core.register_chatcommand("last-login", {
1230 params = S("[<name>]"),
1231 description = S("Get the last login time of a player or yourself"),
1232 func = function(name, param)
1236 local pauth = core.get_auth_handler().get_auth(param)
1237 if pauth and pauth.last_login and pauth.last_login ~= -1 then
1238 -- Time in UTC, ISO 8601 format
1239 return true, S("@1's last login time was @2.",
1241 os.date("!%Y-%m-%dT%H:%M:%SZ", pauth.last_login))
1243 return false, S("@1's last login time is unknown.", param)
1247 core.register_chatcommand("clearinv", {
1248 params = S("[<name>]"),
1249 description = S("Clear the inventory of yourself or another player"),
1250 func = function(name, param)
1252 if param and param ~= "" and param ~= name then
1253 if not core.check_player_privs(name, {server=true}) then
1254 return false, S("You don't have permission to "
1255 .. "clear another player's inventory "
1256 .. "(missing privilege: @1).", "server")
1258 player = core.get_player_by_name(param)
1259 core.chat_send_player(param, S("@1 cleared your inventory.", name))
1261 player = core.get_player_by_name(name)
1265 player:get_inventory():set_list("main", {})
1266 player:get_inventory():set_list("craft", {})
1267 player:get_inventory():set_list("craftpreview", {})
1268 core.log("action", name.." clears "..player:get_player_name().."'s inventory")
1269 return true, S("Cleared @1's inventory.", player:get_player_name())
1271 return false, S("Player must be online to clear inventory!")
1276 local function handle_kill_command(killer, victim)
1277 if core.settings:get_bool("enable_damage") == false then
1278 return false, S("Players can't be killed, damage has been disabled.")
1280 local victimref = core.get_player_by_name(victim)
1281 if victimref == nil then
1282 return false, S("Player @1 is not online.", victim)
1283 elseif victimref:get_hp() <= 0 then
1284 if killer == victim then
1285 return false, S("You are already dead.")
1287 return false, S("@1 is already dead.", victim)
1290 if killer ~= victim then
1291 core.log("action", string.format("%s killed %s", killer, victim))
1295 return true, S("@1 has been killed.", victim)
1298 core.register_chatcommand("kill", {
1299 params = S("[<name>]"),
1300 description = S("Kill player or yourself"),
1301 privs = {server=true},
1302 func = function(name, param)
1303 return handle_kill_command(name, param == "" and name or param)