#!/usr/bin/python3
import re
import pywikibot
from pywikibot import pagegenerators
from pywikibot.backports import Tuple
from pywikibot.bot import (
ExistingPageBot,
NoRedirectPageBot,
SingleSiteBot,
)
class AddBaseTwoBot(
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
):
r_base = '|Rb=2\n'
regex = re.compile(r'Riesel prime (\d+)')
replacePattern = r'Riesel prime 2 \1'
def treat_page(self) -> None:
"""Load the given page, do some changes, and save it."""
page = self.current_page
# Move page
newPageTitle = self.regex.sub(self.replacePattern,
page.title())
newPage = page.move(
newPageTitle, reason='Add base=2 to title',
movetalk=True, noredirect=True)
# Add base to page text
text = newPage.text
# This is the easiest way to place the |Rb=2 line between |Rk and |RCount.
# TODO: Create class representing Riesel k page.
start, r_count, finish = text.partition('|RCount')
newPage.text = ''.join((start, self.r_base, r_count, finish))
newPage.save(summary='Add Rb=2')
def main(*args: Tuple[str, ...]) -> None:
"""
Process command line arguments and invoke bot.
If args is an empty list, sys.argv is used.
:param args: command line arguments
"""
options = {}
# Process global arguments to determine desired site
local_args = pywikibot.handle_args(args)
# 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.
gen_factory = pagegenerators.GeneratorFactory()
# Process pagegenerators arguments
local_args = gen_factory.handle_args(local_args)
# Parse your own command line arguments
for arg in local_args:
arg, sep, value = arg.partition(':')
option = arg[1:]
# take the remaining options as booleans.
# You will get a hint if they aren't pre-defined in your bot class
options[option] = True
# The preloading option is responsible for downloading multiple
# pages from the wiki simultaneously.
gen = gen_factory.getCombinedGenerator(preload=True)
if gen:
# pass generator and private options to the bot
bot = AddBaseTwoBot(generator=gen, **options)
bot.run() # guess what it does
else:
pywikibot.bot.suggest_help(missing_generator=True)
if __name__ == '__main__':
main()