Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

Chatted event help?

So im making a sort of command, and im wondering how I can take a part of a chatted message, and do code based on that.

Ex.

/timer 100

It does a countdown for 100

Im fairly certain it uses something like msg:sub() or something.

A wiki link would be awesome, or just a little code that tells me what it would look like would also be great!

2 answers

I always used a server script, not a local script.

game.Players.PlayerAdded:connect(function(plr)
	plr.Chatted:connect(function(msg)
		--code
	end)
end)

Now we have an event firing when a player chats. But how do we know if the first 7 characters of the message is "/timer "? We use :sub().

game.Players.PlayerAdded:connect(function(plr)
	plr.Chatted:connect(function(msg)
		if msg:sub(1,7) == "/timer " then --Remember, space counts as a character!
			local time = tonumber(msg:sub(8)) --Set the length to everything after "/timer ". tonumber() converts a string to a number.
		end
	end)
end)

Now we have checked if they used the correct command and got the length of the time. To actually do the counting down, we will create a new function that creates a hint in workspace.

function countdown(length)
	local h = Instance.new("Hint",workspace)
	for i = length,1,-1 do
		h.Text = tostring(i) --tostring() converts a number to a string.
		wait(1)
	end
	h:Destroy()
end

Now we have our countdown function. The last thing to do is to put it all together!

function countdown(length)
	local h = Instance.new("Hint",workspace)
	for i = length,1,-1 do
		h.Text = tostring(i) --tostring() converts a number to a string.
		wait(1)
	end
	h:Destroy()
end


game.Players.PlayerAdded:connect(function(plr)
	plr.Chatted:connect(function(msg)
		if msg:sub(1,7) == "/timer " then
			local time = tonumber(msg:sub(8)) 
			countdown(time)
		end
	end)
end)

Hope I helped!

1 comment

0

All I needed was to see how to get the second part, but thanks!

This discussion is preserved as it was. New answers, comments, and votes are closed.