function initialize(config) {
    _config = config.live_data.twitch;

    var options = {
        options: {
            debug: false
        },
        connection: {
            reconnect: true
        },
        channels: [_config.channel]
    };

    var client = new irc.client(options);

    client.on("connected", function (address, port) {
        ready();
    });

    client.on("chat", function (channel, user, message, self) {
        var chatMessage = {
            type: 'chat',
            author: user['display-name'],
            color: user['color'],
            message: message,
            emotes: user['emotes'],
            source: 'twitch',
            date: new Date().getTime()
        };

        _newMessages.push(chatMessage);
    });

    client.connect();
}
Example #2
0
function connect () {
  retrieveStore()
  console.log(username, password, channel)
 /* eslint-disable */
  client = new Tmi.client(options)
   /* eslint-enable */

  client.addListener('connectfail', () => {
    console.log('connectfail')
  })

  client.addListener('connected', () => {
    console.log('Connected!')
    eventBus.$emit('connected')
  })

  client.on('disconnected', (reason) => {
    console.log(reason)
    if (reason === 'Login unsuccessful' || reason === 'Invalid NICK.' || reason === 'Connection closed.') {
      eventBus.$emit('loginfail')
    }
  })

  client.connect()
  clientOn()
}
Example #3
0
  twitch.on('raid', async (channel, username, raider, viewers, userstate) => {
    if (!userstate) return;
    log.info(`${userstate.login} raided from ${userstate['msg-param-login']} with ${viewers} viewers`);
    const displayName = utils.displayName(await twitchAPI.getUser(userstate['msg-param-login']));
    // Save to the database
    const entry = new mongo.Hosts({
      data: {
        username: displayName || username,
        viewers,
        created_at: Date.now(),
      },
      isRaid: true,
    });
    // Emit to clients
    io.emit('host', parser.host(entry));
    entry.save()
      .then(() => {
        utils.trimDB(mongo.Hosts);
      })
      .catch(log.error);

    // Auto raid mode
    twitch.say(config.twitch.channel, '!raidmode on (auto)');
    const followersAmount = status.channel.followersonly;
    const followersEnabled = followersAmount !== -1;
    if (followersEnabled) twitch.say(config.twitch.channel, '/followersoff');
    setTimeout(() => {
      twitch.say(config.twitch.channel, '!raidmode off (auto)');
      if (followersEnabled) twitch.say(config.twitch.channel, `/followers ${followersAmount}`);
    }, 1000 * 60 * 3);
  });
Example #4
0
// Used to send the auth code for updating the following buttons/emotes when needed.
function sendAuthThroughTwitchChat(auth) {
	// Settings for the temporary Twitch chat connection.
	var options = {
		options: {
			//debug: true  // might want to turn off when in production
		},
		connection: {
			secure: true
		},
		identity: {
			username: nodeCgExport.bundleConfig.user,
			password: accessToken
		}
	};

	var client = new tmi.client(options);
	client.connect();

	client.once('connected', function(address, port) {
		// Send the auth code to the specific Twitch channel.
		client.say('frankerfacezauthorizer', 'AUTH ' + auth);

		// Giving it 5 seconds until we disconnect just to make sure the message was sent.
		setTimeout(function() {client.disconnect();}, 5000);
	});
}
Example #5
0
 Object.keys(EVENTS).forEach(twitchEvent => {
   const mappedFn = this[EVENTS[twitchEvent]];
   this.client.on(twitchEvent, (...args) => mappedFn.bind(this)(...args));
   this.client.on(twitchEvent, (...args) => {
     this.bot.emitter.emit(`twitch-${twitchEvent}`, ...args);
   });
 });
