MediaWiki:Gadget-Botify.js

From Zelda Wiki, the Zelda encyclopedia
Revision as of 01:46, 29 June 2017 by KokoroSenshi (talk | contribs) (Rewrote; ajax calls have to use done/fail/always; used more mw.Api methods; untested)
Jump to navigation Jump to search

Note: After publishing, you may have to bypass your browser's cache to see the changes.

  • Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
  • Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
  • Internet Explorer / Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5
  • Opera: Press Ctrl-F5.
// --------------------------------------------------------
// Will Bot the user just before the Replace Text starts
// Notes: https://doc.wikimedia.org/mediawiki-core/master/js/#!/api/mw.Api
// --------------------------------------------------------

/* Either Bots or Unbots the current user */
function botify( addOrRemove, expiry, callback ) {
	
	var apiOptions = {
		action: 'userrights',
		user: mw.config.get("wgUserName"),
	};
	apiOptions[addOrRemove] = 'bot';
	if (addOrRemove === 'add') apiOptions.expiry = '1 minute' ; //TODO:Not working: It doesn't expire...
	
	var api = new mw.Api();
	api.postWithToken('userrights', apiOptions).done(function(data){
		console.log(data);
		console.log("User right changed");
		
		//TODO://Temporary for testing, don't forget to move the response() out
		api.getUserInfo().done(function(data){
			console.log(data.groups);
			alert( (data.groups.indexOf("bot") > -1) ? "You are now a bot." : "You are now not a bot." );
			callback();
		});
		
	});
	
}

/* Adds an Event Listener for the Replace Text submit button */
function botOnReplaceText() { console.log("botOnReplaceText()");
	
	$('#choose_pages').on('submit', function(e){
		e.preventDefault();
		(new mw.Api()).getUserInfo().done(function(data){
			console.log(data.groups);
			if (data.groups.indexOf("bot") === -1) botify('add', '1 minute', function(){$('#choose_pages').off('submit').submit()});
		});
	});
}

//When document ready:
$(function(){
	
	botOnReplaceText();
	
	//Link in Tools in sidebar to unbot
	mediaWiki.util.addPortletLink("p-tb", "#", "Unbot", "ca-unbot", "Click to unbot");
	console.log("Unbot link added");
	//Event listener for that link
	$("#ca-unbot").on("click", function(e){
		e.preventDefault();
		botify('remove');
	}); console.log("Unbot click event added");
	
});