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 local player = core.get_player_by_name(player_name)
136 relpos = player:get_pos()
138 p1, p2 = core.string_to_area(str, relpos)
139 if p1 == nil or p2 == nil then
140 return false, S("Incorrect area format. "
141 .. "Expected: (x1,y1,z1) (x2,y2,z2)")
151 core.register_chatcommand("me", {
152 params = S("<action>"),
153 description = S("Show chat action (e.g., '/me orders a pizza' "
154 .. "displays '<player name> orders a pizza')"),
155 privs = {shout=true},
156 func = function(name, param)
157 core.chat_send_all("* " .. name .. " " .. param)
162 core.register_chatcommand("admin", {
163 description = S("Show the name of the server owner"),
164 func = function(name)
165 local admin = core.settings:get("name")
167 return true, S("The administrator of this server is @1.", admin)
169 return false, S("There's no administrator named "
170 .. "in the config file.")
175 local function privileges_of(name, privs)
177 privs = core.get_player_privs(name)
179 local privstr = core.privs_to_string(privs, ", ")
180 if privstr == "" then
181 return S("@1 does not have any privileges.", name)
183 return S("Privileges of @1: @2", name, privstr)
187 core.register_chatcommand("privs", {
188 params = S("[<name>]"),
189 description = S("Show privileges of yourself or another player"),
190 func = function(caller, param)
192 local name = (param ~= "" and param or caller)
193 if not core.player_exists(name) then
194 return false, S("Player @1 does not exist.", name)
196 return true, privileges_of(name)
200 core.register_chatcommand("haspriv", {
201 params = S("<privilege>"),
202 description = S("Return list of all online players with privilege"),
203 privs = {basic_privs = true},
204 func = function(caller, param)
207 return false, S("Invalid parameters (see /help haspriv).")
209 if not core.registered_privileges[param] then
210 return false, S("Unknown privilege!")
212 local privs = core.string_to_privs(param)
213 local players_with_priv = {}
214 for _, player in pairs(core.get_connected_players()) do
215 local player_name = player:get_player_name()
216 if core.check_player_privs(player_name, privs) then
217 table.insert(players_with_priv, player_name)
220 if #players_with_priv == 0 then
221 return true, S("No online player has the \"@1\" privilege.",
224 return true, S("Players online with the \"@1\" privilege: @2",
226 table.concat(players_with_priv, ", "))
231 local function handle_grant_command(caller, grantname, grantprivstr)
232 local caller_privs = core.get_player_privs(caller)
233 if not (caller_privs.privs or caller_privs.basic_privs) then
234 return false, S("Your privileges are insufficient.")
237 if not core.get_auth_handler().get_auth(grantname) then
238 return false, S("Player @1 does not exist.", grantname)
240 local grantprivs = core.string_to_privs(grantprivstr)
241 if grantprivstr == "all" then
242 grantprivs = core.registered_privileges
244 local privs = core.get_player_privs(grantname)
245 local privs_unknown = ""
247 core.string_to_privs(core.settings:get("basic_privs") or "interact,shout")
248 for priv, _ in pairs(grantprivs) do
249 if not basic_privs[priv] and not caller_privs.privs then
250 return false, S("Your privileges are insufficient. "..
251 "'@1' only allows you to grant: @2",
253 core.privs_to_string(basic_privs, ', '))
255 if not core.registered_privileges[priv] then
256 privs_unknown = privs_unknown .. S("Unknown privilege: @1", priv) .. "\n"
260 if privs_unknown ~= "" then
261 return false, privs_unknown
263 core.set_player_privs(grantname, privs)
264 for priv, _ in pairs(grantprivs) do
265 -- call the on_grant callbacks
266 core.run_priv_callbacks(grantname, priv, caller, "grant")
268 core.log("action", caller..' granted ('..core.privs_to_string(grantprivs, ', ')..') privileges to '..grantname)
269 if grantname ~= caller then
270 core.chat_send_player(grantname,
271 S("@1 granted you privileges: @2", caller,
272 core.privs_to_string(grantprivs, ', ')))
274 return true, privileges_of(grantname)
277 core.register_chatcommand("grant", {
278 params = S("<name> (<privilege> [, <privilege2> [<...>]] | all)"),
279 description = S("Give privileges to player"),
280 func = function(name, param)
281 local grantname, grantprivstr = string.match(param, "([^ ]+) (.+)")
282 if not grantname or not grantprivstr then
283 return false, S("Invalid parameters (see /help grant).")
285 return handle_grant_command(name, grantname, grantprivstr)
289 core.register_chatcommand("grantme", {
290 params = S("<privilege> [, <privilege2> [<...>]] | all"),
291 description = S("Grant privileges to yourself"),
292 func = function(name, param)
294 return false, S("Invalid parameters (see /help grantme).")
296 return handle_grant_command(name, name, param)
300 local function handle_revoke_command(caller, revokename, revokeprivstr)
301 local caller_privs = core.get_player_privs(caller)
302 if not (caller_privs.privs or caller_privs.basic_privs) then
303 return false, S("Your privileges are insufficient.")
306 if not core.get_auth_handler().get_auth(revokename) then
307 return false, S("Player @1 does not exist.", revokename)
310 local privs = core.get_player_privs(revokename)
312 local revokeprivs = core.string_to_privs(revokeprivstr)
313 local is_singleplayer = core.is_singleplayer()
314 local is_admin = not is_singleplayer
315 and revokename == core.settings:get("name")
317 if revokeprivstr == "all" then
318 revokeprivs = table.copy(privs)
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 -- Old/removed privileges might still be granted to certain players
336 if not privs[priv] then
337 privs_unknown = privs_unknown .. S("Unknown privilege: @1", priv) .. "\n"
339 elseif is_singleplayer and def.give_to_singleplayer then
340 irrevokable[priv] = true
341 elseif is_admin and def.give_to_admin then
342 irrevokable[priv] = true
345 for priv, _ in pairs(irrevokable) do
346 revokeprivs[priv] = nil
347 has_irrevokable_priv = true
349 if privs_unknown ~= "" then
350 return false, privs_unknown
352 if has_irrevokable_priv then
353 if is_singleplayer then
354 core.chat_send_player(caller,
355 S("Note: Cannot revoke in singleplayer: @1",
356 core.privs_to_string(irrevokable, ', ')))
358 core.chat_send_player(caller,
359 S("Note: Cannot revoke from admin: @1",
360 core.privs_to_string(irrevokable, ', ')))
364 local revokecount = 0
365 for priv, _ in pairs(revokeprivs) do
367 revokecount = revokecount + 1
370 if revokecount == 0 then
371 return false, S("No privileges were revoked.")
374 core.set_player_privs(revokename, privs)
375 for priv, _ in pairs(revokeprivs) do
376 -- call the on_revoke callbacks
377 core.run_priv_callbacks(revokename, priv, caller, "revoke")
379 local new_privs = core.get_player_privs(revokename)
381 core.log("action", caller..' revoked ('
382 ..core.privs_to_string(revokeprivs, ', ')
383 ..') privileges from '..revokename)
384 if revokename ~= caller then
385 core.chat_send_player(revokename,
386 S("@1 revoked privileges from you: @2", caller,
387 core.privs_to_string(revokeprivs, ', ')))
389 return true, privileges_of(revokename, new_privs)
392 core.register_chatcommand("revoke", {
393 params = S("<name> (<privilege> [, <privilege2> [<...>]] | all)"),
394 description = S("Remove privileges from player"),
396 func = function(name, param)
397 local revokename, revokeprivstr = string.match(param, "([^ ]+) (.+)")
398 if not revokename or not revokeprivstr then
399 return false, S("Invalid parameters (see /help revoke).")
401 return handle_revoke_command(name, revokename, revokeprivstr)
405 core.register_chatcommand("revokeme", {
406 params = S("<privilege> [, <privilege2> [<...>]] | all"),
407 description = S("Revoke privileges from yourself"),
409 func = function(name, param)
411 return false, S("Invalid parameters (see /help revokeme).")
413 return handle_revoke_command(name, name, param)
417 core.register_chatcommand("setpassword", {
418 params = S("<name> <password>"),
419 description = S("Set player's password"),
420 privs = {password=true},
421 func = function(name, param)
422 local toname, raw_password = string.match(param, "^([^ ]+) +(.+)$")
424 toname = param:match("^([^ ]+) *$")
429 return false, S("Name field required.")
432 local msg_chat, msg_log, msg_ret
433 if not raw_password then
434 core.set_player_password(toname, "")
435 msg_chat = S("Your password was cleared by @1.", name)
436 msg_log = name .. " clears password of " .. toname .. "."
437 msg_ret = S("Password of player \"@1\" cleared.", toname)
439 core.set_player_password(toname,
440 core.get_password_hash(toname,
442 msg_chat = S("Your password was set by @1.", name)
443 msg_log = name .. " sets password of " .. toname .. "."
444 msg_ret = S("Password of player \"@1\" set.", toname)
447 if toname ~= name then
448 core.chat_send_player(toname, msg_chat)
451 core.log("action", msg_log)
457 core.register_chatcommand("clearpassword", {
458 params = S("<name>"),
459 description = S("Set empty password for a player"),
460 privs = {password=true},
461 func = function(name, param)
464 return false, S("Name field required.")
466 core.set_player_password(toname, '')
468 core.log("action", name .. " clears password of " .. toname .. ".")
470 return true, S("Password of player \"@1\" cleared.", toname)
474 core.register_chatcommand("auth_reload", {
476 description = S("Reload authentication data"),
477 privs = {server=true},
478 func = function(name, param)
479 local done = core.auth_reload()
480 return done, (done and S("Done.") or S("Failed."))
484 core.register_chatcommand("remove_player", {
485 params = S("<name>"),
486 description = S("Remove a player's data"),
487 privs = {server=true},
488 func = function(name, param)
491 return false, S("Name field required.")
494 local rc = core.remove_player(toname)
497 core.log("action", name .. " removed player data of " .. toname .. ".")
498 return true, S("Player \"@1\" removed.", toname)
500 return true, S("No such player \"@1\" to remove.", toname)
502 return true, S("Player \"@1\" is connected, cannot remove.", toname)
505 return false, S("Unhandled remove_player return code @1.", tostring(rc))
510 -- pos may be a non-integer position
511 local function find_free_position_near(pos)
513 vector.new( 1, 0, 0),
514 vector.new(-1, 0, 0),
515 vector.new( 0, 0, 1),
516 vector.new( 0, 0, -1),
518 for _, d in ipairs(tries) do
519 local p = vector.add(pos, d)
520 local n = core.get_node_or_nil(p)
522 local def = core.registered_nodes[n.name]
523 if def and not def.walkable then
531 -- Teleports player <name> to <p> if possible
532 local function teleport_to_pos(name, p)
533 local lm = 31007 -- equals MAX_MAP_GENERATION_LIMIT in C++
534 if p.x < -lm or p.x > lm or p.y < -lm or p.y > lm
535 or p.z < -lm or p.z > lm then
536 return false, S("Cannot teleport out of map bounds!")
538 local teleportee = core.get_player_by_name(name)
539 if not teleportee then
540 return false, S("Cannot get player with name @1.", name)
542 if teleportee:get_attach() then
543 return false, S("Cannot teleport, @1 " ..
544 "is attached to an object!", name)
546 teleportee:set_pos(p)
547 return true, S("Teleporting @1 to @2.", name, core.pos_to_string(p, 1))
550 -- Teleports player <name> next to player <target_name> if possible
551 local function teleport_to_player(name, target_name)
552 if name == target_name then
553 return false, S("One does not teleport to oneself.")
555 local teleportee = core.get_player_by_name(name)
556 if not teleportee then
557 return false, S("Cannot get teleportee with name @1.", name)
559 if teleportee:get_attach() then
560 return false, S("Cannot teleport, @1 " ..
561 "is attached to an object!", name)
563 local target = core.get_player_by_name(target_name)
565 return false, S("Cannot get target player with name @1.", target_name)
567 local p = find_free_position_near(target:get_pos())
568 teleportee:set_pos(p)
569 return true, S("Teleporting @1 to @2 at @3.", name, target_name,
570 core.pos_to_string(p, 1))
573 core.register_chatcommand("teleport", {
574 params = S("<X>,<Y>,<Z> | <to_name> | <name> <X>,<Y>,<Z> | <name> <to_name>"),
575 description = S("Teleport to position or player"),
576 privs = {teleport=true},
577 func = function(name, param)
578 local player = core.get_player_by_name(name)
581 relpos = player:get_pos()
584 p.x, p.y, p.z = string.match(param, "^([%d.~-]+)[, ] *([%d.~-]+)[, ] *([%d.~-]+)$")
585 p = core.parse_coordinates(p.x, p.y, p.z, relpos)
586 if p and p.x and p.y and p.z then
587 return teleport_to_pos(name, p)
590 local target_name = param:match("^([^ ]+)$")
592 return teleport_to_player(name, target_name)
595 local has_bring_priv = core.check_player_privs(name, {bring=true})
596 local missing_bring_msg = S("You don't have permission to teleport " ..
597 "other players (missing privilege: @1).", "bring")
599 local teleportee_name
601 teleportee_name, p.x, p.y, p.z = param:match(
602 "^([^ ]+) +([%d.~-]+)[, ] *([%d.~-]+)[, ] *([%d.~-]+)$")
603 if teleportee_name then
604 local teleportee = core.get_player_by_name(teleportee_name)
605 if not teleportee then
608 relpos = teleportee:get_pos()
609 p = core.parse_coordinates(p.x, p.y, p.z, relpos)
611 p = vector.apply(p, tonumber)
613 if teleportee_name and p.x and p.y and p.z then
614 if not has_bring_priv then
615 return false, missing_bring_msg
617 return teleport_to_pos(teleportee_name, p)
620 teleportee_name, target_name = string.match(param, "^([^ ]+) +([^ ]+)$")
621 if teleportee_name and target_name then
622 if not has_bring_priv then
623 return false, missing_bring_msg
625 return teleport_to_player(teleportee_name, target_name)
632 core.register_chatcommand("set", {
633 params = S("([-n] <name> <value>) | <name>"),
634 description = S("Set or read server configuration setting"),
635 privs = {server=true},
636 func = function(name, param)
637 local arg, setname, setvalue = string.match(param, "(-[n]) ([^ ]+) (.+)")
638 if arg and arg == "-n" and setname and setvalue then
639 core.settings:set(setname, setvalue)
640 return true, setname .. " = " .. setvalue
643 setname, setvalue = string.match(param, "([^ ]+) (.+)")
644 if setname and setvalue then
645 if setname:sub(1, 7) == "secure." then
646 return false, S("Failed. Cannot modify secure settings. "
647 .. "Edit the settings file manually.")
649 if not core.settings:get(setname) then
650 return false, S("Failed. Use '/set -n <name> <value>' "
651 .. "to create a new setting.")
653 core.settings:set(setname, setvalue)
654 return true, S("@1 = @2", setname, setvalue)
657 setname = string.match(param, "([^ ]+)")
659 setvalue = core.settings:get(setname)
661 setvalue = S("<not set>")
663 return true, S("@1 = @2", setname, setvalue)
666 return false, S("Invalid parameters (see /help set).")
670 local function emergeblocks_callback(pos, action, num_calls_remaining, ctx)
671 if ctx.total_blocks == 0 then
672 ctx.total_blocks = num_calls_remaining + 1
673 ctx.current_blocks = 0
675 ctx.current_blocks = ctx.current_blocks + 1
677 if ctx.current_blocks == ctx.total_blocks then
678 core.chat_send_player(ctx.requestor_name,
679 S("Finished emerging @1 blocks in @2ms.",
681 string.format("%.2f", (os.clock() - ctx.start_time) * 1000)))
685 local function emergeblocks_progress_update(ctx)
686 if ctx.current_blocks ~= ctx.total_blocks then
687 core.chat_send_player(ctx.requestor_name,
688 S("emergeblocks update: @1/@2 blocks emerged (@3%)",
689 ctx.current_blocks, ctx.total_blocks,
690 string.format("%.1f", (ctx.current_blocks / ctx.total_blocks) * 100)))
692 core.after(2, emergeblocks_progress_update, ctx)
696 core.register_chatcommand("emergeblocks", {
697 params = S("(here [<radius>]) | (<pos1> <pos2>)"),
698 description = S("Load (or, if nonexistent, generate) map blocks contained in "
699 .. "area pos1 to pos2 (<pos1> and <pos2> must be in parentheses)"),
700 privs = {server=true},
701 func = function(name, param)
702 local p1, p2 = parse_range_str(name, param)
710 start_time = os.clock(),
711 requestor_name = name
714 core.emerge_area(p1, p2, emergeblocks_callback, context)
715 core.after(2, emergeblocks_progress_update, context)
717 return true, S("Started emerge of area ranging from @1 to @2.",
718 core.pos_to_string(p1, 1), core.pos_to_string(p2, 1))
722 core.register_chatcommand("deleteblocks", {
723 params = S("(here [<radius>]) | (<pos1> <pos2>)"),
724 description = S("Delete map blocks contained in area pos1 to pos2 "
725 .. "(<pos1> and <pos2> must be in parentheses)"),
726 privs = {server=true},
727 func = function(name, param)
728 local p1, p2 = parse_range_str(name, param)
733 if core.delete_area(p1, p2) then
734 return true, S("Successfully cleared area "
735 .. "ranging from @1 to @2.",
736 core.pos_to_string(p1, 1), core.pos_to_string(p2, 1))
738 return false, S("Failed to clear one or more "
739 .. "blocks in area.")
744 core.register_chatcommand("fixlight", {
745 params = S("(here [<radius>]) | (<pos1> <pos2>)"),
746 description = S("Resets lighting in the area between pos1 and pos2 "
747 .. "(<pos1> and <pos2> must be in parentheses)"),
748 privs = {server = true},
749 func = function(name, param)
750 local p1, p2 = parse_range_str(name, param)
755 if core.fix_light(p1, p2) then
756 return true, S("Successfully reset light in the area "
757 .. "ranging from @1 to @2.",
758 core.pos_to_string(p1, 1), core.pos_to_string(p2, 1))
760 return false, S("Failed to load one or more blocks in area.")
765 core.register_chatcommand("mods", {
767 description = S("List mods installed on the server"),
769 func = function(name, param)
770 local mods = core.get_modnames()
772 return true, S("No mods installed.")
774 return true, table.concat(core.get_modnames(), ", ")
779 local function handle_give_command(cmd, giver, receiver, stackstring)
780 core.log("action", giver .. " invoked " .. cmd
781 .. ', stackstring="' .. stackstring .. '"')
782 local itemstack = ItemStack(stackstring)
783 if itemstack:is_empty() then
784 return false, S("Cannot give an empty item.")
785 elseif (not itemstack:is_known()) or (itemstack:get_name() == "unknown") then
786 return false, S("Cannot give an unknown item.")
787 -- Forbid giving 'ignore' due to unwanted side effects
788 elseif itemstack:get_name() == "ignore" then
789 return false, S("Giving 'ignore' is not allowed.")
791 local receiverref = core.get_player_by_name(receiver)
792 if receiverref == nil then
793 return false, S("@1 is not a known player.", receiver)
795 local leftover = receiverref:get_inventory():add_item("main", itemstack)
797 if leftover:is_empty() then
799 elseif leftover:get_count() == itemstack:get_count() then
804 -- The actual item stack string may be different from what the "giver"
805 -- entered (e.g. big numbers are always interpreted as 2^16-1).
806 stackstring = itemstack:to_string()
808 if partiality == true then
809 msg = S("@1 partially added to inventory.", stackstring)
810 elseif partiality == false then
811 msg = S("@1 could not be added to inventory.", stackstring)
813 msg = S("@1 added to inventory.", stackstring)
815 if giver == receiver then
818 core.chat_send_player(receiver, msg)
820 if partiality == true then
821 msg_other = S("@1 partially added to inventory of @2.",
822 stackstring, receiver)
823 elseif partiality == false then
824 msg_other = S("@1 could not be added to inventory of @2.",
825 stackstring, receiver)
827 msg_other = S("@1 added to inventory of @2.",
828 stackstring, receiver)
830 return true, msg_other
834 core.register_chatcommand("give", {
835 params = S("<name> <ItemString> [<count> [<wear>]]"),
836 description = S("Give item to player"),
838 func = function(name, param)
839 local toname, itemstring = string.match(param, "^([^ ]+) +(.+)$")
840 if not toname or not itemstring then
841 return false, S("Name and ItemString required.")
843 return handle_give_command("/give", name, toname, itemstring)
847 core.register_chatcommand("giveme", {
848 params = S("<ItemString> [<count> [<wear>]]"),
849 description = S("Give item to yourself"),
851 func = function(name, param)
852 local itemstring = string.match(param, "(.+)$")
853 if not itemstring then
854 return false, S("ItemString required.")
856 return handle_give_command("/giveme", name, name, itemstring)
860 core.register_chatcommand("spawnentity", {
861 params = S("<EntityName> [<X>,<Y>,<Z>]"),
862 description = S("Spawn entity at given (or your) position"),
863 privs = {give=true, interact=true},
864 func = function(name, param)
865 local entityname, pstr = string.match(param, "^([^ ]+) *(.*)$")
866 if not entityname then
867 return false, S("EntityName required.")
869 core.log("action", ("%s invokes /spawnentity, entityname=%q")
870 :format(name, entityname))
871 local player = core.get_player_by_name(name)
872 if player == nil then
873 core.log("error", "Unable to spawn entity, player is nil")
874 return false, S("Unable to spawn entity, player is nil.")
876 if not core.registered_entities[entityname] then
877 return false, S("Cannot spawn an unknown entity.")
884 p.x, p.y, p.z = string.match(pstr, "^([%d.~-]+)[, ] *([%d.~-]+)[, ] *([%d.~-]+)$")
885 local relpos = player:get_pos()
886 p = core.parse_coordinates(p.x, p.y, p.z, relpos)
887 if not (p and p.x and p.y and p.z) then
888 return false, S("Invalid parameters (@1).", param)
892 local obj = core.add_entity(p, entityname)
894 return true, S("@1 spawned.", entityname)
896 return true, S("@1 failed to spawn.", entityname)
901 core.register_chatcommand("pulverize", {
903 description = S("Destroy item in hand"),
904 func = function(name, param)
905 local player = core.get_player_by_name(name)
907 core.log("error", "Unable to pulverize, no player.")
908 return false, S("Unable to pulverize, no player.")
910 local wielded_item = player:get_wielded_item()
911 if wielded_item:is_empty() then
912 return false, S("Unable to pulverize, no item in hand.")
914 core.log("action", name .. " pulverized \"" ..
915 wielded_item:get_name() .. " " .. wielded_item:get_count() .. "\"")
916 player:set_wielded_item(nil)
917 return true, S("An item was pulverized.")
922 core.rollback_punch_callbacks = {}
924 core.register_on_punchnode(function(pos, node, puncher)
925 local name = puncher and puncher:get_player_name()
926 if name and core.rollback_punch_callbacks[name] then
927 core.rollback_punch_callbacks[name](pos, node, puncher)
928 core.rollback_punch_callbacks[name] = nil
932 core.register_chatcommand("rollback_check", {
933 params = S("[<range>] [<seconds>] [<limit>]"),
934 description = S("Check who last touched a node or a node near it "
935 .. "within the time specified by <seconds>. "
936 .. "Default: range = 0, seconds = 86400 = 24h, limit = 5. "
937 .. "Set <seconds> to inf for no time limit"),
938 privs = {rollback=true},
939 func = function(name, param)
940 if not core.settings:get_bool("enable_rollback_recording") then
941 return false, S("Rollback functions are disabled.")
943 local range, seconds, limit =
944 param:match("(%d+) *(%d*) *(%d*)")
945 range = tonumber(range) or 0
946 seconds = tonumber(seconds) or 86400
947 limit = tonumber(limit) or 5
949 return false, S("That limit is too high!")
952 core.rollback_punch_callbacks[name] = function(pos, node, puncher)
953 local name = puncher:get_player_name()
954 core.chat_send_player(name, S("Checking @1 ...", core.pos_to_string(pos)))
955 local actions = core.rollback_get_node_actions(pos, range, seconds, limit)
957 core.chat_send_player(name, S("Rollback functions are disabled."))
960 local num_actions = #actions
961 if num_actions == 0 then
962 core.chat_send_player(name,
963 S("Nobody has touched the specified "
964 .. "location in @1 seconds.",
968 local time = os.time()
969 for i = num_actions, 1, -1 do
970 local action = actions[i]
971 core.chat_send_player(name,
972 S("@1 @2 @3 -> @4 @5 seconds ago.",
973 core.pos_to_string(action.pos),
981 return true, S("Punch a node (range=@1, seconds=@2, limit=@3).",
982 range, seconds, limit)
986 core.register_chatcommand("rollback", {
987 params = S("(<name> [<seconds>]) | (:<actor> [<seconds>])"),
988 description = S("Revert actions of a player. "
989 .. "Default for <seconds> is 60. "
990 .. "Set <seconds> to inf for no time limit"),
991 privs = {rollback=true},
992 func = function(name, param)
993 if not core.settings:get_bool("enable_rollback_recording") then
994 return false, S("Rollback functions are disabled.")
996 local target_name, seconds = string.match(param, ":([^ ]+) *(%d*)")
998 if not target_name then
1000 player_name, seconds = string.match(param, "([^ ]+) *(%d*)")
1001 if not player_name then
1002 return false, S("Invalid parameters. "
1003 .. "See /help rollback and "
1004 .. "/help rollback_check.")
1006 seconds = tonumber(seconds) or 60
1007 target_name = "player:"..player_name
1008 rev_msg = S("Reverting actions of player '@1' since @2 seconds.",
1009 player_name, seconds)
1011 seconds = tonumber(seconds) or 60
1012 rev_msg = S("Reverting actions of @1 since @2 seconds.",
1013 target_name, seconds)
1015 core.chat_send_player(name, rev_msg)
1016 local success, log = core.rollback_revert_actions_by(
1017 target_name, seconds)
1020 response = S("(log is too long to show)").."\n"
1022 for _, line in pairs(log) do
1023 response = response .. line .. "\n"
1027 response = response .. S("Reverting actions succeeded.")
1029 response = response .. S("Reverting actions FAILED.")
1031 return success, response
1035 core.register_chatcommand("status", {
1036 description = S("Show server status"),
1037 func = function(name, param)
1038 local status = core.get_server_status(name, false)
1039 if status and status ~= "" then
1042 return false, S("This command was disabled by a mod or game.")
1046 local function get_time(timeofday)
1047 local time = math.floor(timeofday * 1440)
1048 local minute = time % 60
1049 local hour = (time - minute) / 60
1050 return time, hour, minute
1053 core.register_chatcommand("time", {
1054 params = S("[<0..23>:<0..59> | <0..24000>]"),
1055 description = S("Show or set time of day"),
1057 func = function(name, param)
1059 local current_time = math.floor(core.get_timeofday() * 1440)
1060 local minutes = current_time % 60
1061 local hour = (current_time - minutes) / 60
1062 return true, S("Current time is @1:@2.",
1063 string.format("%d", hour),
1064 string.format("%02d", minutes))
1066 local player_privs = core.get_player_privs(name)
1067 if not player_privs.settime then
1068 return false, S("You don't have permission to run "
1069 .. "this command (missing privilege: @1).", "settime")
1071 local relative, negative, hour, minute = param:match("^(~?)(%-?)(%d+):(%d+)$")
1072 if not relative then -- checking the first capture against nil suffices
1073 local new_time = core.parse_relative_number(param, core.get_timeofday() * 24000)
1074 if not new_time then
1075 new_time = tonumber(param) or -1
1077 new_time = new_time % 24000
1079 if new_time ~= new_time or new_time < 0 or new_time > 24000 then
1080 return false, S("Invalid time (must be between 0 and 24000).")
1082 core.set_timeofday(new_time / 24000)
1083 core.log("action", name .. " sets time to " .. new_time)
1084 return true, S("Time of day changed.")
1087 hour = tonumber(hour)
1088 minute = tonumber(minute)
1089 if relative == "" then
1090 if hour < 0 or hour > 23 then
1091 return false, S("Invalid hour (must be between 0 and 23 inclusive).")
1092 elseif minute < 0 or minute > 59 then
1093 return false, S("Invalid minute (must be between 0 and 59 inclusive).")
1095 new_time = (hour * 60 + minute) / 1440
1097 if minute < 0 or minute > 59 then
1098 return false, S("Invalid minute (must be between 0 and 59 inclusive).")
1100 local current_time = core.get_timeofday()
1101 if negative == "-" then -- negative time
1102 hour, minute = -hour, -minute
1104 new_time = (current_time + (hour * 60 + minute) / 1440) % 1
1106 _, hour, minute = get_time(new_time)
1108 core.set_timeofday(new_time)
1109 core.log("action", ("%s sets time to %d:%02d"):format(name, hour, minute))
1110 return true, S("Time of day changed.")
1114 core.register_chatcommand("days", {
1115 description = S("Show day count since world creation"),
1116 func = function(name, param)
1117 return true, S("Current day is @1.", core.get_day_count())
1121 local function parse_shutdown_param(param)
1122 local delay, reconnect, message
1123 local one, two, three
1124 one, two, three = param:match("^(%S+) +(%-r) +(.*)")
1125 if one and two and three then
1126 -- 3 arguments: delay, reconnect and message
1127 return one, two, three
1130 one, two = param:match("^(%S+) +(.*)")
1132 if tonumber(one) then
1139 elseif one == "-r" then
1140 reconnect, message = one, two
1142 return delay, reconnect, message
1145 one = param:match("(.*)")
1146 if tonumber(one) then
1148 elseif one == "-r" then
1153 return delay, reconnect, message
1156 core.register_chatcommand("shutdown", {
1157 params = S("[<delay_in_seconds> | -1] [-r] [<message>]"),
1158 description = S("Shutdown server (-1 cancels a delayed shutdown, -r allows players to reconnect)"),
1159 privs = {server=true},
1160 func = function(name, param)
1161 local delay, reconnect, message = parse_shutdown_param(param)
1162 local bool_reconnect = reconnect == "-r"
1166 delay = tonumber(delay) or 0
1169 core.log("action", name .. " shuts down server")
1170 core.chat_send_all("*** "..S("Server shutting down (operator request)."))
1172 core.request_shutdown(message:trim(), bool_reconnect, delay)
1177 core.register_chatcommand("ban", {
1178 params = S("[<name>]"),
1179 description = S("Ban the IP of a player or show the ban list"),
1181 func = function(name, param)
1183 local ban_list = core.get_ban_list()
1184 if ban_list == "" then
1185 return true, S("The ban list is empty.")
1187 return true, S("Ban list: @1", ban_list)
1190 if not core.get_player_by_name(param) then
1191 return false, S("Player is not online.")
1193 if not core.ban_player(param) then
1194 return false, S("Failed to ban player.")
1196 local desc = core.get_ban_description(param)
1197 core.log("action", name .. " bans " .. desc .. ".")
1198 return true, S("Banned @1.", desc)
1202 core.register_chatcommand("unban", {
1203 params = S("<name> | <IP_address>"),
1204 description = S("Remove IP ban belonging to a player/IP"),
1206 func = function(name, param)
1207 if not core.unban_player_or_ip(param) then
1208 return false, S("Failed to unban player/IP.")
1210 core.log("action", name .. " unbans " .. param)
1211 return true, S("Unbanned @1.", param)
1215 core.register_chatcommand("kick", {
1216 params = S("<name> [<reason>]"),
1217 description = S("Kick a player"),
1218 privs = {kick=true},
1219 func = function(name, param)
1220 local tokick, reason = param:match("([^ ]+) (.+)")
1221 tokick = tokick or param
1222 if not core.kick_player(tokick, reason) then
1223 return false, S("Failed to kick player @1.", tokick)
1225 local log_reason = ""
1227 log_reason = " with reason \"" .. reason .. "\""
1229 core.log("action", name .. " kicks " .. tokick .. log_reason)
1230 return true, S("Kicked @1.", tokick)
1234 core.register_chatcommand("clearobjects", {
1235 params = S("[full | quick]"),
1236 description = S("Clear all objects in world"),
1237 privs = {server=true},
1238 func = function(name, param)
1240 if param == "" or param == "quick" then
1241 options.mode = "quick"
1242 elseif param == "full" then
1243 options.mode = "full"
1245 return false, S("Invalid usage, see /help clearobjects.")
1248 core.log("action", name .. " clears objects ("
1249 .. options.mode .. " mode).")
1250 if options.mode == "full" then
1251 core.chat_send_all(S("Clearing all objects. This may take a long time. "
1252 .. "You may experience a timeout. (by @1)", name))
1254 core.clear_objects(options)
1255 core.log("action", "Object clearing done.")
1256 core.chat_send_all("*** "..S("Cleared all objects."))
1261 core.register_chatcommand("msg", {
1262 params = S("<name> <message>"),
1263 description = S("Send a direct message to a player"),
1264 privs = {shout=true},
1265 func = function(name, param)
1266 local sendto, message = param:match("^(%S+)%s(.+)$")
1268 return false, S("Invalid usage, see /help msg.")
1270 if not core.get_player_by_name(sendto) then
1271 return false, S("The player @1 is not online.", sendto)
1273 core.log("action", "DM from " .. name .. " to " .. sendto
1275 core.chat_send_player(sendto, S("DM from @1: @2", name, message))
1276 return true, S("Message sent.")
1280 core.register_chatcommand("last-login", {
1281 params = S("[<name>]"),
1282 description = S("Get the last login time of a player or yourself"),
1283 func = function(name, param)
1287 local pauth = core.get_auth_handler().get_auth(param)
1288 if pauth and pauth.last_login and pauth.last_login ~= -1 then
1289 -- Time in UTC, ISO 8601 format
1290 return true, S("@1's last login time was @2.",
1292 os.date("!%Y-%m-%dT%H:%M:%SZ", pauth.last_login))
1294 return false, S("@1's last login time is unknown.", param)
1298 core.register_chatcommand("clearinv", {
1299 params = S("[<name>]"),
1300 description = S("Clear the inventory of yourself or another player"),
1301 func = function(name, param)
1303 if param and param ~= "" and param ~= name then
1304 if not core.check_player_privs(name, {server=true}) then
1305 return false, S("You don't have permission to "
1306 .. "clear another player's inventory "
1307 .. "(missing privilege: @1).", "server")
1309 player = core.get_player_by_name(param)
1310 core.chat_send_player(param, S("@1 cleared your inventory.", name))
1312 player = core.get_player_by_name(name)
1316 player:get_inventory():set_list("main", {})
1317 player:get_inventory():set_list("craft", {})
1318 player:get_inventory():set_list("craftpreview", {})
1319 core.log("action", name.." clears "..player:get_player_name().."'s inventory")
1320 return true, S("Cleared @1's inventory.", player:get_player_name())
1322 return false, S("Player must be online to clear inventory!")
1327 local function handle_kill_command(killer, victim)
1328 if core.settings:get_bool("enable_damage") == false then
1329 return false, S("Players can't be killed, damage has been disabled.")
1331 local victimref = core.get_player_by_name(victim)
1332 if victimref == nil then
1333 return false, S("Player @1 is not online.", victim)
1334 elseif victimref:get_hp() <= 0 then
1335 if killer == victim then
1336 return false, S("You are already dead.")
1338 return false, S("@1 is already dead.", victim)
1341 if killer ~= victim then
1342 core.log("action", string.format("%s killed %s", killer, victim))
1346 return true, S("@1 has been killed.", victim)
1349 core.register_chatcommand("kill", {
1350 params = S("[<name>]"),
1351 description = S("Kill player or yourself"),
1352 privs = {server=true},
1353 func = function(name, param)
1354 return handle_kill_command(name, param == "" and name or param)