Text Source Custom Script: Twitch chat controlled counter

This script will allow you to add a text counter that the chat can manipulate.

  1. Add a text file, right click it and make sure “Use Custom Script” is checked
  2. Click Edit Script

  1. Make sure the template is Blank Template, click the “Script” tab and then paste the script found below

image

  1. Now you can tweak the settings such as the channel the chat should connect to, a starting value and the commands used to increase or decrease the counter

image

The Code

/**
 * @name TWITCH_CHANNEL
 * @label Twitch Channel
 * @type text
 * @description The Twitch channel that will listen for the commands.
 */
var TWITCH_CHANNEL = "gazreyn";

/**
 * @name COUNTER_VALUE
 * @label Counter Value
 * @type int
 * @description Set a specific value for the counter
 */
var COUNTER_VALUE = 0;

/**
 * @name INCREMENT_CMD
 * @label Increment Command
 * @type text
 * @description This command will be used to +1 to the counter
 */
var INCREMENT_CMD = "add";

/**
 * @name DECREMENT_CMD
 * @label Decrement Command
 * @type text
 * @description This command will be used to -1 to the counter
 */
var DECREMENT_CMD = "remove";

/* DO NOT MODIFY ANYTHING BELOW */
var tmiScript = document.createElement('script');
tmiScript.src = 'https://unpkg.com/twitch-js@1.2.17/dist/twitch-js.min.js';
document.head.prepend(tmiScript);

const channels = [`#${TWITCH_CHANNEL}`];
const clientOptions = {
  channels: channels
};

setTimeout(() => {
  const client = new tmi.client(clientOptions); 
  
  client.connect();
  client.addListener('message', handleChat);
  
  function handleChat(channel, user, message, self) {
    if(message == '!' + INCREMENT_CMD) { 
      updateCounter(++COUNTER_VALUE);
    }
    if(message == '!' + DECREMENT_CMD) {
      updateCounter(--COUNTER_VALUE);
    }
  }
}, 1000);

function updateCounter(value) {
  SetText(value.toString(), 'Count: ' + value.toString())
}

updateCounter(COUNTER_VALUE);