Example #6
0
client.on('chat', function(channel, user, message, self) {
	if(message === "!twitter") {
		client.action("twitchtvchat", "twitter.com/matthewmariner")
		;
	}
	client.action("twitchtvchat", user['display-name'] + " you are a total noob.");
});
Example #7
0
    spawnWhisperClient () {
        if (this.whisperClient) {
            return
        }

        let whisperSettings = {
            options: {
                debug: Settings.bot.debug
            },
            identity: {
                username: Settings.bot.name,
                password: Settings.bot.oauth
            },
            logger: Log
        }

        if (this.whisperRetries <= 8) {
            this.whisperRetries++

            if (this.whisperRetries <= 5) {
                whisperSettings.connection = {
                    cluster: 'group'
                }
            }
        } else {
            this.whisperRetries = 0
        }

        if (!whisperSettings.connection) {
            whisperSettings.connection = {
                server: '199.9.253.119',
                port: '80'
            }
        }

        let client = new tmi.client(whisperSettings)

        client.connect()

        client.on('connected', (address, port) => {
            this.whisperRetries = 0
            Log.info('[Chat]', '[Whisper]', `Connected to Twitch Group chat (${address.yellow}:${port})`)
            this.whisperClient = client
        })

        client.on('whisper', (user, message, self) => {
            if (user.name !== Settings.bot.name.toLowerCase()) {
                this.handleMessage(null, user, message, self, true)
            }
        })

        client.on('disconnected', (reason) => {
            Log.error('[Chat]', '[Whisper]', 'Retrying, reason:', reason)
            client.disconnect()
            this.whisperClient = null
            this.spawnWhisperClient()
        })
    }
Example #8
0
client.on('chat', function(channel, user, message, self) {
  var usernameInMessage = message.slice(7,message.length);
  var banInMessage = message.slice(0,6);

  if(user.username === 'g000ey' && message.length >= 4 && banInMessage === "!unban" ){
    client.unban('g000ey', usernameInMessage);
    client.action('g000ey',"by the grace of his Gooeyness "+ usernameInMessage  + ' has been unbanned GG Kreygasm Kreygasm');
    }
});
Example #9
0
						queries.updateGameFen(player.id, newFen, function(err) {
							if (err){
								console.log(err);
								client.whisper(player.User_name, 'There was an error updating the game.');
								return;
							}

							client.whisper(player.User_name, 'I played the move ' + zuubyMove);
						});
Example #10
0
client.on('chat', function(channel, user, message, self) {
  var usernameInMessage = message.slice(5,message.length);
  var banInMessage = message.slice(0,4);

  if(user.username === 'g000ey' && message.length >= 5 && banInMessage === "!ban" ){
    client.ban('g000ey', usernameInMessage);
    client.action('g000ey', usernameInMessage  + ' has been banned GG KappaPride');
    }
});
Example #11
0
  send (message) {
    this.bot.log.debug(`Sending ${message.text} to ${message.channel}`);

    if (message.whisper) {
      return this.client.whisper(message.user.name, message.text);
    }

    this.client.say(message.channel, message.text);
  }
Example #12
0
	queries.getPlayer(user['username'], function(err, player) {
		if (err){
			console.error(err);
			return;
		}

		if (player) {
			client.action(channel, 'Player Exists.');
		} else {
			client.action(channel, 'Player does not exist.');
		}
	});
Example #13
0
//setup the bot
function setup(){
    // Init bot Instance
    bot = new irc.client(config.irc);
    
    // Connect the client to the server..
    bot.connect();
    
    // set color of the bot
    bot.color(config.botColor).catch(function(err) {
        console.log(colors.error(err));
    });
}
Example #14
0
      fs.writeFile("../../web/twitch/streamowner/index.html", newLog + '<br>',"utf-8", function(err) {
        if(err) {
          console.log('Error saving highlight: ' + err);
          mes += 'error writing to highlight log! BibleThump';
          bot.say(channel, mes);
        }

        else{
          console.log('Highlight logged successfully!');
          mes += 'highlight logged successfully! VoHiYo';
          bot.say(channel, mes);
        }
      });
Example #15
0
 .then(function(jsonBody){
     if (jsonBody.length == 0) {
         dentonBot.say(channel, 'No Results found for ' + capUser);
     } else {
         var masteryLevel = jsonBody[0].MasteryLevel;
         if (masteryLevel == 0) {
             dentonBot.say(channel, capUser + " has not mastered any gods.");
         }
         else {
             dentonBot.say(channel, capUser + " has mastered " + masteryLevel + " gods.");
         }
     }
 })
Example #16
0
 fs.readFile("rosieSets.json", function(err,data){
   if(err){
     console.log("Failed to read file to verify settings were updated, err is: " + err);
     retry = true;
     bot.say(channel, "Failed to verify new moderator settings were saved (reading the new settings file failed). Enter !retry to attempt to verify moderator save again. " + oldMod + " has lost mod powers until I am shut down (or permanently if the file saved or if !retry is successful)");
   }
   else{
     var jData = JSON.parse(data);
     console.log(JSON.stringify(jData.moderators));
     console.log(JSON.stringify(settings.moderators));
     if(JSON.stringify(jData.moderators) == JSON.stringify(settings.moderators)) bot.say(channel, mes);
   }
 });
