tmijs / tmi.js

💬 Javascript library for the Twitch Messaging Interface. (Twitch.tv)
https://tmijs.com
MIT License
1.54k stars 216 forks source link

Mod / Broadcaster only #449

Closed Jake-BM closed 3 years ago

Jake-BM commented 3 years ago

After scouring the docs, forums and videos and trying multiple variations of the code, I can't seem to get this to only fire when used by a mod or the broadcaster. Occasionally it will seemingly work, but then crash the entire app if a non-mod user types it.

client.connect().catch(console.error);
client.on('chat', (channel, tags, message, self) => {

if(self) return;

    if(message.includes('!challenge')) {
        fs.writeFile('./JW_Challenge.txt', `  ${message.slice(10)}   `, 'utf8', function(error) {
          if(error) throw error;
          client.say(channel,'/me Challenge updated.');

I've got very limited knowledge of coding, so this could well be horribly written, as it's a mash-up of multiple different tutorials and what not.

Thanks in advance

AlcaDesign commented 3 years ago

This isn't an issue with tmi.js, please use the Discord #tmi channel or the discussions tab.

The broadcaster will have matching user-id and room-id and also have the broadcaster badge. Moderators will have the moderator badge.

client.on('message', (channel, tags, message, self) => {
    if(self) return;
    const badges = tags.badges || {};
    const isBroadcaster = badges.broadcaster;
    const isMod= badges.moderator;
    const isModUp = isMod || isBroadcaster;
    if(isModUp && message.toLowerCase().startsWith('!challenge')) {
        console.log('Moderator or broadcaster used the !challenge command');
    }
});
Zamiell commented 3 years ago

For reference, this is how you determine if the bot is a moderator:

const botUserState = client.userstate[channel];
const amMod = botUserState !== undefined && botUserState.mod === true;

The "userstate" object is automatically updated by the client when the "join" event happens or the "chat" event happens, so you don't have to micro-manage it.