Jump to content

User:Opencooper/collapseBots.js

From Wikipedia, the free encyclopedia

This is an old revision of this page, as edited by Opencooper (talk | contribs) at 01:52, 20 April 2020 (tweak). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
function setup() {
    // If we're not reading a talk page, do nothing
    if (!(mw.config.get('wgAction') === 'view'
          && mw.config.get('wgIsArticle')
          && !location.search.split('oldid=')[1] // Old revision
          && mw.config.get('wgNamespaceNumber') % 2 == 1)) { // talk namespaces have odd numbers
        return;
    }
    
    $("#bodyContent h2").each(tryCollapse);
}

function tryCollapse() {
	var talkNodes = $(this).nextUntil("h2");
	
	var lastSignature = $(talkNodes).find("a[href^='/wiki/User:']").last();
	if (lastSignature.length) { 
		console.log("User:Opencooper/collapseBots.js: " + lastSignature.text());
		checkBotStatus($(this), lastSignature.text());
	}
}

function checkBotStatus(header, username) {
    // API docs: https://www.mediawiki.org/wiki/API:Users
    $.ajax({
        url: "https://en.wikipedia.org/w/api.php",
        data: {
            action: "query",
            list: "users",
            format: "json",
            ususers: username,
            usprop: "groups"
        },
        success: function(response) {
        	var user = response.query.users[0];
        	
        	if (user.groups && user.groups.includes("bot")) {
        		console.log("User:Opencooper/collapseBots.js: " + username + " is a bot.");
        		collapseSection($(header));
        	}
        }
    });
}

function collapseSection(header) {
	var siblings = $(header).nextUntil("h2");
	$(siblings).wrapAll("<div class='mw-collapsible-content'></div>");
	
	siblings = $(header).nextUntil("h2"); // recompute b/c of collapsible
	var section = $().add(header).add(siblings);
	$(section).wrapAll("<div class='mw-collapsible'></div>"); // mw-collapsed
}

setup();