Error with TextChatService

Basically I want to remove a script from StarterPlayerScripts if a user is below a specific rank so he wouldn’t be able to use a command for moderators only. After using script:Destroy() player can’t chat and the error “Error occurred while calling TextChatService.OnIncomingMessage: Script that implemented this callback has been destroyed while calling async callback” occurs.

Local Script inside the StarterPlayerScripts:

local TextChatService = game:GetService("TextChatService")
local Players = game:GetService("Players")

local countdown = 0
local enabled = false
local mod = false

function Timer()
	--Not needed for answer
end

function SendMessage(text)
	-- GUI message, not needed for answer
end

TextChatService.OnIncomingMessage = function(message: TextChatMessage)
	if message.TextSource and mod == true then
		if message.Text == ":dutystart" and message.Status == Enum.TextChatMessageStatus.Success then
			if enabled == false then
				enabled = true
				SendMessage("Timer activated.")
				Timer()
			else
				SendMessage("Already enabled.")
			end
		elseif message.Text == ":dutyend" and message.Status == Enum.TextChatMessageStatus.Success then
			if enabled == true then
				enabled = false
				Timer()
				SendMessage(countdown .. " Minutes.")
			else
				SendMessage("Not enabled yet.")
			end
		end
	end
end

if Players.LocalPlayer:GetRankInGroup(13955368) >= 243 then
	mod = true
	print("Mod")
else
	script:Destroy()
	return
end

I am not sure why this occurs and how to fix it, will be thankful for any help!

I have found a solution. All that was needed was to check if player is a stated rank before calling TextChatService. So basically how it looks:

local Players = game:GetService("Players")

if Players.LocalPlayer:GetRankInGroup(13955368) < 243 then
	script:Destroy()
end

local TextChatService = game:GetService("TextChatService")

--The rest of the script.

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