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

Issues encountered when trying to make the game respond to certain words in chat?

I'm trying to make a system where if a player says a certain word, something happens ingame. However, I've run in an issue where the "message" parameter of the Chatted event does not match with the actual chat. For example, this demonstration code is supposed to print "hello" if you chat the words "hi", and print "x" if you chat anything else. However, whenever I test it, it always responds "x", even if I write in "hi" in chat.

local player = game.Players.LocalPlayer

player.chatted:Connect(function(message, recipient)
	if message == "hi" then
		print("hello")
	elseif message ~= "hi" then 
		print("x")		
	end	
end)

2 answers

✓ Accepted answer

This is because the message contains a newline character at the end. This is because you have to type enter to send the message.

What you have to do is "trim" the input message:

player.Chatted:Connect(function(message, recipient)
	local trimmed = message:gsub("%s+", "")
	if trimmed == "hi" then
		print("hello")
	else
		print("x")      
	end
end)

Additionally you had a few more issues. You were using chatted instead of Chatted. Also your elseif block was entirely useless, there's no reason to first off check if something equals hi, to then proceed to check if something is not hi. The elseif would always be true so in that case you can just use else.

1 comment

0

Thank you!

The player.Chatted event should be capitalized. It is very important for any language of coding that you check spelling mistakes. You may also not want to run so many events due to the fact the output would be full of "x" and "hello" which makes troubleshooting errors rather difficult. I would personally call this on a server script using the following code:


game.Players.PlayerAdded:Connect(function(player)
  player.Chatted:Connect(function(msg)
          if msg == "hi" then
	        print("hello")
	    else 
	        print("x")     
	    end

  end)
end)


1 comment

0

FloweryBoy has some more details if you are using it on the client >:)

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