Here naverokê

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

Ji Wîkîpediya, ensîklopediya azad.
#!/usr/bin/env python3
"""
python pwb.py updatewin -f:"addhighuse.py" -s:"fix"

Şablona bikaranîna bilind lê zêde dike an radike, eger belgekirin tinebe li jorê şablonê bi noinclude lê zêde dike.

"""
import re
import mytools
import pywikibot
from pywikibot import pagegenerators
from pywikibot.bot import (
    ConfigParserBot,
    ExistingPageBot,
    SingleSiteBot,
)
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


def get_data_pages(site):
    main_page_title = 'Modul:Transclusion count/data/'

    # Retrieve subpages
    subpages = pagegenerators.PrefixingPageGenerator(main_page_title, namespace=828, site=site, content=True)

    template_list = []

    for subpage in subpages:
        if subpage.title().endswith('/belge'):
            continue
        else:
            templates = get_data(subpage.text)
            if templates:
                template_list.extend(templates)
    return template_list


def get_data(text):
    # Use regular expression to find all titles inside square brackets
    titles = re.findall(r'\["([^"]+)"\]', text)
    title_list = []
    # Print the extracted titles
    for title in titles:
        title = title.replace("_", " ")
        if not title.startswith("Modul:"):
            title = "Şablon:" + title
        title_list.append(title)
    return title_list


class HighUseBot(
    SingleSiteBot,  # A bot only working on one site
    ConfigParserBot,  # A bot which reads options from scripts.ini setting file
    ExistingPageBot,  # CurrentPageBot which only treats existing pages
):
    use_redirects = False  # treats non-redirects only

    update_options = {
        'async': False,
        'showdiff': False,
    }

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

        global VERBOSE
        VERBOSE = self.opt.get('showdiff', False)
        self.bot_name = "User:Balyozxane/skrîpt/py/addhighuse.py"

        self.template_data = bilind_data
        self.bilind_redirects = mytools.get_template_redirects(self.site, 'Bikaranîna bilind')

        print("<<< template_data >>>\n,", self.template_data)

    def add_remove_bilind(self, page, high_use, noinclude=False):
        text = page.text
        bilind_heye = mytools.is_template_in_page(text, self.bilind_redirects)
        if high_use:
            if bilind_heye:
                print('hem bilind e hem jî şablon heye loma ne hewce ye were guhartin')
                return None, None, None
            else:
                template = '{{Bikaranîna bilind}}'
                if noinclude:
                    template = '<noinclude>' + template + '</noinclude>'

                text = template + text
                done = 'lê hat zêdekirin'
                return page, text, done

        else:
            if not bilind_heye:
                print('ne bilind e, şablon jî nîne skip')
                return None, None, None
            else:
                text = mytools.remove_template(text, self.bilind_redirects)
                done = 'hat rakirin'
                return page, text, done

    def treat_page(self) -> None:
        page = self.current_page

        if page.title().endswith('/belge'):
            page_title = re.sub('/belge$', '', page.title())
            page = pywikibot.Page(self.site, page_title)

        title = page.title()
        if title.endswith('.css'):
            return

        high_use = False
        if title in self.template_data:

            high_use = True

        doc_page = pywikibot.Page(self.site, title + '/belge')

        if page.namespace() == 828:
            edited_page, text, done = self.add_remove_bilind(doc_page, high_use)
        else:
            if doc_page.exists():
                edited_page, text, done = self.add_remove_bilind(doc_page, high_use)
            else:
                edited_page, text, done = self.add_remove_bilind(page, high_use, noinclude=True)
        if not edited_page:
            return
        edited_page.text = text
        summary = f'[[{self.bot_name}|Bot]]: Şablona {{{{[[Şablon:Bikaranîna bilind|Bikaranîna bilind]]}}}} {done}'

        if VERBOSE:
            print(f"\n<<< {page.title()} >>>\n")
        edited_page.save(summary=summary)


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
        else:
            options[option] = True
    # The preloading option is responsible for downloading multiple
    # pages from the wiki simultaneously.
    gen = gen_factory.getCombinedGenerator(preload=True)

    if not gen:
        site = pywikibot.Site()
        bilind_page = pywikibot.Page(site, 'Şablon:Bikaranîna bilind')
        bilind_bikartine = set(mytools.referring_page_generator(bilind_page, only_template_inclusion=True))

        bilind_data = get_data_pages(site)
        bilind_set = set()
        for temp in bilind_data:
            templpage = pywikibot.Page(site, temp)
            bilind_set.add(templpage)

        bilind_bikartine.update(bilind_set)
        gen = iter(bilind_bikartine)
        print(gen)
        if gen:
            bot = HighUseBot(generator=gen, bilind_data=bilind_data, **options)
            bot.run()


if __name__ == '__main__':
    main()