User:Theleekycauldron/DYK stats notifier.js

From Wikipedia, the free encyclopedia
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.
//<nowiki>
importScript('User:Theleekycauldron/Query pages.js');
try {
	let api = new mw.Api();
} catch (SyntaxError) {}
async function notify(user,article,views,vph,monthyear){
	talkpage = await get_pages("User talk:"+user,"content",null,"older");
	talktext = talkpage[0].revisions[0].slots.main.content;
	sectionid = findsection(talktext,"DYK for "+article);
	if (sectionid == 0) return;
	sectiontext = getsection(talktext,"DYK for "+article);
	matches = sectiontext.match("\{\{DYK views","i");
	if (matches !== null) {return;}
	console.log("Notifying",user,"for",article);
	var params = {
		action: 'edit',
		title: 'User talk:'+user,
		section: sectionid,
		summary: "/* DYK for "+article+" */ your hook reached "+views+" views!",
		appendtext: '\n{{DYK views\|'+views+"\|"+vph+"\|"+monthyear+"\|"+article+"}} ~~~~",
		format: 'json'
	}
	api.postWithToken( 'csrf', params );
}
function findsection(pagetext,title){
	pagetext = pagetext.split("\n");
	var s = 0;
	for (line of pagetext){
		if (line.match(/^==/) !== null){
			s += 1;
		}
		if (line.includes(title)){
			break;
		}
	}
	return s
}

function getsection(pagetext,title){
	pagetext = pagetext.split("\n");
	var res = [];
	var found=false;
	for (line of pagetext){
		if (line.includes(title)){
			found=true;
		} else if (found && line.match(/^==(?!=)/) !== null){
			break;
		} else if (found){
			res.push(line);
		}
		
	}
	return res.join("");
}
//</nowiki>