smourph
7/28/2017 - 1:42 PM

SlackObserver

SlackObserver

var speech = new SpeechSynthesisUtterance();
var voices = [];

function populateVoiceList() {
    voices = speechSynthesis.getVoices();
}

function onMutation(mutations) {
    mutations.forEach(function (mutation) {
        if (mutation.type === 'childList') {
            if (mutation.target.nodeType === 1 && mutation.target.tagName === 'DIV' && mutation.target.className === 'day_msgs') {
                var added = mutation.addedNodes;
                for (var i = 0; i < added.length; i++) {
                    var node = added[i];
                    if (node.nodeType !== 1) {
                        continue;
                    }
                    if (node.tagName === 'TS-MESSAGE' && node.className.indexOf('unprocessed') === -1) {
                        var authorNode = node.querySelector('.message_sender');
                        var author = authorNode.innerText || authorNode.textContent;
                        var authorId = authorNode.dataset.memberId;
                        if (authorId === 'USLACKBOT') {
                            var messageNode = node.querySelector('.message_body');
                            var message = messageNode.innerText || messageNode.textContent;
                            speech.text = message;
                            speechSynthesis.speak(speech);
                            var fullMessage = author + ' : ' + message;
                            console.log(fullMessage);
                        }
                    }
                }
            }
        }
    });
}

populateVoiceList();
speech.voice = voices[8];
if (speechSynthesis.onvoiceschanged !== undefined) {
    speechSynthesis.onvoiceschanged = populateVoiceList;
}

var observer = new MutationObserver(onMutation);
var msgsContainer = document.getElementById('msgs_div');
var config = {attributes: false, childList: true, characterData: false, subtree: true};
observer.observe(msgsContainer, config);