Purple exclamation mark.svg Planning the future of Botwiki! - Help us bring Botwiki up to date, contribute to our strategy discussion, add bot scripts, and contribute manuals, guides, and tutorials! Almost anything related to bots, particularly those used to edit mediawiki, is welcome.

Red exclamation mark.svg UNABLE TO EDIT? - We've experienced attacks by spambots lately and now require you to confirm your e-mail before you can edit (go to your preferences, enter an e-mail address, and request a confirmation e-mail, then go to your e-mail and click on the confirmation link). We also require new accounts to make a few edits and wait a few minutes before before you can create a page; however, if this is a problem contact us in #botwiki and we can manually confirm your account. Sorry for the inconvenience.

Python:Monitoraggio bot.py

From Botwiki
Jump to: navigation, search

It works in couple with Python:Monitoraggio logic.py

#!/usr/bin/python
# -*- coding: utf-8  -*-
"""
Bot to add Monitoraggio templates (for itwiki)
 
The following parameters are supported:
 
&params;
 
-dry              If given, doesn't do any real changes, but only shows
                  what would have been changed.
 
-auto             If given, do not ask for confirmation when saving
 
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
# Adaptations for Monitoraggio: (C) 2012 Merlijn 'valhallasw' van Deen
#
# Distributed under the terms of the MIT license.
#
 
import wikipedia as pywikibot
import pagegenerators
from pywikibot import i18n
 
import monitoraggio_logic
 
# This is required for the text that is shown when you run this script
# with the parameter -help.
docuReplacements = {
    '&params;': pagegenerators.parameterHelp
}
 
class MonitoraggioBot:
    # 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, auto):
        """
        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
        self.auto = auto
 
    def run(self):
        for page in self.generator:
            self.treat(page)
 
    def treat(self, page):
        """
        Loads the given page, does some changes, and saves it.
        """
        if page.isTalkPage():
            page = page.toggleTalkPage()
 
        text = self.load(page)
        if text is None:
            return
 
        (summary, template) = monitoraggio_logic.parsePage(page)
 
        talkpage = page.toggleTalkPage()
        talktext = self.load(talkpage, force=True)
        newtalktext = template + u"\n\n" + talktext
 
        if not self.save(newtalktext, talkpage, summary, oldtext=talktext):
            pywikibot.output(u'Page %s not saved.' % page.title(asLink=True))
 
    def load(self, page, force=False):
        """
        Loads the given page, does some changes, and saves it.
        """
        try:
            # Load the page
            text = page.get()
        except pywikibot.NoPage:
            pywikibot.output(u"Page %s does not exist; skipping."
                             % page.title(asLink=True))
            if force:
                return u""
        except pywikibot.IsRedirectPage:
            pywikibot.output(u"Page %s is a redirect; skipping."
                             % page.title(asLink=True))
            if force:
                return u""
        else:
            return text
        return None
 
    def save(self, text, page, comment=None, minorEdit=True,
             botflag=True, oldtext=u""):
        # only save if something was changed
        if text != oldtext:
            # 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(oldtext, text)
            pywikibot.output(u'Comment: %s' %comment)
            if not self.dry:
                if not self.auto:
                    choice = pywikibot.inputChoice(
                        u'Do you want to accept these changes?',
                        ['Yes', 'No'], ['y', 'N'], 'N')
                else:
                    choice = 'y'
                if choice == 'y':
                    try:
                        # Save the page
                        page.put(text, comment=comment or self.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
    # This temporary array is used to read the page title if one single
    # page to work on is specified by the arguments.
    pageTitleParts = []
    # If dry is True, doesn't do any real changes, but only show
    # what would have been changed.
    dry = False
 
    # Do not ask if the diff is OK
    auto = False
 
    # Parse command line arguments
    for arg in pywikibot.handleArgs():
        if arg.startswith("-auto"):
            auto = True
        if arg.startswith("-dry"):
            dry = True
        else:
            # check if a standard argument like
            # -start:XYZ or -ref:Asdf was given.
            if not genFactory.handleArg(arg):
                pageTitleParts.append(arg)
 
    if pageTitleParts != []:
        # We will only work on a single page.
        pageTitle = ' '.join(pageTitleParts)
        page = pywikibot.Page(pywikibot.getSite(), pageTitle)
        gen = iter([page])
 
    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 = MonitoraggioBot(gen, dry, auto)
        bot.run()
    else:
        pywikibot.showHelp()
 
if __name__ == "__main__":
    try:
        main()
    finally:
        pywikibot.stopme()
Personal tools
Share