Checking locally whatever you already are in the channel or not is probably the cleanest way to go about it.
// untested..
client.on("chat", function (channel, userstate, message, self) {
// Don't listen to my own messages..
if (self) return;
// ... logics
const target = '#' + userstate.username;
if(!client.getChannels().includes(target)){
// target is not in the channel list
client.join(target)
}
});
You could also consider throttling / rate limiting the function if someone is abusing it (google it).