Jump to content

User:Ieditrandomarticles/bot.js

From Simple English Wikipedia, the free encyclopedia

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)
  • Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5.
mw.loader.using(['mediawiki.util', 'mediawiki.api'], function () {
    $(async function () {
        const api = new mw.Api();

        function transformHeadings(wikitext) {
            let changed = false;
            const newText = wikitext.replace(/^(={2,})\s*External links\s*\1\s*$/gim, (_, equals) => {
                changed = true;
                return `${equals} Other websites ${equals}`;
            }).replace(/^(={2,})\s*See also\s*\1\s*$/gim, (_, equals) => {
                changed = true;
                return `${equals} Related pages ${equals}`;
            });
            return [changed, newText];
        }

        const title = mw.config.get('wgPageName');
        const ns = mw.config.get('wgNamespaceNumber');

        if (ns !== 0) {
            console.log("[WikiWare/HeaderMini] Not an article page.");
            return;
        }

        try {
            const data = await api.get({
                action: 'query',
                prop: 'revisions',
                titles: title,
                rvslots: 'main',
                rvprop: 'content',
                formatversion: 2
            });

            const content = data.query.pages[0].revisions[0].slots.main.content;
            const [changed, newText] = transformHeadings(content);

            if (!changed) {
                console.log(`[WikiWare/HeaderMini] Nothing to fix in [[${title}]], heading to another...`);
                location.href = '/wiki/Special:Random';
                return;
            }

            const token = await api.get({
                action: 'query',
                meta: 'tokens'
            });

            await api.postWithToken('csrf', {
                action: 'edit',
                title: title,
                text: newText,
                summary: 'Replaced section titles with simpler forms per [[WP:MOS]]',
                format: 'json'
            });

            console.log(`[WikiWare/HeaderMini] Fixed [[${title}]]. Heading to another...`);
            alert("[WikiWare/HeaderMini] Fixed current page.")
            setTimeout(() => {
                location.href = '/wiki/Special:Random';
            }, 1000);
        } catch (e) {
            console.error("[WikiWare/HeaderMini] Error during edit:", e);
            alert("[WikiWare/HeaderMini] Something broke, check console.");
        }
    });
});