Usuario:Shyde/category move.py

#!/usr/bin/python
# -*- coding: utf-8  -*-
"""
This is not a complete bot; rather, it is a template from which simple
bots can be made. You can rename it to mybot.py, then edit it in
whatever way you want.

The following parameters are supported:

&params;

-dry              If given, doesn't do any real changes, but only shows
                  what would have been changed.

All other parameters will be regarded as part of the title of a single page,
and the bot will only work on that single page.
"""
#
# (C) Pywikipedia bot team, 2006-2011
#
# Distributed under the terms of the MIT license.
#
__version__ = '$Id: basic.py 9359 2011-07-10 12:22:39Z xqt $'
#

import wikipedia as pywikibot
import pagegenerators
from pywikibot import i18n

# This is required for the text that is shown when you run this script
# with the parameter -help.
docuReplacements = {
    '&params;': pagegenerators.parameterHelp
}

class BasicBot:
    # Edit summary message that should be used is placed on /i18n subdirectory.
    # The file containing these messages should have the same name as the caller
    # script (i.e. basic.py in this case)

    def __init__(self, generator, dry):
        """
        Constructor. Parameters:
            @param generator: The page generator that determines on which pages
                              to work.
            @type generator: generator.
            @param dry: If True, doesn't do any real changes, but only shows
                        what would have been changed.
            @type dry: boolean.
        """
        self.generator = generator
        self.dry = dry
        # Set the edit summary message
        self.summary = i18n.twtranslate(pywikibot.getSite(), 'basic-changing')

    def run(self):
        for page in self.generator:
            self.treat(page)

    def treat(self, oldPage):
        """
        Loads the given page, does some changes, and saves it.
        """
        
        # Get newPage.
        newPage = pywikibot.Page(pywikibot.getSite(), oldPage.title().replace(u'Páxinas', u'Entradas'))
        
        if self.create(newPage, oldPage.get().replace(u'Páxinas', u'Entradas')):
	  if self.delete(oldPage, newPage):
	    pywikibot.output(u'%s%s' % (oldPage.title(), newPage.title()))
	  else:
	    pywikibot.output(u'+ %s (non se puido marcar para borrar a vella)' % newPage.title())
	else:
          pywikibot.output(u'Non se puido crear a categoría «%s».' % newPage.title())

    def create(self, page, text):
      
        if not self.dry:            
          try:
              # Save the page
              try:
                currentText = page.get()
              except pywikibot.NoPage:
                page.put(text, u'Páxinas → Entradas (creada).',
                        minorEdit=True, botflag=True)
              else:
                if page.get() != text:
                  page.put(text, u'Páxinas → Entradas (creada).',
                        minorEdit=True, botflag=True)
                else:
                  return False
          except pywikibot.LockedPage:
              pywikibot.output(u"Page %s is locked; skipping."
                                % page.title(asLink=True))
          except pywikibot.EditConflict:
              pywikibot.output(
                  u'Skipping %s because of edit conflict'
                  % (page.title()))
          except pywikibot.SpamfilterError, error:
              pywikibot.output(
u'Cannot change %s because of spam blacklist entry %s'
                  % (page.title(), error.url))
          else:
              return True
        return False

    def delete(self, oldPage, newPage):
      
        if not self.dry:
            try:
                # Save the page
                text = u'{{lixo|[[:%s]] a substituirá}}' % newPage.title()
                oldPage.put(text, u'Páxinas → Entradas (marcada para borrar).', minorEdit=True, botflag=True)
            except pywikibot.LockedPage:
                pywikibot.output(u"Page %s is locked; skipping."
                                  % page.title(asLink=True))
            except pywikibot.EditConflict:
                pywikibot.output(
                    u'Skipping %s because of edit conflict'
                    % (page.title()))
            except pywikibot.SpamfilterError, error:
                pywikibot.output(
u'Cannot change %s because of spam blacklist entry %s'
                    % (page.title(), error.url))
            else:
                return True
        return False

    # Not used, just left as reference.
    def save(self, text, page, comment, minorEdit=True, botflag=True):
        # only save if something was changed
        if text != page.get():
            # Show the title of the page we're working on.
            # Highlight the title in purple.
            pywikibot.output(u"\n\n>>> \03{lightpurple}%s\03{default} <<<"
                             % page.title())
            # show what was changed
            pywikibot.showDiff(page.get(), text)
            pywikibot.output(u'Comment: %s' %comment)
            if not self.dry:
                choice = pywikibot.inputChoice(
                    u'Do you want to accept these changes?',
                    ['Yes', 'No'], ['y', 'N'], 'N')
                if choice == 'y':
                    try:
                        # Save the page
                        page.put(text, comment=comment,
                                 minorEdit=minorEdit, botflag=botflag)
                    except pywikibot.LockedPage:
                        pywikibot.output(u"Page %s is locked; skipping."
                                         % page.title(asLink=True))
                    except pywikibot.EditConflict:
                        pywikibot.output(
                            u'Skipping %s because of edit conflict'
                            % (page.title()))
                    except pywikibot.SpamfilterError, error:
                        pywikibot.output(
u'Cannot change %s because of spam blacklist entry %s'
                            % (page.title(), error.url))
                    else:
                        return True
        return False

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
    # If dry is True, doesn't do any real changes, but only show
    # what would have been changed.
    dry = False

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

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

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