Example #17
0
 .then(function(jsonBody){
     if (jsonBody.length == 0) {
         dentonBot.say(channel, 'No Results found for ' + capUser);
     } else {
         var conquestPlayed = 0, conquestWins = 0;
         for (var i = 0; i < jsonBody.length; i++){
             var conquestPlayed = conquestPlayed + jsonBody[i].Wins + jsonBody[i].Losses;
             var conquestWins = conquestWins + jsonBody[i].Wins;
         }
         var winrate = Math.round(conquestWins / conquestPlayed * 100);
         dentonBot.say(channel, capUser + " has played " + conquestPlayed + " Conquest games with a win rate of " +
           winrate + "%" );
     }
 })
Example #18
0
 .then(function(jsonBody){
     if (jsonBody.length == 0) {
         dentonBot.say(channel, 'No Results found for ' + msgArray[1]);
     } else {
         var clashPlayed = 0, clashWins = 0;
         for (var i = 0; i < jsonBody.length; i++) {
             var clashPlayed = clashPlayed + jsonBody[i].Wins + jsonBody[i].Losses;
             var clashWins = clashWins + jsonBody[i].Wins;
         }
         var winrate = Math.round(clashWins / clashPlayed * 100);
         dentonBot.say(channel, msgArray[1] + " has played " + clashPlayed + " Clash games with a win rate of " +
           winrate + "%");
     }
 })
Example #19
0
client.on("chat", function (channel, user, message, self) {
    if(message === "!help") {
      client.say("pr0pagandapandah", "Here is a list of commands: !twitter, !facebook, !sponsors");
    }
    if(message === "!twitter") {
      client.say("pr0pagandapandah", settings.twitter);
    }
    if(message === "!facebook") {
      client.say("pr0pagandapandah", settings.facebook);
    }
    if(message === "!sponsors") {
      client.say("pr0pagandapandah", "There are no sponsors BibleThump");
    }
});
Example #20
0
client.on("chat", function (channel, user, message, self) {
    if (user["user-type"] === "mod") {
        //command for new poll/old
        if (message.toLowerCase() === "!lb poll") {
            if (pollID === oldPoll) {
                strawP.createPoll(spPostOpt, function (res) {
                    pollID = res.id;
                    client.action(userChannel, "The poll for lights is located here: " + baseURL + pollID);
                    return pollID
                });
            }
            if(pollID != oldPoll) {
                strawP.getPoll(spPostOpt.url + '/' + pollID, function (err, res) {
                    console.log(res);
                    colors = res.choices.options;
                    votes = res.choices.votes;

                    maxVote = _.max(votes);
                    idxMaxVote = _.indexOf(votes, maxVote);
                    votedColor = colors[idxMaxVote];

                    localHue.selectedColor(votedColor);
                    oldPoll = res.choices.id;
                    client.action(userChannel, "The color with the most votes is " + votedColor + ", please enjoy the new color!");
                    return oldPoll
                });
            }
        }

        //override for color --- does this still work
        if (message.startsWith("!lb color")) {
            usersColor = S(message.toLowerCase()).strip('!lb color ').s;
            client.action(options.channels[0], user['display-name'] + ", the color that was selected is " + usersColor);
            console.log(user['display-name'] + ", the color that was selected was " + usersColor);
            localHue.selectedColor(usersColor);
        };
    }
    //command for current poll
    if(message === "!lb current"){
        if(pollID === oldPoll){
            client.action(twitch_options.channels[0],  "We are currently in between polls. Please wait for the next one to be published.");
        }
        client.action(userChannel,  "This is the current poll ->" + baseURL + pollID);
    }
    if(message === "!lights"){
        client.action(userChannel, user['display-name'] + ", we can't all be god and control the lights. So please leave that up to me!")
    }
});
Example #21
0
 disconnect(msg) {
   if(this._error) {
     global.logger.error(`${this._pluginName}|${this._id}: Cannot disconnect. Check log for errors.`);
     return;
   }
   this._client.disconnect(msg || 'Goodbye.');
 }
