jenkins-bot has submitted this change and it was merged.

Change subject: [IMPR] basic.py is a sample to create bot scripts with 
pywikibot framework
......................................................................


[IMPR] basic.py is a sample to create bot scripts with pywikibot framework

- Give a hint to use global simulate option for testings
- Some samples for private options
- remove ugly -dry option which doesn't demonstrate anything anymore
- use several bot classes to demonstrate how to use them
- use CurrentPageBot class and treat_page method
- load method is obsolete with some bot subclasses
- additional comments

Change-Id: I2ba391ac22f1083b346dfb16aeeaeed0aa7a8e45
---
M scripts/basic.py
1 file changed, 114 insertions(+), 47 deletions(-)

Approvals:
  John Vandenberg: Looks good to me, approved
  jenkins-bot: Verified



diff --git a/scripts/basic.py b/scripts/basic.py
index f481eb0..f616f82 100755
--- a/scripts/basic.py
+++ b/scripts/basic.py
@@ -7,16 +7,26 @@
 bots can be made. You can rename it to mybot.py, then edit it in
 whatever way you want.
 
+Use global -simulate option for test purposes. No changes to live wiki
+will be done.
+
 The following parameters are supported:
 
 &params;
 
--dry              If given, doesn't do any real changes, but only shows
-                  what would have been changed.
+-always           If used, the bot won't ask if it should file the message
+                  onto user talk page.
 
+-text:            Use this text to be added; otherwise 'Test' is used
+
+-replace:         Dont add text but replace it
+
+-top              Place additional text on top of the page
+
+-summary:         Set the action summary message for the edit.
 """
 #
-# (C) Pywikibot team, 2006-2015
+# (C) Pywikibot team, 2006-2016
 #
 # Distributed under the terms of the MIT license.
 #
@@ -26,9 +36,10 @@
 #
 
 import pywikibot
-from pywikibot import i18n, pagegenerators
+from pywikibot import pagegenerators
 
-from pywikibot.bot import SingleSiteBot
+from pywikibot.bot import (
+    SingleSiteBot, ExistingPageBot, NoRedirectPageBot, AutomaticTWSummaryBot)
 from pywikibot.tools import issue_deprecation_warning
 
 # This is required for the text that is shown when you run this script
@@ -38,65 +49,108 @@
 }
 
 
-class BasicBot(SingleSiteBot):
+class BasicBot(
+    # Refer pywikobot.bot for generic bot classes
+    SingleSiteBot,  # A bot only working on one site
+    # CurrentPageBot,  # Sets 'current_page'. Process it in treat_page method.
+    #                  # Not needed here because we have subclasses
+    ExistingPageBot,  # CurrentPageBot which only treats existing pages
+    NoRedirectPageBot,  # CurrentPageBot which only treats non-redirects
+    AutomaticTWSummaryBot,  # Automatically defines summary; needs summary_key
+):
 
-    """An incomplete sample bot."""
+    """
+    An incomplete sample bot.
 
-    # 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)
+    @ivar summary_key: Edit summary message key. The 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). Use summary_key to set a default edit summary message.
+    @type summary_key: str
+    """
 
-    def __init__(self, generator, dry=False, **kwargs):
+    summary_key = 'basic-changing'
+
+    def __init__(self, generator, **kwargs):
         """
         Constructor.
 
         @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: bool
         """
-        if dry:
-            issue_deprecation_warning('dry argument', 
'pywikibot.config.simulate', 1)
-            pywikibot.config.simulate = True
+        # Add your own options to the bot and set their defaults
+        # -always option is predefined by BaseBot class
+        self.availableOptions.update({
+            'replace': False,  # delete old text and write the new text
+            'summary': None,  # your own bot summary
+            'text': 'Test',  # add this text from option. 'Test' is default
+            'top': False,  # append text on top of the page
+        })
+
+        # call constructor of the super class
         super(BasicBot, self).__init__(site=True, **kwargs)
+
+        # handle old -dry paramter
+        self._handle_dry_param(**kwargs)
+
+        # assign the generator to the bot
         self.generator = generator
 
-        # Set the edit summary message
-        self.summary = i18n.twtranslate(self.site, 'basic-changing')
+    def _handle_dry_param(self, **kwargs):
+        """
+        Read the dry parameter and set the simulate variable instead.
 
