Bikarhêner:Balyozxane/katbike.py

import pywikibot
import re
from pywikibot import pagegenerators
from pywikibot.bot import AutomaticTWSummaryBot, ConfigParserBot, SingleSiteBot

# Bikaranîn:
# Di heman klasora bi pywikibotê de skrîpteke bi navê "myBot.py" çêkin û koda li vir têxin wê skrîptê. Ji bîr nekin syntaxhighlight li destpêkê û dawiyê jê bibin. Dûre lîsteyeke kategoriyan ji rûpela [[Taybet:Kategorîyên tên xwestin]] çêkin û di dosyeyeke bi navê "list.txt" qeyd bikin û koda li jêr bixebitînin:
# python pwb.py myBot -file:list.txt

class AppendTextBot(
    SingleSiteBot,
    ConfigParserBot,
    AutomaticTWSummaryBot,
):
    summary_key = 'basic-changing'
    use_redirects = False
    update_options = {
        'summary': None,
        'text': '{{katbike}}', 
        'top': False,
    }

    def fetch_interwiki_link_content(self, page_title):
        site = pywikibot.Site("ku", "wiktionary")  # Local wiki (ku.wiktionary.org)
        pywikibot.output(f"Fetching interwiki link content for page: {page_title}")

        # Remove "Kategorî:" from the page title
        cleaned_title = page_title.replace("Kategorî:", "")

        # Fetch the result of Module:înterwîkî-çêke from the local wiki
        params = {
            "action": "expandtemplates",
            "format": "json",
            "text": f"{{{{#invoke:înterwîkî-çêke|biwesine|{cleaned_title}}}}}",
            "prop": "wikitext"
        }
        request = pywikibot.data.api.Request(site=site, **params)
        response = request.submit()
        data = response['expandtemplates']
        interwiki_link_content = data['wikitext']

        category_result = "Category:" + interwiki_link_content  # Add "Category:" to the result

        # Check if the page exists on en.wiktionary.org
        en_site = pywikibot.Site("en", "wiktionary")
        page = pywikibot.Page(en_site, category_result)
        page_exists = page.exists()

        return {
            "content": category_result,
            "pageExists": page_exists
        }

    def treat_page(self) -> None:
        page = self.current_page
        pywikibot.output(f"Processing page: {page.title()}")

        if page.exists():
            pywikibot.output(f"Page '{page.title()}' already exists. Skipping.")
            return

        text = page.text
        text_to_append = self.opt.text

        if self.opt.top:
            text = text_to_append + text
        else:
            text += text_to_append

        interwiki_content = self.fetch_interwiki_link_content(page.title())
        pywikibot.output(f"Interwiki content: {interwiki_content['content']}")

        summary = None
        
        if interwiki_content['pageExists']:
            summary = (
                f"Rûpel bi {{{{[[Şablon:katbike|katbike]]}}}} hat çêkirin "
                f"û înterwîkî [[en:{interwiki_content['content']}]] lê hat zêdekirin"
            )
            text += "\n" + "[[en:" + interwiki_content['content'] + "]]"
        else:
            summary = (
                f"Rûpel bi {{{{[[Şablon:katbike|katbike]]}}}} hat çêkirin "
                f"lê înterwîkî [[en:{interwiki_content['content']}]] li en.wiktê tine ye"
            )

        pywikibot.output(f"Final text to put: {text}")

        self.put_current(text, summary=summary)

def main(*args: str) -> None:
    local_args = pywikibot.handle_args(args)
    gen_factory = pagegenerators.GeneratorFactory()
    local_args = gen_factory.handle_args(local_args)

    options = {'text': '{{katbike}}'}  # Set the default text to append

    for arg in local_args:
        option, _, value = arg.partition(':')
        if option in ('summary', 'text'):
            if not value:
                pywikibot.input(f'Please enter a value for {option}')
            options[option] = value
        else:
            options[option] = True

    gen = gen_factory.getCombinedGenerator(preload=True)

    if not pywikibot.bot.suggest_help(missing_generator=not gen):
        bot = AppendTextBot(generator=gen, **options)
        bot.run()

if __name__ == '__main__':
    main()