Here naverokê

Bikarhêner:Balyozxane/skrîpt/py/kuCosmeticsRun.py

Ji Wîkîpediya, ensîklopediya azad.
#!/usr/bin/env python3
"""
python pwb.py updatewin -f:"kucosmrun.py" -s:"fix global VERBOSE"
The following parameters are supported:

-always           The bot won't ask for confirmation when putting a page.

-showdiff         The bot will show the differences in the console.

-async            Edits will be performed asynchronously.

Use global -simulate option for test purposes. No changes to live wiki
will be done.

"""
#
# (C) w:ku:Balyozxane
#
# Distributed under the terms of the MIT license.
#

import pywikibot
from pywikibot import pagegenerators
from pywikibot.bot import (
    AutomaticTWSummaryBot,
    ConfigParserBot,
    ExistingPageBot,
    SingleSiteBot,
)
from kucosmetics import CANCEL, CosmeticChangesToolkit

VERBOSE = False

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


class PaqijiBot(
    # Refer pywikobot.bot for generic bot classes
    SingleSiteBot,  # A bot only working on one site
    ConfigParserBot,  # A bot which reads options from scripts.ini setting file
    # CurrentPageBot,  # Sets 'current_page'. Process it in treat_page method.
    #                  # Not needed here because we have subclasses
    ExistingPageBot,  # CurrentPageBot which only treats existing pages
    AutomaticTWSummaryBot,  # Automatically defines summary; needs summary_key
):
    use_redirects = False  # treats non-redirects only
    summary_key = 'basic-changing'

    update_options = {
        'async': False,
        'showdiff': False,
        'ignore': CANCEL.MATCH,
    }

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        global VERBOSE
        VERBOSE = self.opt.get('showdiff', False)

        self.bot_name = "User:Balyozxane/skrîpt/py/kuCosmeticsCore.py"
        self.summaries = {}

    def do_kozmetik(self, old_text):

        cc_toolkit = CosmeticChangesToolkit(self.current_page,
                                            ignore=self.opt.ignore,
                                            show_diff=self.opt.showdiff)
        new_text, summaries = cc_toolkit.change(old_text)  # Capture summaries

        self.summaries.update(summaries)
        return new_text

    def treat_page(self) -> None:
        self.summaries = {}

        if self.current_page.namespace() not in [0, 14] and self.current_page.title() != "Bikarhêner:Balyozxane/ceribandin":
            if VERBOSE:
                print("Skipping Namespace not 0 or 14.")
            return

        text = self.current_page.text

        # kozmetik first
        new_text = self.do_kozmetik(text)

        # Save the page
        if ''.join(text.split()) != ''.join(new_text.split()):

            # Construct summary from captured summaries
            applies_summaries = ', '.join(self.summaries.values())

            summary = f'[[{self.bot_name}|Bot]]: Paqijiyên kozmetîk'
            # Append additional summary if needed
            if applies_summaries:
                summary += f' ({applies_summaries}.)'

            self.put_current(
                new_text,
                summary=summary,
                asynchronous=self.opt['async'],
                show_diff=self.opt['showdiff']
            )


def main(*args: 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, _, value = arg.partition(':')
        option = arg[1:]
        if option in ('-always', '-async', '-showdiff'):
            options[option[1:]] = True
        elif option == '-ignore':
            value = value.upper()
            try:
                options['ignore'] = getattr(CANCEL, value)
            except AttributeError:
                raise ValueError(f'Unknown ignore mode {value!r}!')
        # take the remaining options as booleans.
        # You will get a hint if they aren't pre-defined in your bot class
        else:
            options[option] = True
    # The preloading option is responsible for downloading multiple
    # pages from the wiki simultaneously.
    gen = gen_factory.getCombinedGenerator(preload=True)

    # check if further help is needed
    if not pywikibot.bot.suggest_help(missing_generator=not gen):
        # pass generator and private options to the bot
        bot = PaqijiBot(generator=gen, **options)
        bot.run()  # guess what it does


if __name__ == '__main__':
    main()