Example #22
0
    needle.get('http://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user=_GAMERTAG_&api_key=a96aa71dd3405190934ff7a35ce37256&format=json', function(err,resp){

      if(err){
        bot.whisper(user.username, "Error getting current song BibleThump");
      }

      else{
      lastJSON = resp.body;
      nowPlaying = lastJSON.recenttracks.track[0]["@attr"].nowplaying;
      curTrack = lastJSON.recenttracks.track[0]["name"];
      curArtist = lastJSON.recenttracks.track[0].artist["#text"];

      if(nowPlaying) bot.whisper(user.username, "Current Song: " +curTrack+" by " + curArtist);
      else bot.whisper(user.username, "No song currently reported as playing");
    }
    })
Example #23
0
 fs.readFile("rosieSets.json", function(err,data){
   if(err){
     console.log("Failed to read file to verify settings were updated, err is: " + err);
     retry = true;
     bot.say(channel, "Failed to verify new moderator settings were saved (reading the new settings file failed). Enter !retry to attempt to verify moderator save again.");
   }
   else{
     var jData = JSON.parse(data);
     console.log(JSON.stringify(jData.moderators));
     console.log(JSON.stringify(settings.moderators));
     if(JSON.stringify(jData.moderators) == JSON.stringify(settings.moderators)){
       bot.say(channel, "Retry successful! Settings file reports current moderators should be: " + jData.moderators);
       retry = false;
     }
   }
 });
Example #24
0
      fs.readFile("../../web/twitch/streamowner/index.html", "utf-8",function(err, data){
        if(err){
        console.log('Error reading highlight log: ' + err);
        mes = 'error reading the existing highlight log! BibleThump';
        bot.say(channel, mes);
        readSuccess = false;
      }
      oldLog = data;
      console.log("ReadFile oldLog = " + oldLog);
      console.log("ReadFile data = " + data);

      var newLog = oldLog + highlightLog;

      if(readSuccess){
      fs.writeFile("../../web/twitch/streamowner/index.html", newLog + '<br>',"utf-8", function(err) {
        if(err) {
          console.log('Error saving highlight: ' + err);
          mes += 'error writing to highlight log! BibleThump';
          bot.say(channel, mes);
        }

        else{
          console.log('Highlight logged successfully!');
          mes += 'highlight logged successfully! VoHiYo';
          bot.say(channel, mes);
        }
      });
    }

    });
Example #25
0
				fs.readFile('bundles/stream-info-boxes/view/song.txt', {encoding:'utf8'}, function(err, data) {
					if (!err && data != '') {
						client.say(channel, 'CURRENT SONG: ' + data);
						
						inCommandCooldown = true;
						setTimeout(function() {inCommandCooldown = false;}, 15000);
					}
				});
Example #26
0
   fs.writeFile("rosieSets.json.bak", JSON.stringify(settings),"utf-8", function(err) {
   if(err) {
     console.log('Error saving settings backup: ' + err);
     bot.say(channel, "Error saving backup of current mod list BibleThump . Resubmit !removemod command.");
     backedUp = false;
     return;
   }
 });
Example #27
0
      needle.get('https://api.twitch.tv/kraken/channels/_STREAMOWNER_?channel[status]='+myTitle+'&oauth_token=xowhhbpw8hhlqipxw2ti9sji9eyscv&_method=put', function(err,resp){

        var respBody = resp.body;
        var newStatus = respBody.status;

        bot.say(channel, 'Stream title updated to: ' + newStatus);

      });
Example #28
0
client.on('chat', function(channel, user, message, self) {
  if(message === '!mods') {
    client.mods('g000ey').then(function(data) {
      console.log(data);
      client.action('g000ey', "Mods are " + data)
    });
  }
});
Example #29
0
      needle.get('https://api.twitch.tv/kraken/channels/_STREAMOWNER_?channel[game]='+myGame+'&oauth_token=xowhhbpw8hhlqipxw2ti9sji9eyscv&_method=put', function(err,resp){

        var respBody = resp.body;
        var newGame = respBody.game;

        bot.say(channel, "Stream game updated to: " + newGame);

      });
Example #30
0
      needle.get('https://api.twitch.tv/kraken/channels/_STREAMOWNER_', function(err, resp){

        var twitchJSON = resp.body;
        var game = twitchJSON.game;

        bot.say(channel, "Current Game: " + game);

      });