#!/usr/bin/env python3"""Script to log the bot in to a wiki account.Suggestion is to make a special account to use for bot use only. Makesure this bot account is well known on your home wiki before using.The following parameters are supported:-all Try to log in on all sites where a username is defined in user config file (user-config.py).-logout Log out of the current site. Combine with ``-all`` to log out of all sites, or with :ref:`global options` ``-family``, ``-lang`` or ``-site`` to log out of a specific site.-oauth Generate OAuth authentication information. .. note:: Need to copy OAuth tokens to your user config file manually. -logout is not compatible with -oauth.-autocreate Auto-create an account using unified login when necessary. .. note:: the global account must exist already before using this.-async Run the bot in parallel tasks, only useful together with ``-all`` option.. hint:: Use :ref:`global options` ``-code``, ``-family`` or ``-site`` to determine the site to login/logout.If not given as parameter, the script will ask for your username andpassword (password entry will be hidden), log in to your home wiki usingthis combination, and store the resulting cookies (containing yourpassword hash, so keep it secured!) in a file in the data subdirectory.All scripts in this library will be looking for this cookie file andwill use the login information if it is present.To log out, throw away the ``*.lwp`` file that is created in the datasubdirectory... versionchanged:: 7.4 moved to :mod:`pywikibot.scripts` folder"""## (C) Pywikibot team, 2003-2024## Distributed under the terms of the MIT license.#from__future__importannotationsimportdatetimefromcontextlibimportnullcontext,suppressimportpywikibotfrompywikibotimportconfigfrompywikibot.exceptionsimportNoUsernameError,SiteDefinitionErrorfrompywikibot.loginimportOauthLoginManagerfrompywikibot.tools.threadingimportBoundedPoolExecutordef_get_consumer_token(site)->tuple[str,str]:key_msg=f'OAuth consumer key on {site.code}:{site.family}'key=pywikibot.input(key_msg)secret_msg=f'OAuth consumer secret for consumer {key}'secret=pywikibot.input(secret_msg,password=True)returnkey,secretdef_oauth_login(site)->None:consumer_key,consumer_secret=_get_consumer_token(site)login_manager=OauthLoginManager(consumer_secret,site,consumer_key)login_manager.login()identity=login_manager.identityifidentityisNone:pywikibot.error(f'Invalid OAuth info for {site}.')elifsite.username()!=identity['username']:pywikibot.error('Logged in on {site} via OAuth as {wrong}, but expect as {right}'.format(site=site,wrong=identity['username'],right=site.username()))else:oauth_token=login_manager.consumer_token+login_manager.access_tokenpywikibot.info(f'Logged in on {site} as {site.username()} via OAuth consumer 'f'{consumer_key}\nNOTE: To use OAuth, you need to copy the'' following line to your user config file:\n'f'authenticate[{site.hostname()!r}] = {oauth_token}')
[docs]deflogin_one_site(code,family,oauth,logout,autocreate):"""Login on one site."""try:site=pywikibot.Site(code,family)exceptSiteDefinitionError:pywikibot.error(f'{family}:{code} is not a valid site, ''please remove it from your user-config')returnifoauth:_oauth_login(site)returniflogout:site.logout()else:try:site.login(autocreate=autocreate)exceptNoUsernameErrorase:pywikibot.error(e)user=site.user()ifuser:pywikibot.info(f'Logged in on {site} as {user}.')eliflogout:pywikibot.info(f'Logged out of {site}.')else:pywikibot.info(f'Not logged in on {site}.')
[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 """logall=Falselogout=Falseoauth=Falseautocreate=Falseasynchronous=Falseunknown_args=[]forarginpywikibot.handle_args(args):ifarg=='-all':logall=Trueelifarg=='-logout':logout=Trueelifarg=='-oauth':oauth=Trueelifarg=='-autocreate':autocreate=Trueelifarg=='-async':asynchronous=Trueelse:unknown_args.append(arg)ifpywikibot.bot.suggest_help(unknown_parameters=unknown_args):returniflogall:namedict=config.usernameselse:site=pywikibot.Site()namedict={site.family.name:{site.code:None}}params=oauth,logout,autocreatecontext=(nullcontext(),BoundedPoolExecutor('ThreadPoolExecutor'))[asynchronous]withcontextasexecutor:forfamily_nameinnamedict:forlanginnamedict[family_name]:ifasynchronous:executor.submit(login_one_site,lang,family_name,*params)else:login_one_site(lang,family_name,*params)