How to make chat commands?

I wanna make a chat command like when an admin types ?warn Username it warns him but how do i get the username from a string. Like if the admin typed “?warn DevFoll” how do i get "DevFoll from that message?

To get the username from the message, you can use string manipulation in Lua. Here’s an example of how you can do it:

-- Listen for the chat command
game.Players.PlayerAdded:Connect(function(player)
    player.Chatted:Connect(function(message)
        -- Check if the message starts with the "?warn " prefix
        if string.sub(message, 1, 6) == "?warn " then
            -- Get the username from the message
            local username = string.sub(message, 7)
            
            -- Warn the player with the given username
            local targetPlayer = game.Players:FindFirstChild(username)
            if targetPlayer then
                -- Do the warning action here, e.g. send a warning message
                print("Warning issued to " .. username)
            else
                -- The player with the given username was not found
                print("Player not found: " .. username)
            end
        end
    end)
end)

In this example, we listen for the Chatted event of each player and check if the message starts with the ?warn prefix. If it does, we extract the username from the message using string.sub. The 7 argument specifies the starting position of the username in the message (i.e., after the ?warn prefix).

Once we have the username, we can use the game.Players:FindFirstChild method to get the player object with the given username. If the player is found, we can perform the warning action (e.g., send a warning message). If the player is not found, we print an error message.

1 Like

i recommend using string.split instead of string.sub as its easier to use when making multiple commands

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.