-    def treat(self, page):
-        """Load the given page, does some changes, and saves it."""
-        text = self.load(page)
-        if not text:
-            return
+        This is a private method. It prints a deprecation warning for old
+        -dry paramter and sets the global simulate variable and informs
+        the user about this setting.
+
+        The constuctor of the super class ignores it because it is not
+        part of self.availableOptions.
+
+        @note: You should ommit this method in your own application.
+
+        @keyword dry: deprecated option to prevent changes on live wiki.
+            Use -simulate instead.
+        @type dry: bool
+        """
+        if 'dry' in kwargs:
+            issue_deprecation_warning('dry argument',
+                                      'pywikibot.config.simulate', 1)
+            # use simulate variable instead
+            pywikibot.config.simulate = True
+            pywikibot.output('config.simulate was set to True')
+
+    def treat_page(self):
+        """Load the given page, do some changes, and save it."""
+        text = self.current_page.text
 
         ################################################################
         # NOTE: Here you can modify the text in whatever way you want. #
         ################################################################
 
         # If you find out that you do not want to edit this page, just return.
-        # Example: This puts the text 'Test' at the beginning of the page.
-        text = 'Test ' + text
+        # Example: This puts Text on a page.
 
-        if not self.userPut(page, page.text, text, summary=self.summary,
-                            ignore_save_related_errors=True):
-            pywikibot.output(u'Page %s not saved.' % page.title(asLink=True))
+        # Retrieve your private option
+        # Use your own text or use the default 'Test'
+        text_to_add = self.getOption('text')
 
-    def load(self, page):
-        """Load the text of the given page."""
-        try:
-            text = page.get()
-        except pywikibot.NoPage:
-            pywikibot.output(u"Page %s does not exist; skipping."
-                             % page.title(asLink=True))
-        except pywikibot.IsRedirectPage:
-            pywikibot.output(u"Page %s is a redirect; skipping."
-                             % page.title(asLink=True))
+        if self.getOption('replace'):
+            # replace the page text
+            text = text_to_add
+
+        elif self.getOption('top'):
+            # put text on top
+            text = text_to_add + text
+
         else:
-            return text
-        return None
+            # put text on bottom
+            text += text_to_add
+
+        # if summary option is None, it takes the default i18n summary from
+        # i18n subdirectory with summary_key as summary key.
+        self.put_current(text, summary=self.getOption('summary'))
 
 
 def main(*args):
@@ -108,6 +162,7 @@
     @param args: command line arguments
     @type args: list of unicode
     """
+    options = {}
     # Process global arguments to determine desired site
     local_args = pywikibot.handle_args(args)
 
@@ -118,19 +173,31 @@
 
     # Parse command line arguments
     for arg in local_args:
-        if arg == '-dry':
-            issue_deprecation_warning('-dry option', '-simulate', 1)
-            pywikibot.config.simulate = True
+
+        # Catch the pagegenerators options
+        if genFactory.handleArg(arg):
+            continue  # nothing to do here
+
+        # Now pick up your own options
+        arg, sep, value = arg.partition(':')
+        option = arg[1:]
+        if option in ('summary', 'text'):
+            if not value:
+                pywikibot.input('Please enter a value for ' + arg)
+            options[option] = value
+        # take the remaining options as booleans.
+        # You will get a hint if they aren't pre-definded in your bot class
         else:
-            genFactory.handleArg(arg)
+            options[option] = True
 
     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)
-        bot.run()
+        # pass generator and private options to the bot
+        bot = BasicBot(gen, **options)
+        bot.run()  # guess what it does
         return True
     else:
         pywikibot.bot.suggest_help(missing_generator=True)

-- 
To view, visit https://gerrit.wikimedia.org/r/266052
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings

Gerrit-MessageType: merged
Gerrit-Change-Id: I2ba391ac22f1083b346dfb16aeeaeed0aa7a8e45
Gerrit-PatchSet: 11
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Owner: Xqt <[email protected]>
Gerrit-Reviewer: Annafijol <[email protected]>
Gerrit-Reviewer: John Vandenberg <[email protected]>
Gerrit-Reviewer: Mpaa <[email protected]>
Gerrit-Reviewer: Ricordisamoa <[email protected]>
Gerrit-Reviewer: XZise <[email protected]>
Gerrit-Reviewer: Xqt <[email protected]>
Gerrit-Reviewer: jenkins-bot <>

_______________________________________________
MediaWiki-commits mailing list
[email protected]
https://lists.wikimedia.org/mailman/listinfo/mediawiki-commits

Reply via email to