Why can't I use LocalPlayer.Chatted:Connect() in a LocalScript?

I’m trying to code something that runs everytime the LocalPlayer chats. I’ve tried using the LocalPlayer.Chatted connection as per documentation and other posts on the DevForum, but it doesn’t seem to work.

Here’s the code I attempted to use:

local player = game.Players.LocalPlayer

player.Chatted:Connect(function(msg)
	print(msg)
end)
1 Like

This is probably a bug that only occurs for the new chat system when the script is running on the client. Here’s my attempt at creating a temporary solution:

--For LocalScripts
function Chatted(): RBXScriptSignal
	local TextChatService = game:GetService("TextChatService")
	local Player = game.Players.LocalPlayer 
	local event = Instance.new("BindableEvent")
	local function ChannelAdded(channel: Instance)
		if not channel:IsA("TextChannel") then return end
		channel.MessageReceived:Connect(function(message)
			local source = message.TextSource 
			if not source or source.Name ~= Player.Name then return end 
			local recipient, sender = channel.Name:match("^RBXWhisper:(-?%d+)_(-?%d+)")
			if recipient and sender and Player.UserId == tonumber(sender) then
				local recipientPlr = game.Players:GetPlayerByUserId(tonumber(recipient))
				event:Fire(message.Text, recipientPlr)
			else
				event:Fire(message.Text, nil)
			end
		end)
	end
	if TextChatService.ChatVersion.Name == "LegacyChatService" then
		Player.Chatted:Connect(function(...) event:Fire(...) end)
	else
		local Channels = TextChatService:WaitForChild("TextChannels")
		for _, channel in pairs(Channels:GetChildren()) do
			ChannelAdded(channel)
		end
		Channels.ChildAdded:Connect(ChannelAdded)
	end
	return event.Event
end

Chatted():Connect(function(message: string, recipient: Player?)
	print(message, recipient)
end)

To figure out the black magic the script does I suggest you take a look into the TextChannel and TextChatMessage instances and also try exploring instances under TextChatService during the game simulation, most specifically when whisper messages are being sent.

2 Likes

you can just use the same method on the server and just fire a remote event with the message as an argument

1 Like

That’s what I implemented temporarily but check out NyrionDev’s solution

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