Xqt has uploaded a new change for review.

  https://gerrit.wikimedia.org/r/266052

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

[IMPR] basic.py is a samply 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 doen'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, 78 insertions(+), 43 deletions(-)


  git pull ssh://gerrit.wikimedia.org:29418/pywikibot/core 
refs/changes/52/266052/1

diff --git a/scripts/basic.py b/scripts/basic.py
index f481eb0..0b44275 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.
 #
@@ -38,65 +48,79 @@
 }
 
 
-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."""
 
     # 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)
+    # script (i.e. basic.py in this case). Use summary_key to set the edit
+    # summary message.
+    summary_key = 'basic-changing'
 
-    def __init__(self, generator, dry=False, **kwargs):
+    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
+        # -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': None,  # add this text. Otherwise use 'Test' as default
+            'top': False,  # append text on top of the page
+        })
         super(BasicBot, self).__init__(site=True, **kwargs)
         self.generator = generator
 
-        # Set the edit summary message
-        self.summary = i18n.twtranslate(self.site, 'basic-changing')
-
-    def treat(self, page):
-        """Load the given page, does some changes, and saves it."""
-        text = self.load(page)
-        if not text:
-            return
+    def treat_page(self):
+        """Load the given page, do some changes, and save it."""
+        text = self.currentpage.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
+        text_option = 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))
+        # Use your own text or use the default 'Test'
+        text_to_add = text_option if text_option is not None else 'Test'
+
+        if self.getOption('replace'):
+            # replace the page text
+            text = text_to_add
+
+        elif self.getOptions('top'):
+            # put text on top
+            text = text_to_add + text
+
         else:
-            return text
-        return None
+            # put text on bottom
+            text += text_to_add
+
+        summary = self.getOption('summary')
+        if summary is not None:
+            # Set your own action summary
+            self.put_current(text, summary=summary)
+        else:
+            # AutomaticTWSummaryBot which sets the summary
+            self.put_current(text)
 
 
 def main(*args):
@@ -108,6 +132,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 +143,29 @@
 
     # Parse command line arguments
     for arg in local_args:
-        if arg == '-dry':
-            issue_deprecation_warning('-dry option', '-simulate', 1)
-            pywikibot.config.simulate = True
+        if genFactory.handleArg(arg):  # Catch the pagegenerators options
+            pass  # noting to do here
+        # Now pick up your own options
+        elif arg.startswith('-summary') or arg.startswith('-text'):
+            pos = arg.find(':')
+            if pos > 0:
+                options[arg[1:pos]] = arg[pos + 1:]
+            else:
+                options[arg[1:] = pywikibot.input(
+                    'Please enter a value for ' + arg)
+        # 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[arg[1:]] = 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: newchange
Gerrit-Change-Id: I2ba391ac22f1083b346dfb16aeeaeed0aa7a8e45
Gerrit-PatchSet: 1
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Owner: Xqt <i...@gno.de>

_______________________________________________
MediaWiki-commits mailing list
MediaWiki-commits@lists.wikimedia.org
https://lists.wikimedia.org/mailman/listinfo/mediawiki-commits

Reply via email to