Jump to content

User:Ieditrandomarticles/bot.js

From Simple English Wikipedia, the free encyclopedia
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.

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 simplifyLinks(wikitext) {
            let changed = false;
            const newText = wikitext.replace(/\[\[([^\[\]\|]+)\|\1\]\]/g, (_, link) => {
                changed = true;
                return `[[${link}]]`;
            });
            return [changed, newText];
        }

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

        if (ns !== 0) {
            console.log("[WikiWare/LinkMini] 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] = simplifyLinks(content);

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

            await api.postWithToken('csrf', {
                action: 'edit',
                title: title,
                text: newText,
                summary: 'Fixed using [[Wikipedia:WikiProject Check Wikipedia]] (Link equal to linktext)',
                format: 'json'
            });

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