Utilisateur:Goldorak/force cat change.py

Un article de la désencyclopédie.
Aller à la navigation Aller à la recherche
#!/usr/bin/python
# -*- coding: utf-8  -*-
"""
Ce script permet d'imposer le changement de catégorie dans les cas où category.py ne suffit pas :
lorsque la catégorie est donnée par un modèle, la simple modification du modèle ne suffit pas et
il faut alors éditer les pages pour qu'elles se positionnent dans leur nouvelle catégorie.
(équivalent de l'ancien script touch.py qui semble ne plus fonctionner)

lancement sur une page :
    python force_cat_change.py Pagename
lancement sur une catégorie :
    python force_cat_change.py -cat:"nom ancienne catégorie" 
exemple classique - archivage des votes statués sur le forum Big Brother : 
    python force_cat_change.py -cat:"Effacement non statué" 
"""
import wikipedia
import pagegenerators
import sys

class BasicBot:

    # Edit summary message that should be used.
    # NOTE: Put a good description here, and add translations, if possible!
    msg = {
        'fr': u'Réactualisation de la page pour forcer le changement de catégorie (modifié directement dans un modèle)', 
    }

    def __init__(self, generator, debug):
        """
        Constructor. Parameters:
            * generator - The page generator that determines on which pages
                          to work on.
            * debug     - If True, doesn't do any real changes, but only show
                          what would have been changed.
        """
        self.generator = generator
        self.debug = debug

    def run(self):
        # Set the edit summary message
        wikipedia.setAction(wikipedia.translate(wikipedia.getSite(), self.msg))
        for page in self.generator:
            self.treat(page)

    def treat(self, page):
        try:
            text = page.get()
        except wikipedia.NoPage:
            wikipedia.output(u"Page %s does not exist; skipping." % page.aslink())
            return
        except wikipedia.IsRedirectPage:
            wikipedia.output(u"Page %s is a redirect; skipping." % page.aslink())
            return
        except wikipedia.LockedPage:
            wikipedia.output(u"Page %s is locked; skipping." % page.aslink())
            return

        # Highlight the title in purple.
        colors = [None] * 6 + [13] * len(page.title()) + [None] * 4
        wikipedia.output(u"\n\n>>> %s <<<" % page.title(), colors = colors)
        if not self.debug:
            try:
                page.put(text)
            except wikipedia.EditConflict:
                wikipedia.output(u'Skipping %s because of edit conflict' % (page.title()))
            except wikipedia.SpamfilterError, e:
                wikipedia.output(u'Cannot change %s because of blacklist entry %s' % (page.title(), e.url))


def main():
    # This factory is responsible for processing command line arguments
    # that are also used by other scripts and that determine on which pages
    # to work on.
    genFactory = pagegenerators.GeneratorFactory()
    # The generator gives the pages that should be worked upon.
    gen = None
    # This temporary array is used to read the page title if one single
    # page to work on is specified by the arguments.
    pageTitleParts = []
    # If debug is True, doesn't do any real changes, but only show
    # what would have been changed.
    debug = False

    # Parse command line arguments
    for arg in wikipedia.handleArgs():
        if arg.startswith("-debug"):
            debug = True
        else:
            # check if a standard argument like
            # -start:XYZ or -ref:Asdf was given.
            generator = genFactory.handleArg(arg)
            if generator:
                gen = generator
            else:
                pageTitleParts.append(arg)

    if pageTitleParts != []:
        # We will only work on a single page.
        pageTitle = ' '.join(pageTitleParts)
        page = wikipedia.Page(wikipedia.getSite(), pageTitle)
        gen = iter([page])

    if gen:
        # The preloading generator is responsible for downloading multiple
        # pages from the wiki simultaneously.
        gen = pagegenerators.PreloadingGenerator(gen)
        bot = BasicBot(gen, debug)
        bot.run()
    else:
        wikipedia.showHelp()

if __name__ == "__main__":
    try:
        main()
    finally:
        wikipedia.stopme()