#!/usr/bin/env python3"""This script changes the content language of pages.These command line parameters can be used to specify which pages to workon:¶ms;Furthermore, the following command line parameters are supported:-setlang What language the pages should be set to-always If a language is already set for a page, always change it to the one set in -setlang.-never If a language is already set for a page, never change it to the one set in -setlang (keep the current language)... note:: This script is a :class:`ConfigParserBot<bot.ConfigParserBot>`. All options can be set within a settings file which is scripts.ini by default... versionadded:: 5.1"""## (C) Pywikibot team, 2018-2024## Distributed under the terms of the MIT license.#from__future__importannotationsimportpywikibotfrompywikibotimportpagegeneratorsfrompywikibot.botimportConfigParserBot,SingleSiteBotdocuReplacements={# noqa: N816'¶ms;':pagegenerators.parameterHelp,}
[docs]classChangeLangBot(ConfigParserBot,SingleSiteBot):"""Change page language bot. .. versionchanged:: 7.0 ChangeLangBot is a ConfigParserBot """update_options={'never':False,'setlang':'',}def__init__(self,**kwargs)->None:"""Initializer."""super().__init__(**kwargs)assertnot(self.opt.alwaysandself.opt.never), \
'Either "always" or "never" must be set but not both'
[docs]defchangelang(self,page)->None:"""Set page language. :param page: The page to update and save :type page: pywikibot.page.BasePage """parameters={'action':'setpagelanguage','title':page.title(),'lang':self.opt.setlang,'token':self.site.tokens['csrf']}r=self.site.simple_request(**parameters)r.submit()pywikibot.info(f'<<lightpurple>>{page}<<default>>: Setting 'f'page language to <<green>>{self.opt.setlang}')
[docs]deftreat(self,page)->None:"""Treat a page. :param page: The page to treat :type page: pywikibot.page.BasePage """# Current content language of the page and site languageparameters={'action':'query','prop':'info','titles':page.title(),'meta':'siteinfo'}r=self.site.simple_request(**parameters)langcheck=r.submit()['query']currentlang=''forkinlangcheck['pages']:currentlang=langcheck['pages'][k]['pagelanguage']sitelang=langcheck['general']['lang']ifself.opt.setlang==currentlang:pywikibot.info(f'<<lightpurple>>{page}<<default>>: This page is already set 'f'to <<green>>{self.opt.setlang}<<default>>; skipping.')elifcurrentlang==sitelangorself.opt.always:self.changelang(page)elifself.opt.never:pywikibot.info(f'<<lightpurple>>{page}<<default>>: This page already has a 'f'different content language 'f'<<yellow>>{currentlang}<<default>> set; skipping.')else:pywikibot.info(f'\n\n>>> <<lightpurple>>{page.title()}<<default>> <<<')choice=pywikibot.input_choice(f'The content language for this page is already set to 'f'<<yellow>>{currentlang}<<default>>, which is different from 'f'the default ({sitelang}). Change it to'f'<<green>>{self.opt.setlang}<<default>> anyway?',[('Always','a'),('Yes','y'),('No','n'),('Never','v')],default='Y')ifchoice=='a':self.opt.always=Trueelifchoice=='v':self.opt.never=Trueifchoicein'ay':self.changelang(page)else:pywikibot.info('Skipping ...\n')
[docs]defmain(*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 args and prepare generator args parserlocal_args=pywikibot.handle_args(args)gen_factory=pagegenerators.GeneratorFactory()forarginlocal_args:opt,_,value=arg.partition(':')ifopt=='-setlang':options[opt[1:]]=valueelifargin('-always','-never'):options[opt[1:]]=Trueelse:gen_factory.handle_arg(arg)ifnotoptions.get('setlang'):pywikibot.error('No -setlang parameter given.')returnsite=pywikibot.Site()specialpages=site.siteinfo['specialpagealiases']specialpagelist={item['realname']foriteminspecialpages}allowedlanguages=site._paraminfo.parameter(module='setpagelanguage',param_name='lang')['type']# Check if the special page PageLanguage is enabled on the wiki# If it is not, page languages can't be set, and there's no point in# running the bot any furtherif'PageLanguage'notinspecialpagelist:pywikibot.error("This site doesn't allow changing the "'content languages of pages; aborting.')return# Check if the account has the right to change page content language# If it doesn't, there's no point in running the bot any further.if'pagelang'notinsite.userinfo['rights']:pywikibot.error("Your account doesn't have sufficient "'rights to change the content language of pages; '"aborting.\n\nYou must have the 'pagelang' right "'in order to use this script.')return# Check if the language you are trying to set is allowed.ifoptions['setlang']notinallowedlanguages:pywikibot.error('"{}" is not in the list of allowed language codes; ''aborting.\n\n The following is the list of allowed ''languages. Using "default" will unset any set ''language and use the default language for the wiki ''instead.\n\n'.format(options['setlang'])+', '.join(allowedlanguages))returngen=gen_factory.getCombinedGenerator(preload=True)bot=ChangeLangBot(generator=gen,**options)bot.run()