Jump to content

User:DreamRimmer bot III/Task9.py

From 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.
import pywikibot
import mwparserfromhell

def run(wikicode, inside_template=False):
    for node in wikicode.nodes:
        if isinstance(node, mwparserfromhell.nodes.Template):
            for param in node.params:
                run(param.value, inside_template=True)
        elif isinstance(node, mwparserfromhell.nodes.Wikilink):
            if str(node.title).startswith('Category:') and not inside_template:
                category_name = str(node.title)[9:].strip()
                words = category_name.split()
                if not any(word.lower() in {'draft', 'drafts', 'wikipedia'} for word in words):
                    node.title.insert(0, mwparserfromhell.nodes.Text(':'))
        elif isinstance(node, mwparserfromhell.nodes.Tag):
            if node.contents:
                run(node.contents, inside_template)

site = pywikibot.Site('en', 'wikipedia')
search_string = r'insource:/\[\[Category:/ incategory:"All content moved from mainspace to draftspace" -insource:/\{\{[Dd]raft categories/'
pages = site.search(search_string, namespaces=[118])

for page in pages:
    print(page)
    current_text = page.text
    code = mwparserfromhell.parse(current_text)
    run(code)
    new_text = str(code)
    
    if current_text != new_text:
        pywikibot.showDiff(current_text, new_text)
        page.text = new_text
        page.save(summary='Disable content categories per [[WP:DRAFTNOCAT]] (bot)', minor=True, bot=True)