def __init__(self, password=None, sysop=False, site=None, user=None): if site is not None: self.site = site else: self.site = pywikibot.Site() if user: self.username = user elif sysop: try: self.username = config.sysopnames\ [self.site.family.name][self.site.code] except KeyError: raise NoUsername( u"""ERROR: Sysop username for %(fam_name)s:%(wiki_code)s is undefined. If you have a sysop account for that site, please add a line to user-config.py: sysopnames['%(fam_name)s']['%(wiki_code)s'] = 'myUsername'""" % {'fam_name': self.site.family.name, 'wiki_code': self.site.code}) else: try: self.username = config.usernames\ [self.site.family.name][self.site.code] except: raise NoUsername( u"""ERROR: Username for %(fam_name)s:%(wiki_code)s is undefined. If you have an account for that site, please add a line to user-config.py: usernames['%(fam_name)s']['%(wiki_code)s'] = 'myUsername'""" % {'fam_name': self.site.family.name, 'wiki_code': self.site.code}) self.password = password if getattr(config, 'password_file', ''): self.readPassword()
def login(self, retry=False, autocreate=False): """ Attempt to log into the server. @param retry: infinitely retry if the API returns an unknown error @type retry: bool @param autocreate: if true, allow auto-creation of the account using unified login @type autocreate: bool @raises NoUsername: Username is not recognised by the site. """ if not self.password: # First check that the username exists, # to avoid asking for a password that will not work. if not autocreate: self.check_user_exists() # As we don't want the password to appear on the screen, we set # password = True self.password = pywikibot.input( 'Password for user %(name)s on %(site)s (no characters will ' 'be shown):' % { 'name': self.login_name, 'site': self.site }, password=True) pywikibot.output('Logging in to %(site)s as %(name)s' % { 'name': self.login_name, 'site': self.site }) try: cookiedata = self.getCookie() except pywikibot.data.api.APIError as e: pywikibot.error('Login failed (%s).' % e.code) if e.code == 'NotExists': raise NoUsername("Username '%s' does not exist on %s" % (self.login_name, self.site)) elif e.code == 'Illegal': raise NoUsername("Username '%s' is invalid on %s" % (self.login_name, self.site)) elif e.code == 'readapidenied': raise NoUsername( 'Username "{0}" does not have read permissions on ' '{1}'.format(self.login_name, self.site)) elif e.code == 'Failed': raise NoUsername( 'Username "{0}" does not have read permissions on ' '{1}\n.{2}'.format(self.login_name, self.site, e.info)) # TODO: investigate other unhandled API codes (bug T75539) if retry: self.password = None return self.login(retry=True) else: return False self.storecookiedata(cookiedata) pywikibot.log('Should be logged in now') return True
def login(self, retry=False): """ Attempt to log into the server. @param retry: infinitely retry if the API returns an unknown error @type retry: bool @raises NoUsername: Username is not recognised by the site. """ if not self.password: # First check that the username exists, # to avoid asking for a password that will not work. self.check_user_exists() # As we don't want the password to appear on the screen, we set # password = True self.password = pywikibot.input( u'Password for user %(name)s on %(site)s (no characters will ' u'be shown):' % { 'name': self.username, 'site': self.site }, password=True) pywikibot.output(u"Logging in to %(site)s as %(name)s" % { 'name': self.username, 'site': self.site }) try: cookiedata = self.getCookie() except pywikibot.data.api.APIError as e: pywikibot.error(u"Login failed (%s)." % e.code) if e.code == 'NotExists': raise NoUsername(u"Username '%s' does not exist on %s" % (self.username, self.site)) elif e.code == 'Illegal': raise NoUsername(u"Username '%s' is invalid on %s" % (self.username, self.site)) # TODO: investigate other unhandled API codes (bug 73539) if retry: self.password = None return self.login(retry=True) else: return False self.storecookiedata(cookiedata) pywikibot.log(u"Should be logged in now") # # Show a warning according to the local bot policy # FIXME: disabled due to recursion; need to move this to the Site object after # login # if not self.botAllowed(): # logger.error( # u"Username '%(name)s' is not listed on [[%(page)s]]." # % {'name': self.username, # 'page': botList[self.site.family.name][self.site.code]}) # logger.error( # "Please make sure you are allowed to use the robot before actually using it!") # return False return True
def __init__(self, password=None, sysop=False, site=None, user=None): """ Initializer. All parameters default to defaults in user-config. @param site: Site object to log into @type site: BaseSite @param user: username to use. If user is None, the username is loaded from config.usernames. @type user: basestring @param password: password to use @type password: basestring @param sysop: login as sysop account. The sysop username is loaded from config.sysopnames. @type sysop: bool @raises NoUsername: No username is configured for the requested site. """ self.site = site or pywikibot.Site() if user: self.username = user elif sysop: config_names = config.sysopnames family_sysopnames = (config_names[self.site.family.name] or config_names['*']) self.username = family_sysopnames.get(self.site.code, None) try: self.username = self.username or family_sysopnames['*'] except KeyError: raise NoUsername(""" \ ERROR: Sysop username for %(fam_name)s:%(wiki_code)s is undefined. If you have a sysop account for that site, please add a line to user-config.py: sysopnames['%(fam_name)s']['%(wiki_code)s'] = 'myUsername'""" % { 'fam_name': self.site.family.name, 'wiki_code': self.site.code }) else: config_names = config.usernames family_usernames = (config_names[self.site.family.name] or config_names['*']) self.username = family_usernames.get(self.site.code, None) try: self.username = self.username or family_usernames['*'] except KeyError: raise NoUsername(""" \ ERROR: Username for %(fam_name)s:%(wiki_code)s is undefined. If you have an account for that site, please add a line to user-config.py: usernames['%(fam_name)s']['%(wiki_code)s'] = 'myUsername'""" % { 'fam_name': self.site.family.name, 'wiki_code': self.site.code }) self.password = password self.login_name = self.username if getattr(config, 'password_file', ''): self.readPassword()
def check_user_exists(self): """ Check that the username exists on the site. @see: U{https://www.mediawiki.org/wiki/API:Users} @raises NoUsername: Username doesn't exist in user list. """ # convert any Special:BotPassword usernames to main account equivalent main_username = self.username if '@' in self.username: warn('When using BotPasswords it is recommended that you store ' 'your login credentials in a password_file instead. See ' '{}/BotPasswords for instructions and more information.'. format(__url__)) main_username = self.username.partition('@')[0] try: data = self.site.allusers(start=main_username, total=1) user = next(iter(data)) except pywikibot.data.api.APIError as e: if e.code == 'readapidenied': pywikibot.warning('Could not check user %s exists on %s' % (main_username, self.site)) return else: raise if user['name'] != main_username: # Report the same error as server error code NotExists raise NoUsername("Username '%s' does not exist on %s" % (main_username, self.site))
def __init__(self, password=None, site=None, user=None): """ Initializer. All parameters default to defaults in user-config. @param site: Site object to log into @type site: BaseSite @param user: username to use. If user is None, the username is loaded from config.usernames. @type user: basestring @param password: password to use @type password: basestring @raises NoUsername: No username is configured for the requested site. """ site = self.site = site or pywikibot.Site() if not user: config_names = config.usernames code_to_usr = config_names[site.family.name] or config_names['*'] try: user = code_to_usr.get(site.code) or code_to_usr['*'] except KeyError: raise NoUsername( 'ERROR: ' 'username for {site.family.name}:{site.code} is undefined.' '\nIf you have a username for that site, ' 'please add a line to user-config.py as follows:\n' "usernames['{site.family.name}']['{site.code}'] = " "'myUsername'".format(site=site)) self.password = password self.login_name = self.username = user if getattr(config, 'password_file', ''): self.readPassword()
def login(self, retry=False, autocreate=False): """ Attempt to log into the server. @see: U{https://www.mediawiki.org/wiki/API:Login} @param retry: infinitely retry if the API returns an unknown error @type retry: bool @param autocreate: if true, allow auto-creation of the account using unified login @type autocreate: bool @raises pywikibot.exceptions.NoUsername: Username is not recognised by the site. """ if not self.password: # First check that the username exists, # to avoid asking for a password that will not work. if not autocreate: self.check_user_exists() # As we don't want the password to appear on the screen, we set # password = True self.password = pywikibot.input( 'Password for user %(name)s on %(site)s (no characters will ' 'be shown):' % { 'name': self.login_name, 'site': self.site }, password=True) pywikibot.output('Logging in to %(site)s as %(name)s' % { 'name': self.login_name, 'site': self.site }) try: cookiedata = self.getCookie() except pywikibot.data.api.APIError as e: error_code = e.code pywikibot.error('Login failed ({}).'.format(error_code)) if error_code in self._api_error: error_msg = 'Username "{}" {} on {}'.format( self.login_name, self._api_error[error_code], self.site) if error_code in ('Failed', 'FAIL'): error_msg += '\n.{}'.format(e.info) raise NoUsername(error_msg) # TODO: investigate other unhandled API codes (bug T75539) if retry: self.password = None return self.login(retry=True) else: return False self.storecookiedata(cookiedata) pywikibot.log('Should be logged in now') return True
def __init__(self, password=None, sysop=False, site=None, user=None): """ Initializer. All parameters default to defaults in user-config. @param site: Site object to log into @type site: BaseSite @param user: username to use. If user is None, the username is loaded from config.usernames. @type user: basestring @param password: password to use @type password: basestring @param sysop: login as sysop account. The sysop username is loaded from config.sysopnames. @type sysop: bool @raises NoUsername: No username is configured for the requested site. """ site = self.site = site or pywikibot.Site() if not user: if sysop: config_names = config.sysopnames else: config_names = config.usernames code_to_usr = config_names[site.family.name] or config_names['*'] try: user = code_to_usr.get(site.code) or code_to_usr['*'] except KeyError: raise NoUsername( 'ERROR: ' '{account} for {fam_name}:{wiki_code} is undefined.\n' 'If you have a {account} for that site, ' 'please add a line to user-config.py as follows:\n' "{account}s['{fam_name}']['{wiki_code}'] = 'myUsername'". format(fam_name=site.family.name, wiki_code=site.code, account='sysopname' if sysop else 'username')) self.password = password self.login_name = self.username = user if getattr(config, 'password_file', ''): self.readPassword()
def check_user_exists(self): """ Check that the username exists on the site. @raises NoUsername: Username doesnt exist in user list. """ try: data = self.site.allusers(start=self.username, total=1) user = next(iter(data)) except pywikibot.data.api.APIError as e: if e.code == 'readapidenied': pywikibot.warning('Could not check user %s exists on %s' % (self.username, self.site)) return else: raise if user['name'] != self.username: # Report the same error as server error code NotExists raise NoUsername('Username \'%s\' does not exist on %s' % (self.username, self.site))