#!/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:: -family:FF Log in to the LL language of the FF family. -lang:LL Example: -family:wiktionary -lang:fr will log you in at fr.wiktionary.org. -site:FF:LL Log in to the LL language of the FF family -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 -family and -lang 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 tasksIf 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 your passwordhash, so keep it secured!) in a file in the data subdirectory.All scripts in this library will be looking for this cookie file and willuse 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-2023## Distributed under the terms of the MIT license.#from__future__importannotationsimportdatetimefromconcurrent.futuresimportThreadPoolExecutorfromcontextlibimportnullcontext,suppressimportpywikibotfrompywikibotimportconfigfrompywikibot.exceptionsimportNoUsernameError,SiteDefinitionErrorfrompywikibot.loginimportOauthLoginManagerdef_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('Logged in on {site} as {username} via OAuth consumer {consumer}\n''NOTE: To use OAuth, you need to copy the following line to your ''user config file:\n authenticate[{hostname!r}] = {oauth_token}'.format(site=site,username=site.username(),consumer=consumer_key,hostname=site.hostname(),oauth_token=oauth_token))
[docs]deflogin_one_site(code,family,oauth,logout,autocreate):"""Login on one site."""try:site=pywikibot.Site(code,family)exceptSiteDefinitionError:pywikibot.error('{}:{} is not a valid site, ''please remove it from your user-config'.format(family,code))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=Falseasyncronous=Falseunknown_args=[]forarginpywikibot.handle_args(args):ifarg=='-all':logall=Trueelifarg=='-logout':logout=Trueelifarg=='-oauth':oauth=Trueelifarg=='-autocreate':autocreate=Trueelifarg=='-async':asyncronous=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=ThreadPoolExecutorifasyncronouselsenullcontextwithcontext()asexecutor:forfamily_nameinnamedict:forlanginnamedict[family_name]:ifasyncronous:executor.submit(login_one_site,lang,family_name,*params)else:login_one_site(lang,family_name,*params)