chat.lua 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086
  1. -- Minetest: builtin/game/chat.lua
  2. --
  3. -- Chat message formatter
  4. --
  5. -- Implemented in Lua to allow redefinition
  6. function core.format_chat_message(name, message)
  7. local str = core.settings:get("chat_message_format")
  8. local error_str = "Invalid chat message format - missing %s"
  9. local i
  10. str, i = str:gsub("@name", name, 1)
  11. if i == 0 then
  12. error(error_str:format("@name"), 2)
  13. end
  14. str, i = str:gsub("@message", message, 1)
  15. if i == 0 then
  16. error(error_str:format("@message"), 2)
  17. end
  18. str = str:gsub("@timestamp", os.date("%H:%M:%S", os.time()), 1)
  19. return str
  20. end
  21. --
  22. -- Chat command handler
  23. --
  24. core.chatcommands = core.registered_chatcommands -- BACKWARDS COMPATIBILITY
  25. core.register_on_chat_message(function(name, message)
  26. if message:sub(1,1) ~= "/" then
  27. return
  28. end
  29. local cmd, param = string.match(message, "^/([^ ]+) *(.*)")
  30. if not cmd then
  31. core.chat_send_player(name, "-!- Empty command")
  32. return true
  33. end
  34. param = param or ""
  35. local cmd_def = core.registered_chatcommands[cmd]
  36. if not cmd_def then
  37. core.chat_send_player(name, "-!- Invalid command: " .. cmd)
  38. return true
  39. end
  40. local has_privs, missing_privs = core.check_player_privs(name, cmd_def.privs)
  41. if has_privs then
  42. core.set_last_run_mod(cmd_def.mod_origin)
  43. local _, result = cmd_def.func(name, param)
  44. if result then
  45. core.chat_send_player(name, result)
  46. end
  47. else
  48. core.chat_send_player(name, "You don't have permission"
  49. .. " to run this command (missing privileges: "
  50. .. table.concat(missing_privs, ", ") .. ")")
  51. end
  52. return true -- Handled chat message
  53. end)
  54. if core.settings:get_bool("profiler.load") then
  55. -- Run after register_chatcommand and its register_on_chat_message
  56. -- Before any chatcommands that should be profiled
  57. profiler.init_chatcommand()
  58. end
  59. -- Parses a "range" string in the format of "here (number)" or
  60. -- "(x1, y1, z1) (x2, y2, z2)", returning two position vectors
  61. local function parse_range_str(player_name, str)
  62. local p1, p2
  63. local args = str:split(" ")
  64. if args[1] == "here" then
  65. p1, p2 = core.get_player_radius_area(player_name, tonumber(args[2]))
  66. if p1 == nil then
  67. return false, "Unable to get player " .. player_name .. " position"
  68. end
  69. else
  70. p1, p2 = core.string_to_area(str)
  71. if p1 == nil then
  72. return false, "Incorrect area format. Expected: (x1,y1,z1) (x2,y2,z2)"
  73. end
  74. end
  75. return p1, p2
  76. end
  77. --
  78. -- Chat commands
  79. --
  80. core.register_chatcommand("me", {
  81. params = "<action>",
  82. description = "Show chat action (e.g., '/me orders a pizza' displays"
  83. .. " '<player name> orders a pizza')",
  84. privs = {shout=true},
  85. func = function(name, param)
  86. core.chat_send_all("* " .. name .. " " .. param)
  87. end,
  88. })
  89. core.register_chatcommand("admin", {
  90. description = "Show the name of the server owner",
  91. func = function(name)
  92. local admin = core.settings:get("name")
  93. if admin then
  94. return true, "The administrator of this server is " .. admin .. "."
  95. else
  96. return false, "There's no administrator named in the config file."
  97. end
  98. end,
  99. })
  100. core.register_chatcommand("privs", {
  101. params = "[<name>]",
  102. description = "Show privileges of yourself or another player",
  103. func = function(caller, param)
  104. param = param:trim()
  105. local name = (param ~= "" and param or caller)
  106. if not core.player_exists(name) then
  107. return false, "Player " .. name .. " does not exist."
  108. end
  109. return true, "Privileges of " .. name .. ": "
  110. .. core.privs_to_string(
  111. core.get_player_privs(name), ' ')
  112. end,
  113. })
  114. core.register_chatcommand("haspriv", {
  115. params = "<privilege>",
  116. description = "Return list of all online players with privilege.",
  117. privs = {basic_privs = true},
  118. func = function(caller, param)
  119. param = param:trim()
  120. if param == "" then
  121. return false, "Invalid parameters (see /help haspriv)"
  122. end
  123. if not core.registered_privileges[param] then
  124. return false, "Unknown privilege!"
  125. end
  126. local privs = core.string_to_privs(param)
  127. local players_with_priv = {}
  128. for _, player in pairs(core.get_connected_players()) do
  129. local player_name = player:get_player_name()
  130. if core.check_player_privs(player_name, privs) then
  131. table.insert(players_with_priv, player_name)
  132. end
  133. end
  134. return true, "Players online with the \"" .. param .. "\" privilege: " ..
  135. table.concat(players_with_priv, ", ")
  136. end
  137. })
  138. local function handle_grant_command(caller, grantname, grantprivstr)
  139. local caller_privs = core.get_player_privs(caller)
  140. if not (caller_privs.privs or caller_privs.basic_privs) then
  141. return false, "Your privileges are insufficient."
  142. end
  143. if not core.get_auth_handler().get_auth(grantname) then
  144. return false, "Player " .. grantname .. " does not exist."
  145. end
  146. local grantprivs = core.string_to_privs(grantprivstr)
  147. if grantprivstr == "all" then
  148. grantprivs = core.registered_privileges
  149. end
  150. local privs = core.get_player_privs(grantname)
  151. local privs_unknown = ""
  152. local basic_privs =
  153. core.string_to_privs(core.settings:get("basic_privs") or "interact,shout")
  154. for priv, _ in pairs(grantprivs) do
  155. if not basic_privs[priv] and not caller_privs.privs then
  156. return false, "Your privileges are insufficient."
  157. end
  158. if not core.registered_privileges[priv] then
  159. privs_unknown = privs_unknown .. "Unknown privilege: " .. priv .. "\n"
  160. end
  161. privs[priv] = true
  162. end
  163. if privs_unknown ~= "" then
  164. return false, privs_unknown
  165. end
  166. for priv, _ in pairs(grantprivs) do
  167. core.run_priv_callbacks(grantname, priv, caller, "grant")
  168. end
  169. core.set_player_privs(grantname, privs)
  170. core.log("action", caller..' granted ('..core.privs_to_string(grantprivs, ', ')..') privileges to '..grantname)
  171. if grantname ~= caller then
  172. core.chat_send_player(grantname, caller
  173. .. " granted you privileges: "
  174. .. core.privs_to_string(grantprivs, ' '))
  175. end
  176. return true, "Privileges of " .. grantname .. ": "
  177. .. core.privs_to_string(
  178. core.get_player_privs(grantname), ' ')
  179. end
  180. core.register_chatcommand("grant", {
  181. params = "<name> (<privilege> | all)",
  182. description = "Give privileges to player",
  183. func = function(name, param)
  184. local grantname, grantprivstr = string.match(param, "([^ ]+) (.+)")
  185. if not grantname or not grantprivstr then
  186. return false, "Invalid parameters (see /help grant)"
  187. end
  188. return handle_grant_command(name, grantname, grantprivstr)
  189. end,
  190. })
  191. core.register_chatcommand("grantme", {
  192. params = "<privilege> | all",
  193. description = "Grant privileges to yourself",
  194. func = function(name, param)
  195. if param == "" then
  196. return false, "Invalid parameters (see /help grantme)"
  197. end
  198. return handle_grant_command(name, name, param)
  199. end,
  200. })
  201. core.register_chatcommand("revoke", {
  202. params = "<name> (<privilege> | all)",
  203. description = "Remove privileges from player",
  204. privs = {},
  205. func = function(name, param)
  206. if not core.check_player_privs(name, {privs=true}) and
  207. not core.check_player_privs(name, {basic_privs=true}) then
  208. return false, "Your privileges are insufficient."
  209. end
  210. local revoke_name, revoke_priv_str = string.match(param, "([^ ]+) (.+)")
  211. if not revoke_name or not revoke_priv_str then
  212. return false, "Invalid parameters (see /help revoke)"
  213. elseif not core.get_auth_handler().get_auth(revoke_name) then
  214. return false, "Player " .. revoke_name .. " does not exist."
  215. end
  216. local revoke_privs = core.string_to_privs(revoke_priv_str)
  217. local privs = core.get_player_privs(revoke_name)
  218. local basic_privs =
  219. core.string_to_privs(core.settings:get("basic_privs") or "interact,shout")
  220. for priv, _ in pairs(revoke_privs) do
  221. if not basic_privs[priv] and
  222. not core.check_player_privs(name, {privs=true}) then
  223. return false, "Your privileges are insufficient."
  224. end
  225. end
  226. if revoke_priv_str == "all" then
  227. revoke_privs = privs
  228. privs = {}
  229. else
  230. for priv, _ in pairs(revoke_privs) do
  231. privs[priv] = nil
  232. end
  233. end
  234. for priv, _ in pairs(revoke_privs) do
  235. core.run_priv_callbacks(revoke_name, priv, name, "revoke")
  236. end
  237. core.set_player_privs(revoke_name, privs)
  238. core.log("action", name..' revoked ('
  239. ..core.privs_to_string(revoke_privs, ', ')
  240. ..') privileges from '..revoke_name)
  241. if revoke_name ~= name then
  242. core.chat_send_player(revoke_name, name
  243. .. " revoked privileges from you: "
  244. .. core.privs_to_string(revoke_privs, ' '))
  245. end
  246. return true, "Privileges of " .. revoke_name .. ": "
  247. .. core.privs_to_string(
  248. core.get_player_privs(revoke_name), ' ')
  249. end,
  250. })
  251. core.register_chatcommand("setpassword", {
  252. params = "<name> <password>",
  253. description = "Set player's password",
  254. privs = {password=true},
  255. func = function(name, param)
  256. local toname, raw_password = string.match(param, "^([^ ]+) +(.+)$")
  257. if not toname then
  258. toname = param:match("^([^ ]+) *$")
  259. raw_password = nil
  260. end
  261. if not toname then
  262. return false, "Name field required"
  263. end
  264. local act_str_past, act_str_pres
  265. if not raw_password then
  266. core.set_player_password(toname, "")
  267. act_str_past = "cleared"
  268. act_str_pres = "clears"
  269. else
  270. core.set_player_password(toname,
  271. core.get_password_hash(toname,
  272. raw_password))
  273. act_str_past = "set"
  274. act_str_pres = "sets"
  275. end
  276. if toname ~= name then
  277. core.chat_send_player(toname, "Your password was "
  278. .. act_str_past .. " by " .. name)
  279. end
  280. core.log("action", name .. " " .. act_str_pres ..
  281. " password of " .. toname .. ".")
  282. return true, "Password of player \"" .. toname .. "\" " .. act_str_past
  283. end,
  284. })
  285. core.register_chatcommand("clearpassword", {
  286. params = "<name>",
  287. description = "Set empty password for a player",
  288. privs = {password=true},
  289. func = function(name, param)
  290. local toname = param
  291. if toname == "" then
  292. return false, "Name field required"
  293. end
  294. core.set_player_password(toname, '')
  295. core.log("action", name .. " clears password of " .. toname .. ".")
  296. return true, "Password of player \"" .. toname .. "\" cleared"
  297. end,
  298. })
  299. core.register_chatcommand("auth_reload", {
  300. params = "",
  301. description = "Reload authentication data",
  302. privs = {server=true},
  303. func = function(name, param)
  304. local done = core.auth_reload()
  305. return done, (done and "Done." or "Failed.")
  306. end,
  307. })
  308. core.register_chatcommand("remove_player", {
  309. params = "<name>",
  310. description = "Remove a player's data",
  311. privs = {server=true},
  312. func = function(name, param)
  313. local toname = param
  314. if toname == "" then
  315. return false, "Name field required"
  316. end
  317. local rc = core.remove_player(toname)
  318. if rc == 0 then
  319. core.log("action", name .. " removed player data of " .. toname .. ".")
  320. return true, "Player \"" .. toname .. "\" removed."
  321. elseif rc == 1 then
  322. return true, "No such player \"" .. toname .. "\" to remove."
  323. elseif rc == 2 then
  324. return true, "Player \"" .. toname .. "\" is connected, cannot remove."
  325. end
  326. return false, "Unhandled remove_player return code " .. rc .. ""
  327. end,
  328. })
  329. core.register_chatcommand("teleport", {
  330. params = "<X>,<Y>,<Z> | <to_name> | (<name> <X>,<Y>,<Z>) | (<name> <to_name>)",
  331. description = "Teleport to position or player",
  332. privs = {teleport=true},
  333. func = function(name, param)
  334. -- Returns (pos, true) if found, otherwise (pos, false)
  335. local function find_free_position_near(pos)
  336. local tries = {
  337. {x=1,y=0,z=0},
  338. {x=-1,y=0,z=0},
  339. {x=0,y=0,z=1},
  340. {x=0,y=0,z=-1},
  341. }
  342. for _, d in ipairs(tries) do
  343. local p = {x = pos.x+d.x, y = pos.y+d.y, z = pos.z+d.z}
  344. local n = core.get_node_or_nil(p)
  345. if n and n.name then
  346. local def = core.registered_nodes[n.name]
  347. if def and not def.walkable then
  348. return p, true
  349. end
  350. end
  351. end
  352. return pos, false
  353. end
  354. local p = {}
  355. p.x, p.y, p.z = string.match(param, "^([%d.-]+)[, ] *([%d.-]+)[, ] *([%d.-]+)$")
  356. p.x = tonumber(p.x)
  357. p.y = tonumber(p.y)
  358. p.z = tonumber(p.z)
  359. if p.x and p.y and p.z then
  360. local lm = 31000
  361. if p.x < -lm or p.x > lm or p.y < -lm or p.y > lm or p.z < -lm or p.z > lm then
  362. return false, "Cannot teleport out of map bounds!"
  363. end
  364. local teleportee = core.get_player_by_name(name)
  365. if teleportee then
  366. teleportee:set_pos(p)
  367. return true, "Teleporting to "..core.pos_to_string(p)
  368. end
  369. end
  370. local target_name = param:match("^([^ ]+)$")
  371. local teleportee = core.get_player_by_name(name)
  372. p = nil
  373. if target_name then
  374. local target = core.get_player_by_name(target_name)
  375. if target then
  376. p = target:get_pos()
  377. end
  378. end
  379. if teleportee and p then
  380. p = find_free_position_near(p)
  381. teleportee:set_pos(p)
  382. return true, "Teleporting to " .. target_name
  383. .. " at "..core.pos_to_string(p)
  384. end
  385. if not core.check_player_privs(name, {bring=true}) then
  386. return false, "You don't have permission to teleport other players (missing bring privilege)"
  387. end
  388. teleportee = nil
  389. p = {}
  390. local teleportee_name
  391. teleportee_name, p.x, p.y, p.z = param:match(
  392. "^([^ ]+) +([%d.-]+)[, ] *([%d.-]+)[, ] *([%d.-]+)$")
  393. p.x, p.y, p.z = tonumber(p.x), tonumber(p.y), tonumber(p.z)
  394. if teleportee_name then
  395. teleportee = core.get_player_by_name(teleportee_name)
  396. end
  397. if teleportee and p.x and p.y and p.z then
  398. teleportee:set_pos(p)
  399. return true, "Teleporting " .. teleportee_name
  400. .. " to " .. core.pos_to_string(p)
  401. end
  402. teleportee = nil
  403. p = nil
  404. teleportee_name, target_name = string.match(param, "^([^ ]+) +([^ ]+)$")
  405. if teleportee_name then
  406. teleportee = core.get_player_by_name(teleportee_name)
  407. end
  408. if target_name then
  409. local target = core.get_player_by_name(target_name)
  410. if target then
  411. p = target:get_pos()
  412. end
  413. end
  414. if teleportee and p then
  415. p = find_free_position_near(p)
  416. teleportee:set_pos(p)
  417. return true, "Teleporting " .. teleportee_name
  418. .. " to " .. target_name
  419. .. " at " .. core.pos_to_string(p)
  420. end
  421. return false, 'Invalid parameters ("' .. param
  422. .. '") or player not found (see /help teleport)'
  423. end,
  424. })
  425. core.register_chatcommand("set", {
  426. params = "([-n] <name> <value>) | <name>",
  427. description = "Set or read server configuration setting",
  428. privs = {server=true},
  429. func = function(name, param)
  430. local arg, setname, setvalue = string.match(param, "(-[n]) ([^ ]+) (.+)")
  431. if arg and arg == "-n" and setname and setvalue then
  432. core.settings:set(setname, setvalue)
  433. return true, setname .. " = " .. setvalue
  434. end
  435. setname, setvalue = string.match(param, "([^ ]+) (.+)")
  436. if setname and setvalue then
  437. if not core.settings:get(setname) then
  438. return false, "Failed. Use '/set -n <name> <value>' to create a new setting."
  439. end
  440. core.settings:set(setname, setvalue)
  441. return true, setname .. " = " .. setvalue
  442. end
  443. setname = string.match(param, "([^ ]+)")
  444. if setname then
  445. setvalue = core.settings:get(setname)
  446. if not setvalue then
  447. setvalue = "<not set>"
  448. end
  449. return true, setname .. " = " .. setvalue
  450. end
  451. return false, "Invalid parameters (see /help set)."
  452. end,
  453. })
  454. local function emergeblocks_callback(pos, action, num_calls_remaining, ctx)
  455. if ctx.total_blocks == 0 then
  456. ctx.total_blocks = num_calls_remaining + 1
  457. ctx.current_blocks = 0
  458. end
  459. ctx.current_blocks = ctx.current_blocks + 1
  460. if ctx.current_blocks == ctx.total_blocks then
  461. core.chat_send_player(ctx.requestor_name,
  462. string.format("Finished emerging %d blocks in %.2fms.",
  463. ctx.total_blocks, (os.clock() - ctx.start_time) * 1000))
  464. end
  465. end
  466. local function emergeblocks_progress_update(ctx)
  467. if ctx.current_blocks ~= ctx.total_blocks then
  468. core.chat_send_player(ctx.requestor_name,
  469. string.format("emergeblocks update: %d/%d blocks emerged (%.1f%%)",
  470. ctx.current_blocks, ctx.total_blocks,
  471. (ctx.current_blocks / ctx.total_blocks) * 100))
  472. core.after(2, emergeblocks_progress_update, ctx)
  473. end
  474. end
  475. core.register_chatcommand("emergeblocks", {
  476. params = "(here [<radius>]) | (<pos1> <pos2>)",
  477. description = "Load (or, if nonexistent, generate) map blocks "
  478. .. "contained in area pos1 to pos2 (<pos1> and <pos2> must be in parentheses)",
  479. privs = {server=true},
  480. func = function(name, param)
  481. local p1, p2 = parse_range_str(name, param)
  482. if p1 == false then
  483. return false, p2
  484. end
  485. local context = {
  486. current_blocks = 0,
  487. total_blocks = 0,
  488. start_time = os.clock(),
  489. requestor_name = name
  490. }
  491. core.emerge_area(p1, p2, emergeblocks_callback, context)
  492. core.after(2, emergeblocks_progress_update, context)
  493. return true, "Started emerge of area ranging from " ..
  494. core.pos_to_string(p1, 1) .. " to " .. core.pos_to_string(p2, 1)
  495. end,
  496. })
  497. core.register_chatcommand("deleteblocks", {
  498. params = "(here [<radius>]) | (<pos1> <pos2>)",
  499. description = "Delete map blocks contained in area pos1 to pos2 "
  500. .. "(<pos1> and <pos2> must be in parentheses)",
  501. privs = {server=true},
  502. func = function(name, param)
  503. local p1, p2 = parse_range_str(name, param)
  504. if p1 == false then
  505. return false, p2
  506. end
  507. if core.delete_area(p1, p2) then
  508. return true, "Successfully cleared area ranging from " ..
  509. core.pos_to_string(p1, 1) .. " to " .. core.pos_to_string(p2, 1)
  510. else
  511. return false, "Failed to clear one or more blocks in area"
  512. end
  513. end,
  514. })
  515. core.register_chatcommand("fixlight", {
  516. params = "(here [<radius>]) | (<pos1> <pos2>)",
  517. description = "Resets lighting in the area between pos1 and pos2 "
  518. .. "(<pos1> and <pos2> must be in parentheses)",
  519. privs = {server = true},
  520. func = function(name, param)
  521. local p1, p2 = parse_range_str(name, param)
  522. if p1 == false then
  523. return false, p2
  524. end
  525. if core.fix_light(p1, p2) then
  526. return true, "Successfully reset light in the area ranging from " ..
  527. core.pos_to_string(p1, 1) .. " to " .. core.pos_to_string(p2, 1)
  528. else
  529. return false, "Failed to load one or more blocks in area"
  530. end
  531. end,
  532. })
  533. core.register_chatcommand("mods", {
  534. params = "",
  535. description = "List mods installed on the server",
  536. privs = {},
  537. func = function(name, param)
  538. return true, table.concat(core.get_modnames(), ", ")
  539. end,
  540. })
  541. local function handle_give_command(cmd, giver, receiver, stackstring)
  542. core.log("action", giver .. " invoked " .. cmd
  543. .. ', stackstring="' .. stackstring .. '"')
  544. local itemstack = ItemStack(stackstring)
  545. if itemstack:is_empty() then
  546. return false, "Cannot give an empty item"
  547. elseif (not itemstack:is_known()) or (itemstack:get_name() == "unknown") then
  548. return false, "Cannot give an unknown item"
  549. -- Forbid giving 'ignore' due to unwanted side effects
  550. elseif itemstack:get_name() == "ignore" then
  551. return false, "Giving 'ignore' is not allowed"
  552. end
  553. local receiverref = core.get_player_by_name(receiver)
  554. if receiverref == nil then
  555. return false, receiver .. " is not a known player"
  556. end
  557. local leftover = receiverref:get_inventory():add_item("main", itemstack)
  558. local partiality
  559. if leftover:is_empty() then
  560. partiality = ""
  561. elseif leftover:get_count() == itemstack:get_count() then
  562. partiality = "could not be "
  563. else
  564. partiality = "partially "
  565. end
  566. -- The actual item stack string may be different from what the "giver"
  567. -- entered (e.g. big numbers are always interpreted as 2^16-1).
  568. stackstring = itemstack:to_string()
  569. if giver == receiver then
  570. local msg = "%q %sadded to inventory."
  571. return true, msg:format(stackstring, partiality)
  572. else
  573. core.chat_send_player(receiver, ("%q %sadded to inventory.")
  574. :format(stackstring, partiality))
  575. local msg = "%q %sadded to %s's inventory."
  576. return true, msg:format(stackstring, partiality, receiver)
  577. end
  578. end
  579. core.register_chatcommand("give", {
  580. params = "<name> <ItemString> [<count> [<wear>]]",
  581. description = "Give item to player",
  582. privs = {give=true},
  583. func = function(name, param)
  584. local toname, itemstring = string.match(param, "^([^ ]+) +(.+)$")
  585. if not toname or not itemstring then
  586. return false, "Name and ItemString required"
  587. end
  588. return handle_give_command("/give", name, toname, itemstring)
  589. end,
  590. })
  591. core.register_chatcommand("giveme", {
  592. params = "<ItemString> [<count> [<wear>]]",
  593. description = "Give item to yourself",
  594. privs = {give=true},
  595. func = function(name, param)
  596. local itemstring = string.match(param, "(.+)$")
  597. if not itemstring then
  598. return false, "ItemString required"
  599. end
  600. return handle_give_command("/giveme", name, name, itemstring)
  601. end,
  602. })
  603. core.register_chatcommand("spawnentity", {
  604. params = "<EntityName> [<X>,<Y>,<Z>]",
  605. description = "Spawn entity at given (or your) position",
  606. privs = {give=true, interact=true},
  607. func = function(name, param)
  608. local entityname, p = string.match(param, "^([^ ]+) *(.*)$")
  609. if not entityname then
  610. return false, "EntityName required"
  611. end
  612. core.log("action", ("%s invokes /spawnentity, entityname=%q")
  613. :format(name, entityname))
  614. local player = core.get_player_by_name(name)
  615. if player == nil then
  616. core.log("error", "Unable to spawn entity, player is nil")
  617. return false, "Unable to spawn entity, player is nil"
  618. end
  619. if not core.registered_entities[entityname] then
  620. return false, "Cannot spawn an unknown entity"
  621. end
  622. if p == "" then
  623. p = player:get_pos()
  624. else
  625. p = core.string_to_pos(p)
  626. if p == nil then
  627. return false, "Invalid parameters ('" .. param .. "')"
  628. end
  629. end
  630. p.y = p.y + 1
  631. core.add_entity(p, entityname)
  632. return true, ("%q spawned."):format(entityname)
  633. end,
  634. })
  635. core.register_chatcommand("pulverize", {
  636. params = "",
  637. description = "Destroy item in hand",
  638. func = function(name, param)
  639. local player = core.get_player_by_name(name)
  640. if not player then
  641. core.log("error", "Unable to pulverize, no player.")
  642. return false, "Unable to pulverize, no player."
  643. end
  644. local wielded_item = player:get_wielded_item()
  645. if wielded_item:is_empty() then
  646. return false, "Unable to pulverize, no item in hand."
  647. end
  648. core.log("action", name .. " pulverized \"" ..
  649. wielded_item:get_name() .. " " .. wielded_item:get_count() .. "\"")
  650. player:set_wielded_item(nil)
  651. return true, "An item was pulverized."
  652. end,
  653. })
  654. -- Key = player name
  655. core.rollback_punch_callbacks = {}
  656. core.register_on_punchnode(function(pos, node, puncher)
  657. local name = puncher and puncher:get_player_name()
  658. if name and core.rollback_punch_callbacks[name] then
  659. core.rollback_punch_callbacks[name](pos, node, puncher)
  660. core.rollback_punch_callbacks[name] = nil
  661. end
  662. end)
  663. core.register_chatcommand("rollback_check", {
  664. params = "[<range>] [<seconds>] [<limit>]",
  665. description = "Check who last touched a node or a node near it"
  666. .. " within the time specified by <seconds>. Default: range = 0,"
  667. .. " seconds = 86400 = 24h, limit = 5",
  668. privs = {rollback=true},
  669. func = function(name, param)
  670. if not core.settings:get_bool("enable_rollback_recording") then
  671. return false, "Rollback functions are disabled."
  672. end
  673. local range, seconds, limit =
  674. param:match("(%d+) *(%d*) *(%d*)")
  675. range = tonumber(range) or 0
  676. seconds = tonumber(seconds) or 86400
  677. limit = tonumber(limit) or 5
  678. if limit > 100 then
  679. return false, "That limit is too high!"
  680. end
  681. core.rollback_punch_callbacks[name] = function(pos, node, puncher)
  682. local name = puncher:get_player_name()
  683. core.chat_send_player(name, "Checking " .. core.pos_to_string(pos) .. "...")
  684. local actions = core.rollback_get_node_actions(pos, range, seconds, limit)
  685. if not actions then
  686. core.chat_send_player(name, "Rollback functions are disabled")
  687. return
  688. end
  689. local num_actions = #actions
  690. if num_actions == 0 then
  691. core.chat_send_player(name, "Nobody has touched"
  692. .. " the specified location in "
  693. .. seconds .. " seconds")
  694. return
  695. end
  696. local time = os.time()
  697. for i = num_actions, 1, -1 do
  698. local action = actions[i]
  699. core.chat_send_player(name,
  700. ("%s %s %s -> %s %d seconds ago.")
  701. :format(
  702. core.pos_to_string(action.pos),
  703. action.actor,
  704. action.oldnode.name,
  705. action.newnode.name,
  706. time - action.time))
  707. end
  708. end
  709. return true, "Punch a node (range=" .. range .. ", seconds="
  710. .. seconds .. "s, limit=" .. limit .. ")"
  711. end,
  712. })
  713. core.register_chatcommand("rollback", {
  714. params = "(<name> [<seconds>]) | (:<actor> [<seconds>])",
  715. description = "Revert actions of a player. Default for <seconds> is 60",
  716. privs = {rollback=true},
  717. func = function(name, param)
  718. if not core.settings:get_bool("enable_rollback_recording") then
  719. return false, "Rollback functions are disabled."
  720. end
  721. local target_name, seconds = string.match(param, ":([^ ]+) *(%d*)")
  722. if not target_name then
  723. local player_name
  724. player_name, seconds = string.match(param, "([^ ]+) *(%d*)")
  725. if not player_name then
  726. return false, "Invalid parameters. See /help rollback"
  727. .. " and /help rollback_check."
  728. end
  729. target_name = "player:"..player_name
  730. end
  731. seconds = tonumber(seconds) or 60
  732. core.chat_send_player(name, "Reverting actions of "
  733. .. target_name .. " since "
  734. .. seconds .. " seconds.")
  735. local success, log = core.rollback_revert_actions_by(
  736. target_name, seconds)
  737. local response = ""
  738. if #log > 100 then
  739. response = "(log is too long to show)\n"
  740. else
  741. for _, line in pairs(log) do
  742. response = response .. line .. "\n"
  743. end
  744. end
  745. response = response .. "Reverting actions "
  746. .. (success and "succeeded." or "FAILED.")
  747. return success, response
  748. end,
  749. })
  750. core.register_chatcommand("status", {
  751. description = "Show server status",
  752. func = function(name, param)
  753. local status = core.get_server_status(name, false)
  754. if status and status ~= "" then
  755. return true, status
  756. end
  757. return false, "This command was disabled by a mod or game"
  758. end,
  759. })
  760. core.register_chatcommand("time", {
  761. params = "[<0..23>:<0..59> | <0..24000>]",
  762. description = "Show or set time of day",
  763. privs = {},
  764. func = function(name, param)
  765. if param == "" then
  766. local current_time = math.floor(core.get_timeofday() * 1440)
  767. local minutes = current_time % 60
  768. local hour = (current_time - minutes) / 60
  769. return true, ("Current time is %d:%02d"):format(hour, minutes)
  770. end
  771. local player_privs = core.get_player_privs(name)
  772. if not player_privs.settime then
  773. return false, "You don't have permission to run this command " ..
  774. "(missing privilege: settime)."
  775. end
  776. local hour, minute = param:match("^(%d+):(%d+)$")
  777. if not hour then
  778. local new_time = tonumber(param)
  779. if not new_time then
  780. return false, "Invalid time."
  781. end
  782. -- Backward compatibility.
  783. core.set_timeofday((new_time % 24000) / 24000)
  784. core.log("action", name .. " sets time to " .. new_time)
  785. return true, "Time of day changed."
  786. end
  787. hour = tonumber(hour)
  788. minute = tonumber(minute)
  789. if hour < 0 or hour > 23 then
  790. return false, "Invalid hour (must be between 0 and 23 inclusive)."
  791. elseif minute < 0 or minute > 59 then
  792. return false, "Invalid minute (must be between 0 and 59 inclusive)."
  793. end
  794. core.set_timeofday((hour * 60 + minute) / 1440)
  795. core.log("action", ("%s sets time to %d:%02d"):format(name, hour, minute))
  796. return true, "Time of day changed."
  797. end,
  798. })
  799. core.register_chatcommand("days", {
  800. description = "Show day count since world creation",
  801. func = function(name, param)
  802. return true, "Current day is " .. core.get_day_count()
  803. end
  804. })
  805. core.register_chatcommand("shutdown", {
  806. params = "[<delay_in_seconds> | -1] [reconnect] [<message>]",
  807. description = "Shutdown server (-1 cancels a delayed shutdown)",
  808. privs = {server=true},
  809. func = function(name, param)
  810. local delay, reconnect, message
  811. delay, param = param:match("^%s*(%S+)(.*)")
  812. if param then
  813. reconnect, param = param:match("^%s*(%S+)(.*)")
  814. end
  815. message = param and param:match("^%s*(.+)") or ""
  816. delay = tonumber(delay) or 0
  817. if delay == 0 then
  818. core.log("action", name .. " shuts down server")
  819. core.chat_send_all("*** Server shutting down (operator request).")
  820. end
  821. core.request_shutdown(message:trim(), core.is_yes(reconnect), delay)
  822. end,
  823. })
  824. core.register_chatcommand("ban", {
  825. params = "[<name> | <IP_address>]",
  826. description = "Ban player or show ban list",
  827. privs = {ban=true},
  828. func = function(name, param)
  829. if param == "" then
  830. local ban_list = core.get_ban_list()
  831. if ban_list == "" then
  832. return true, "The ban list is empty."
  833. else
  834. return true, "Ban list: " .. ban_list
  835. end
  836. end
  837. if not core.get_player_by_name(param) then
  838. return false, "No such player."
  839. end
  840. if not core.ban_player(param) then
  841. return false, "Failed to ban player."
  842. end
  843. local desc = core.get_ban_description(param)
  844. core.log("action", name .. " bans " .. desc .. ".")
  845. return true, "Banned " .. desc .. "."
  846. end,
  847. })
  848. core.register_chatcommand("unban", {
  849. params = "<name> | <IP_address>",
  850. description = "Remove player ban",
  851. privs = {ban=true},
  852. func = function(name, param)
  853. if not core.unban_player_or_ip(param) then
  854. return false, "Failed to unban player/IP."
  855. end
  856. core.log("action", name .. " unbans " .. param)
  857. return true, "Unbanned " .. param
  858. end,
  859. })
  860. core.register_chatcommand("kick", {
  861. params = "<name> [<reason>]",
  862. description = "Kick a player",
  863. privs = {kick=true},
  864. func = function(name, param)
  865. local tokick, reason = param:match("([^ ]+) (.+)")
  866. tokick = tokick or param
  867. if not core.kick_player(tokick, reason) then
  868. return false, "Failed to kick player " .. tokick
  869. end
  870. local log_reason = ""
  871. if reason then
  872. log_reason = " with reason \"" .. reason .. "\""
  873. end
  874. core.log("action", name .. " kicks " .. tokick .. log_reason)
  875. return true, "Kicked " .. tokick
  876. end,
  877. })
  878. core.register_chatcommand("clearobjects", {
  879. params = "[full | quick]",
  880. description = "Clear all objects in world",
  881. privs = {server=true},
  882. func = function(name, param)
  883. local options = {}
  884. if param == "" or param == "quick" then
  885. options.mode = "quick"
  886. elseif param == "full" then
  887. options.mode = "full"
  888. else
  889. return false, "Invalid usage, see /help clearobjects."
  890. end
  891. core.log("action", name .. " clears all objects ("
  892. .. options.mode .. " mode).")
  893. core.chat_send_all("Clearing all objects. This may take long."
  894. .. " You may experience a timeout. (by "
  895. .. name .. ")")
  896. core.clear_objects(options)
  897. core.log("action", "Object clearing done.")
  898. core.chat_send_all("*** Cleared all objects.")
  899. end,
  900. })
  901. core.register_chatcommand("msg", {
  902. params = "<name> <message>",
  903. description = "Send a private message",
  904. privs = {shout=true},
  905. func = function(name, param)
  906. local sendto, message = param:match("^(%S+)%s(.+)$")
  907. if not sendto then
  908. return false, "Invalid usage, see /help msg."
  909. end
  910. if not core.get_player_by_name(sendto) then
  911. return false, "The player " .. sendto
  912. .. " is not online."
  913. end
  914. core.log("action", "PM from " .. name .. " to " .. sendto
  915. .. ": " .. message)
  916. core.chat_send_player(sendto, "PM from " .. name .. ": "
  917. .. message)
  918. return true, "Message sent."
  919. end,
  920. })
  921. core.register_chatcommand("last-login", {
  922. params = "[<name>]",
  923. description = "Get the last login time of a player or yourself",
  924. func = function(name, param)
  925. if param == "" then
  926. param = name
  927. end
  928. local pauth = core.get_auth_handler().get_auth(param)
  929. if pauth and pauth.last_login then
  930. -- Time in UTC, ISO 8601 format
  931. return true, "Last login time was " ..
  932. os.date("!%Y-%m-%dT%H:%M:%SZ", pauth.last_login)
  933. end
  934. return false, "Last login time is unknown"
  935. end,
  936. })
  937. core.register_chatcommand("clearinv", {
  938. params = "[<name>]",
  939. description = "Clear the inventory of yourself or another player",
  940. func = function(name, param)
  941. local player
  942. if param and param ~= "" and param ~= name then
  943. if not core.check_player_privs(name, {server=true}) then
  944. return false, "You don't have permission"
  945. .. " to clear another player's inventory (missing privilege: server)"
  946. end
  947. player = core.get_player_by_name(param)
  948. core.chat_send_player(param, name.." cleared your inventory.")
  949. else
  950. player = core.get_player_by_name(name)
  951. end
  952. if player then
  953. player:get_inventory():set_list("main", {})
  954. player:get_inventory():set_list("craft", {})
  955. player:get_inventory():set_list("craftpreview", {})
  956. core.log("action", name.." clears "..player:get_player_name().."'s inventory")
  957. return true, "Cleared "..player:get_player_name().."'s inventory."
  958. else
  959. return false, "Player must be online to clear inventory!"
  960. end
  961. end,
  962. })
  963. local function handle_kill_command(killer, victim)
  964. if core.settings:get_bool("enable_damage") == false then
  965. return false, "Players can't be killed, damage has been disabled."
  966. end
  967. local victimref = core.get_player_by_name(victim)
  968. if victimref == nil then
  969. return false, string.format("Player %s is not online.", victim)
  970. elseif victimref:get_hp() <= 0 then
  971. if killer == victim then
  972. return false, "You are already dead."
  973. else
  974. return false, string.format("%s is already dead.", victim)
  975. end
  976. end
  977. if not killer == victim then
  978. core.log("action", string.format("%s killed %s", killer, victim))
  979. end
  980. -- Kill victim
  981. victimref:set_hp(0)
  982. return true, string.format("%s has been killed.", victim)
  983. end
  984. core.register_chatcommand("kill", {
  985. params = "[<name>]",
  986. description = "Kill player or yourself",
  987. privs = {server=true},
  988. func = function(name, param)
  989. return handle_kill_command(name, param == "" and name or param)
  990. end,
  991. })