--- title: Chat and Commands layout: default root: ../.. idx: 4.2 description: Registering a chatcommand and handling chat messages with register_on_chat_message redirect_from: /en/chapters/chat.html cmd_online: level: warning title: Offline players can run commands message:
A player name is passed instead of a player object because mods can run commands on behalf of offline players. For example, the IRC bridge allows players to run commands without joining the game.
So make sure that you don't assume that the player is online. You can check by seeing if
minetest.get_player_by_namereturns a player. cb_cmdsprivs: level: warning title: Privileges and Chat Commands message: The shout privilege isn't needed for a player to trigger this callback. This is because chat commands are implemented in Lua, and are just chat messages that begin with a /. --- ## Introduction Mods can interact with player chat, including sending messages, intercepting messages, and registering chat commands. - [Sending Messages to All Players](#sending-messages-to-all-players) - [Sending Messages to Specific Players](#sending-messages-to-specific-players) - [Chat Commands](#chat-commands) - [Complex Subcommands](#complex-subcommands) - [Intercepting Messages](#intercepting-messages) ## Sending Messages to All Players To send a message to every player in the game, call the chat_send_all function. ```lua minetest.chat_send_all("This is a chat message to all players") ``` Here is an example of how this appears in-game:
There is also a library written by the author of this book which can be used to make complex chat commands without patterns called Chat Command Builder.
## Intercepting Messages To intercept a message, use register_on_chat_message: ```lua minetest.register_on_chat_message(function(name, message) print(name .. " said " .. message) return false end) ``` By returning false, you allow the chat message to be sent by the default handler. You can actually remove the line `return false` and it would still work the same, because `nil` is returned implicitly and is treated like false. {% include notice.html notice=page.cb_cmdsprivs %} You should make sure you take into account that it may be a chat command, or the user may not have `shout`. ```lua minetest.register_on_chat_message(function(name, message) if message:sub(1, 1) == "/" then print(name .. " ran chat command") elseif minetest.check_player_privs(name, { shout = true }) then print(name .. " said " .. message) else print(name .. " tried to say " .. message .. " but doesn't have shout") end return false end) ```