pywikibot package

The initialization file for the Pywikibot framework.

exception pywikibot.BadTitle(arg)[source]

Bases: pywikibot.exceptions.Error

Server responded with BadTitle.

__module__ = 'pywikibot.exceptions'
class pywikibot.Bot(site=None, **kwargs)[source]

Bases: pywikibot.bot.BaseBot

Generic bot subclass for multiple sites.

If possible the MultipleSitesBot or SingleSiteBot classes should be used instead which specifically handle multiple or single sites.

__init__(site=None, **kwargs)[source]

Create a Bot instance and initialize cached sites.

__module__ = 'pywikibot.bot'
init_page(item)[source]

Update site before calling treat.

run()[source]

Check if it automatically updates the site before run.

site

Get the current site.

pywikibot.calledModuleName()[source]

Return the name of the module calling this function.

This is required because the -help option loads the module’s docstring and because the module name will be used for the filename of the log.

Return type:str
exception pywikibot.CaptchaError(arg)[source]

Bases: pywikibot.exceptions.Error

Captcha is asked and config.solve_captcha == False.

__module__ = 'pywikibot.exceptions'
exception pywikibot.CascadeLockedPage(page, message=None)[source]

Bases: pywikibot.exceptions.LockedPage

Page is locked due to cascading protection.

__module__ = 'pywikibot.exceptions'
message = 'Page %s is locked due to cascading protection.'
class pywikibot.Category(source, title='', sort_key=None, insite=NotImplemented, sortKey='[deprecated name of sort_key]')[source]

Bases: pywikibot.page.Page

A page in the Category: namespace.

__init__(source, title='', sort_key=None, insite=NotImplemented, sortKey='[deprecated name of sort_key]')[source]

Initializer.

All parameters are the same as for Page() Initializer.

__module__ = 'pywikibot.page'
articles(recurse=False, total=None, content=False, namespaces=None, sortby=None, reverse=False, starttime=None, endtime=None, startsort=None, endsort=None, startprefix=None, endprefix=None, startFrom='[deprecated name of startprefix]', step=NotImplemented)[source]

Yield all articles in the current category.

By default, yields all pages in the category that are not subcategories!

Parameters:
  • recurse (int or bool) – if not False or 0, also iterate articles in subcategories. If an int, limit recursion to this number of levels. (Example: recurse=1 will iterate articles in first-level subcats, but no deeper.)
  • total – iterate no more than this number of pages in total (at all levels)
  • namespaces (int or list of ints) – only yield pages in the specified namespaces
  • content – if True, retrieve the content of the current version of each page (default False)
  • sortby (str) – determines the order in which results are generated, valid values are “sortkey” (default, results ordered by category sort key) or “timestamp” (results ordered by time page was added to the category). This applies recursively.
  • reverse – if True, generate results in reverse order (default False)
  • starttime (pywikibot.Timestamp) – if provided, only generate pages added after this time; not valid unless sortby=”timestamp”
  • endtime (pywikibot.Timestamp) – if provided, only generate pages added before this time; not valid unless sortby=”timestamp”
  • startsort (str) – if provided, only generate pages that have a sortkey >= startsort; not valid if sortby=”timestamp” (Deprecated in MW 1.24)
  • endsort (str) – if provided, only generate pages that have a sortkey <= endsort; not valid if sortby=”timestamp” (Deprecated in MW 1.24)
  • startprefix (str) – if provided, only generate pages >= this title lexically; not valid if sortby=”timestamp”; overrides “startsort” (requires MW 1.18+)
  • endprefix (str) – if provided, only generate pages < this title lexically; not valid if sortby=”timestamp”; overrides “endsort” (requires MW 1.18+)
Return type:

typing.Iterable[pywikibot.Page]

Return a link to place a page in this Category.

Use this only to generate a “true” category link, not for interwikis or text links to category pages.

Parameters:sort_key ((optional) unicode) – The sort key for the article to be placed in this Category; if omitted, default sort key is used.
categoryinfo

Return a dict containing information about the category.

The dict contains values for:

Numbers of pages, subcategories, files, and total contents.

Return type:dict
copyAndKeep(catname, cfd_templates, message, cfdTemplates='[deprecated name of cfd_templates]')[source]

Copy partial category page text (not contents) to a new title.

Like copyTo above, except this removes a list of templates (like deletion templates) that appear in the old category text. It also removes all text between the two HTML comments BEGIN CFD TEMPLATE and END CFD TEMPLATE. (This is to deal with CFD templates that are substituted.)

Returns true if copying was successful, false if target page already existed.

Parameters:
  • catname – New category title (without namespace)
  • cfd_templates – A list (or iterator) of templates to be removed from the page text
Returns:

True if copying was successful, False if target page already existed.

Return type:

bool

copyTo(cat, message)[source]

Copy text of category page to a new page. Does not move contents.

Parameters:
  • cat (str or Category) – New category title (without namespace) or Category object
  • message (str) – message to use for category creation message If two %s are provided in message, will be replaced by (self.title, authorsList)
Returns:

True if copying was successful, False if target page already existed.

Return type:

bool

isEmptyCategory()[source]

Return True if category has no members (including subcategories).

Return type:bool
isHiddenCategory()[source]

Return True if the category is hidden.

Return type:bool
members(recurse=False, namespaces=None, total=None, content=False, step=NotImplemented)[source]

Yield all category contents (subcats, pages, and files).

Return type:typing.Iterable[pywikibot.Page]
newest_pages(total=None)[source]

Return pages in a category ordered by the creation date.

If two or more pages are created at the same time, the pages are returned in the order they were added to the category. The most recently added page is returned first.

It only allows to return the pages ordered from newest to oldest, as it is impossible to determine the oldest page in a category without checking all pages. But it is possible to check the category in order with the newly added first and it yields all pages which were created after the currently checked page was added (and thus there is no page created after any of the cached but added before the currently checked).

Parameters:total (int) – The total number of pages queried.
Returns:A page generator of all pages in a category ordered by the creation date. From newest to oldest. Note: It currently only returns Page instances and not a subclass of it if possible. This might change so don’t expect to only get Page instances.
Return type:generator
subcategories(recurse=False, total=None, content=False, startFrom=NotImplemented, step=NotImplemented, cacheResults=NotImplemented)[source]

Iterate all subcategories of the current category.

Parameters:
  • recurse (int or bool) – if not False or 0, also iterate subcategories of subcategories. If an int, limit recursion to this number of levels. (Example: recurse=1 will iterate direct subcats and first-level sub-sub-cats, but no deeper.)
  • total – iterate no more than this number of subcategories in total (at all levels)
  • content – if True, retrieve the content of the current version of each category description page (default False)
exception pywikibot.CircularRedirect(page, message=None)[source]

Bases: pywikibot.exceptions.PageRelatedError

Page is a circular redirect.

Exception argument is the redirect target; this may be the same title as this page or a different title (in which case the target page directly or indirectly redirects back to this one)

__module__ = 'pywikibot.exceptions'
message = 'Page %s is a circular redirect.'
class pywikibot.Claim(site, pid, snak=None, hash=None, is_reference=False, is_qualifier=False, rank='normal', **kwargs, isQualifier='[deprecated name of is_qualifier]', isReference='[deprecated name of is_reference]')[source]

Bases: pywikibot.page.Property

A Claim on a Wikibase entity.

Claims are standard claims as well as references and qualifiers.

SNAK_TYPES = ('value', 'somevalue', 'novalue')
TARGET_CONVERTER = {'commonsMedia': <function Claim.<lambda>>, 'geo-shape': <bound method type.fromWikibase of <class 'pywikibot.WbGeoShape'>>, 'globe-coordinate': <bound method type.fromWikibase of <class 'pywikibot.Coordinate'>>, 'monolingualtext': <function Claim.<lambda>>, 'quantity': <bound method type.fromWikibase of <class 'pywikibot.WbQuantity'>>, 'tabular-data': <bound method type.fromWikibase of <class 'pywikibot.WbTabularData'>>, 'time': <bound method type.fromWikibase of <class 'pywikibot.WbTime'>>, 'wikibase-item': <function Claim.<lambda>>, 'wikibase-property': <function Claim.<lambda>>}
__eq__(other)[source]

Return self==value.

__hash__ = None
__init__(site, pid, snak=None, hash=None, is_reference=False, is_qualifier=False, rank='normal', **kwargs, isQualifier='[deprecated name of is_qualifier]', isReference='[deprecated name of is_reference]')[source]

Initializer.

Defined by the “snak” value, supplemented by site + pid

Parameters:
  • site (pywikibot.site.DataSite) – repository the claim is on
  • pid – property id, with “P” prefix
  • snak – snak identifier for claim
  • hash – hash identifier for references
  • is_reference – whether specified claim is a reference
  • is_qualifier – whether specified claim is a qualifier
  • rank – rank for claim
__module__ = 'pywikibot.page'
__ne__(other)[source]

Return self!=value.

__repr__()[source]

Return the representation string.

addQualifier(qualifier, **kwargs)[source]

Add the given qualifier.

Parameters:qualifier (Claim) – the qualifier to add
addSource(claim, **kwargs)[source]

Add the claim as a source.

Parameters:claim (pywikibot.Claim) – the claim to add
addSources(claims, **kwargs)[source]

Add the claims as one source.

Parameters:claims (list of pywikibot.Claim) – the claims to add
changeRank(rank, **kwargs)[source]

Change the rank of the Claim and save.

changeSnakType(value=None, **kwargs)[source]

Save the new snak value.

TODO: Is this function really needed?

changeTarget(value=None, snaktype='value', **kwargs)[source]

Set the target value in the data repository.

Parameters:
  • value (object) – The new target value.
  • snaktype (str ('value', 'somevalue', or 'novalue')) – The new snak type.
copy()[source]

Create an independent copy of this object.

Return type:Claim
classmethod fromJSON(site, data)[source]

Create a claim object from JSON returned in the API call.

Parameters:data (dict) – JSON containing claim data
Return type:Claim
getRank()[source]

Return the rank of the Claim.

getSnakType()[source]

Return the type of snak.

Returns:str (‘value’, ‘somevalue’ or ‘novalue’)
Return type:str
getSources()[source]

Return a list of sources, each being a list of Claims.

Return type:list
getTarget()[source]

Return the target value of this Claim.

None is returned if no target is set

Returns:object
has_qualifier(qualifier_id, target)[source]

Check whether Claim contains specified qualifier.

Parameters:
  • qualifier_id (str) – id of the qualifier
  • target – qualifier target to check presence of
Returns:

true if the qualifier was found, false otherwise

Return type:

bool

classmethod qualifierFromJSON(site, data)[source]

Create a Claim for a qualifier from JSON.

Qualifier objects are represented a bit differently like references, but I’m not sure if this even requires it’s own function.

Return type:Claim
classmethod referenceFromJSON(site, data)[source]

Create a dict of claims from reference JSON returned in the API call.

Reference objects are represented a bit differently, and require some more handling.

Return type:dict
removeQualifier(qualifier, **kwargs)[source]

Remove the qualifier. Call removeQualifiers().

Parameters:qualifier (Claim) – the qualifier to remove
removeQualifiers(qualifiers, **kwargs)[source]

Remove the qualifiers.

Parameters:qualifiers (list Claim) – the qualifiers to remove
removeSource(source, **kwargs)[source]

Remove the source. Call removeSources().

Parameters:source (pywikibot.Claim) – the source to remove
removeSources(sources, **kwargs)[source]

Remove the sources.

Parameters:sources (list of pywikibot.Claim) – the sources to remove
setRank(rank)[source]

Set the rank of the Claim.

setSnakType(value)[source]

Set the type of snak.

Parameters:value (str ('value', 'somevalue', or 'novalue')) – Type of snak
setTarget(value)[source]

Set the target value in the local object.

Parameters:value (object) – The new target value.
Raises:ValueError – if value is not of the type required for the Claim type.
target_equals(value)[source]

Check whether the Claim’s target is equal to specified value.

The function checks for:

  • WikibasePage ID equality
  • WbTime year equality
  • Coordinate equality, regarding precision
  • WbMonolingualText text equality
  • direct equality
Parameters:value – the value to compare with
Returns:true if the Claim’s target is equal to the value provided, false otherwise
Return type:bool
toJSON()[source]

Create dict suitable for the MediaWiki API.

Return type:dict
exception pywikibot.CoordinateGlobeUnknownException(arg)[source]

Bases: pywikibot.exceptions.WikiBaseError, NotImplementedError

This globe is not implemented yet in either WikiBase or pywikibot.

__module__ = 'pywikibot.exceptions'
pywikibot.critical(text, decoder=None, newline=True, **kwargs)[source]

Output a critical record to the user via the userinterface.

class pywikibot.CurrentPageBot(**kwargs)[source]

Bases: pywikibot.bot.BaseBot

A bot which automatically sets ‘current_page’ on each treat().

This class should be always used together with either the MultipleSitesBot or SingleSiteBot class as there is no site management in this class.

__module__ = 'pywikibot.bot'
ignore_server_errors = False
put_current(new_text, ignore_save_related_errors=None, ignore_server_errors=None, **kwargs, comment='[deprecated name of summary]')[source]

Call Bot.userPut but use the current page.

It compares the new_text to the current page text.

Parameters:
  • new_text (basestring) – The new text
  • ignore_save_related_errors (bool or None) – Ignore save related errors and automatically print a message. If None uses this instances default.
  • ignore_server_errors (bool or None) – Ignore server errors and automatically print a message. If None uses this instances default.
  • kwargs – Additional parameters directly given to Bot.userPut.
Returns:

whether the page was saved successfully

Return type:

bool

treat(page)[source]

Set page to current page and treat that page.

treat_page()[source]

Process one page (Abstract method).

pywikibot.debug(text, layer, decoder=None, newline=True, **kwargs)[source]

Output a debug record to the log file.

Parameters:layer – The name of the logger that text will be sent to.
exception pywikibot.EditConflict(page, message=None)[source]

Bases: pywikibot.exceptions.PageSaveRelatedError

There has been an edit conflict while uploading the page.

__module__ = 'pywikibot.exceptions'
message = 'Page %s could not be saved due to an edit conflict'
pywikibot.error(text, decoder=None, newline=True, **kwargs)[source]

Output an error message to the user via the userinterface.

exception pywikibot.Error(arg)[source]

Bases: pywikibot.tools.UnicodeMixin, Exception

Pywikibot error.

__init__(arg)[source]

Initializer.

__module__ = 'pywikibot.exceptions'
__unicode__()[source]

Return a unicode string representation.

pywikibot.exception(msg=None, decoder=None, newline=True, tb=False, **kwargs)[source]

Output an error traceback to the user via the userinterface.

Use directly after an ‘except’ statement:

...
except Exception:
    pywikibot.exception()
...

or alternatively:

...
except Exception as e:
    pywikibot.exception(e)
...
Parameters:tb – Set to True in order to output traceback also.
exception pywikibot.FatalServerError(arg)[source]

Bases: pywikibot.exceptions.ServerError

A fatal server error will not be corrected by resending the request.

__module__ = 'pywikibot.exceptions'
class pywikibot.FilePage(source, title='', insite=NotImplemented)[source]

Bases: pywikibot.page.Page

A subclass of Page representing a file description page.

Supports the same interface as Page, with some added methods.

__init__(source, title='', insite=NotImplemented)[source]

Initializer.

__module__ = 'pywikibot.page'
download(filename=None, chunk_size=102400, revision=None)[source]

Download to filename file of FilePage.

Parameters:
  • filename (None or str) – filename where to save file: None: self.title(as_filename=True, with_ns=False) will be used str: provided filename will be used.
  • chunk_size (int) – the size of each chunk to be received and written to file.
  • revision (None or FileInfo) – file revision to download: None: self.latest_file_info will be used FileInfo: provided revision will be used.
Returns:

True if download is successful, False otherwise.

Raise:

IOError if filename cannot be written for any reason.

fileIsOnCommons()[source]

DEPRECATED. Check if the image is stored on Wikimedia Commons.

Return type:bool
fileIsShared()[source]

Check if the file is stored on any known shared repository.

Return type:bool
getFileVersionHistoryTable()[source]

Return the version history in the form of a wiki table.

getImagePageHtml()[source]

Download the file page, and return the HTML, as a unicode string.

Caches the HTML code, so that if you run this method twice on the same FilePage object, the page will only be downloaded once.

get_file_history()[source]

Return the file’s version history.

Returns:dictionary with: key: timestamp of the entry value: instance of FileInfo()
Return type:dict
get_file_url(url_width=None, url_height=None, url_param=None)[source]

Return the url or the thumburl of the file described on this page.

Fetch the information if not available.

Once retrieved, thumburl information will also be accessible as latest_file_info attributes, named as in [1]: - url, thumburl, thumbwidth and thumbheight

Parameters correspond to iiprops in: [1] https://www.mediawiki.org/wiki/API:Imageinfo

Parameters validation and error handling left to the API call.

Parameters:
  • url_width – see iiurlwidth in [1]
  • url_height – see iiurlheigth in [1]
  • url_param – see iiurlparam in [1]
Returns:

latest file url or thumburl

Return type:

str

globalusage(total=None)[source]

Iterate all global usage for this page.

Parameters:total – iterate no more than this number of pages in total
Returns:a generator that yields Pages also on sites different from self.site.
Return type:generator
latest_file_info

Retrieve and store information of latest Image rev. of FilePage.

At the same time, the whole history of Image is fetched and cached in self._file_revisions

Returns:instance of FileInfo()
oldest_file_info

Retrieve and store information of oldest Image rev. of FilePage.

At the same time, the whole history of Image is fetched and cached in self._file_revisions

Returns:instance of FileInfo()
upload(source, **kwargs)[source]

Upload this file to the wiki.

keyword arguments are from site.upload() method.

Parameters:

source (str) – Path or URL to the file to be uploaded.

Keyword Arguments:
 
  • comment – Edit summary; if this is not provided, then filepage.text will be used. An empty summary is not permitted. This may also serve as the initial page text (see below).
  • text – Initial page text; if this is not set, then filepage.text will be used, or comment.
  • watch – If true, add filepage to the bot user’s watchlist
  • ignore_warnings – It may be a static boolean, a callable returning a boolean or an iterable. The callable gets a list of UploadWarning instances and the iterable should contain the warning codes for which an equivalent callable would return True if all UploadWarning codes are in thet list. If the result is False it’ll not continue uploading the file and otherwise disable any warning and reattempt to upload the file. NOTE: If report_success is True or None it’ll raise an UploadWarning exception if the static boolean is False.
  • chunk_size – The chunk size in bytesfor chunked uploading (see https://www.mediawiki.org/wiki/API:Upload#Chunked_uploading). It will only upload in chunks, if the version number is 1.20 or higher and the chunk size is positive but lower than the file size.
  • _file_key – Reuses an already uploaded file using the filekey. If None (default) it will upload the file.
  • _offset – When file_key is not None this can be an integer to continue a previously canceled chunked upload. If False it treats that as a finished upload. If True it requests the stash info from the server to determine the offset. By default starts at 0.
  • _verify_stash – Requests the SHA1 and file size uploaded and compares it to the local file. Also verifies that _offset is matching the file size if the _offset is an int. If _offset is False if verifies that the file size match with the local file. If None it’ll verifies the stash when a file key and offset is given.
  • report_success – If the upload was successful it’ll print a success message and if ignore_warnings is set to False it’ll raise an UploadWarning if a warning occurred. If it’s None (default) it’ll be True if ignore_warnings is a bool and False otherwise. If it’s True or None ignore_warnings must be a bool.
Returns:

It returns True if the upload was successful and False otherwise.

Return type:

bool

usingPages(total=None, content=False, step=NotImplemented)[source]

Yield Pages on which the file is displayed.

Parameters:
  • total – iterate no more than this number of pages in total
  • content – if True, load the current content of each iterated page (default False)
pywikibot.handle_args(args=None, do_help=True)[source]

Handle standard command line arguments, and return the rest as a list.

Takes the command line arguments as Unicode strings, processes all global parameters such as -lang or -log, initialises the logging layer, which emits startup information into log at level ‘verbose’.

This makes sure that global arguments are applied first, regardless of the order in which the arguments were given.

args may be passed as an argument, thereby overriding sys.argv

Parameters:
  • args (typing.Iterable) – Command line arguments
  • do_help (bool) – Handle parameter ‘-help’ to show help and invoke sys.exit
Returns:

list of arguments not recognised globally

Return type:

list of unicode

pywikibot.html2unicode(text, ignore=None, exceptions=None)[source]

Replace HTML entities with equivalent unicode.

Parameters:
  • ignore – HTML entities to ignore
  • ignore – list of int
Return type:

str

pywikibot.input(question, password=False, default='', force=False)[source]

Ask the user a question, return the user’s answer.

Parameters:
  • question (str) – a string that will be shown to the user. Don’t add a space after the question mark/colon, this method will do this for you.
  • password (bool) – if True, hides the user’s input (for password entry).
  • default (basestring) – The default answer if none was entered. None to require an answer.
  • force (bool) – Automatically use the default
Return type:

str

pywikibot.input_choice(question, answers, default=None, return_shortcut=True, automatic_quit=True, force=False)[source]

Ask the user the question and return one of the valid answers.

Parameters:
  • question (basestring) – The question asked without trailing spaces.
  • answers (iterable containing a sequence of length two or instances of ChoiceException) – The valid answers each containing a full length answer and a shortcut. Each value must be unique.
  • default (basestring) – The result if no answer was entered. It must not be in the valid answers and can be disabled by setting it to None. If it should be linked with the valid answers it must be its shortcut.
  • return_shortcut (bool) – Whether the shortcut or the index of the answer is returned.
  • automatic_quit (bool) – Adds the option ‘Quit’ (‘q’) and throw a QuitKeyboardInterrupt if selected.
  • force (bool) – Automatically use the default
Returns:

The selected answer shortcut or index. Is -1 if the default is selected, it does not return the shortcut and the default is not a valid shortcut.

Return type:

int (if not return shortcut), basestring (otherwise)

pywikibot.input_yn(question, default=None, automatic_quit=True, force=False)[source]

Ask the user a yes/no question and return the answer as a bool.

Parameters:
  • question (basestring) – The question asked without trailing spaces.
  • default (basestring or bool) – The result if no answer was entered. It must be a bool or ‘y’ or ‘n’ and can be disabled by setting it to None.
  • automatic_quit (bool) – Adds the option ‘Quit’ (‘q’) and throw a QuitKeyboardInterrupt if selected.
  • force (bool) – Automatically use the default
Returns:

Return True if the user selected yes and False if the user selected no. If the default is not None it’ll return True if default is True or ‘y’ and False if default is False or ‘n’.

Return type:

bool

pywikibot.inputChoice(question, answers, hotkeys, default=None)[source]

Ask the user a question with several options, return the user’s choice.

DEPRECATED: Use input_choice instead!

The user’s input will be case-insensitive, so the hotkeys should be distinctive case-insensitively.

Parameters:
  • question (basestring) – a string that will be shown to the user. Don’t add a space after the question mark/colon, this method will do this for you.
  • answers (list of basestring) – a list of strings that represent the options.
  • hotkeys – a list of one-letter strings, one for each answer.
  • default – an element of hotkeys, or None. The default choice that will be returned when the user just presses Enter.
Returns:

a one-letter string in lowercase.

Return type:

str

exception pywikibot.InterwikiRedirectPage(page, target_page)[source]

Bases: pywikibot.exceptions.PageRelatedError

Page is a redirect to another site.

This is considered invalid in Pywikibot. See bug T75184.

__init__(page, target_page)[source]

Initializer.

Parameters:target_page – Target page of the redirect.
__module__ = 'pywikibot.exceptions'
message = 'Page redirects to a page on another Site.\nPage: %(page)s\nTarget page: %(target_page)s on %(target_site)s.'
exception pywikibot.InvalidTitle(arg)[source]

Bases: pywikibot.exceptions.Error

Invalid page title.

__module__ = 'pywikibot.exceptions'
exception pywikibot.IsNotRedirectPage(page, message=None)[source]

Bases: pywikibot.exceptions.PageRelatedError

Page is not a redirect page.

__module__ = 'pywikibot.exceptions'
message = 'Page %s is not a redirect page.'
exception pywikibot.IsRedirectPage(page, message=None)[source]

Bases: pywikibot.exceptions.PageRelatedError

Page is a redirect page.

__module__ = 'pywikibot.exceptions'
message = 'Page %s is a redirect page.'
class pywikibot.ItemPage(site, title=None, ns=None)[source]

Bases: pywikibot.page.WikibasePage

Wikibase entity of type ‘item’.

A Wikibase item may be defined by either a ‘Q’ id (qid), or by a site & title.

If an item is defined by site & title, once an item’s qid has been looked up, the item is then defined by the qid.

__init__(site, title=None, ns=None)[source]

Initializer.

Parameters:
  • site (pywikibot.site.DataSite) – data repository
  • title (str) – id number of item, “Q###”, -1 or None for an empty item.
__module__ = 'pywikibot.page'
concept_url(**kw)
entity_type = 'item'
classmethod fromPage(page, lazy_load=False)[source]

Get the ItemPage for a Page that links to it.

Parameters:
  • page (pywikibot.Page) – Page to look for corresponding data item
  • lazy_load (bool) – Do not raise NoPage if either page or corresponding ItemPage does not exist.
Return type:

ItemPage

Raises:
  • NoPage – There is no corresponding ItemPage for the page
  • WikiBaseError – The site of the page has no data repository.
classmethod from_entity_uri(site, uri, lazy_load=False)[source]

Get the ItemPage from its entity uri.

Parameters:
  • site (pywikibot.site.DataSite) – The Wikibase site for the item.
  • uri (basestring) – Entity uri for the Wikibase item.
  • lazy_load (bool) – Do not raise NoPage if ItemPage does not exist.
Return type:

ItemPage

Raises:
  • TypeError – Site is not a valid DataSite.
  • ValueError – Site does not match the base of the provided uri.
  • NoPage – Uri points to non-existent item.
get(force=False, get_redirect=False, *args, **kwargs)[source]

Fetch all item data, and cache it.

Parameters:
  • force (bool) – override caching
  • get_redirect (bool) – return the item content, do not follow the redirect, do not raise an exception.
Raises:

NotImplementedError – a value in args or kwargs

Returns:

actual data which entity holds

Return type:

dict

Note:

dicts returned by this method are references to content of this entity and their modifying may indirectly cause unwanted change to the live content

getID(numeric=False, force=False)[source]

Get the entity identifier.

Parameters:
  • numeric (bool) – Strip the first letter and return an int
  • force (bool) – Force an update of new data
getRedirectTarget()[source]

Return the redirect target for this page.

Return the title for the specific site.

If the item doesn’t have that language, raise NoPage.

Parameters:
  • site (pywikibot.Site or database name) – Site to find the linked page of.
  • force – override caching
Return type:

str

isRedirectPage()[source]

Return True if item is a redirect, False if not or not existing.

Iterate through all the sitelinks.

Parameters:family (str|pywikibot.family.Family) – string/Family object which represents what family of links to iterate
Returns:iterator of pywikibot.Page objects
Return type:iterator
mergeInto(item, **kwargs)[source]

Merge the item into another item.

Parameters:item (ItemPage) – The item to merge into

Remove a sitelink.

A site can either be a Site object, or it can be a dbName.

Remove sitelinks.

Sites should be a list, with values either being Site objects, or dbNames.

Set sitelinks. Calls setSitelinks().

A sitelink can either be a Page object, or a {‘site’:dbname,’title’:title} dictionary.

Set sitelinks.

Sitelinks should be a list. Each item in the list can either be a Page object, or a dict with a value for ‘site’ and ‘title’.

set_redirect_target(target_page, create=False, force=False, keep_section=False, save=True, **kwargs)[source]

Make the item redirect to another item.

You need to define an extra argument to make this work, like save=True

Parameters:
  • target_page (ItemPage or string) – target of the redirect, this argument is required.
  • force (bool) – if true, it sets the redirect target even the page is not redirect.
title(**kwargs)[source]

Return ID as title of the ItemPage.

If the ItemPage was lazy-loaded via ItemPage.fromPage, this method will fetch the wikibase item ID for the page, potentially raising NoPage with the page on the linked wiki if it does not exist, or does not have a corresponding wikibase item ID.

This method also refreshes the title if the id property was set. i.e. item.id = ‘Q60’

All optional keyword parameters are passed to the superclass.

title_pattern = 'Q[1-9]\\d*'
toJSON(diffto=None)[source]

Create JSON suitable for Wikibase API.

When diffto is provided, JSON representing differences to the provided data is created.

Parameters:diffto (dict) – JSON containing entity data
Return type:dict

Bases: pywikibot.page.BaseLink

A MediaWiki wikitext link (local or interwiki).

Constructs a Link object based on a wikitext link and a source site.

Extends BaseLink by the following attributes:

  • section: The section of the page linked to (unicode or None); this contains any text following a ‘#’ character in the title
  • anchor: The anchor text (unicode or None); this contains any text following a ‘|’ character inside the link
__init__(text, source=None, default_namespace=0, defaultNamespace='[deprecated name of default_namespace]')[source]

Initializer.

Parameters:
  • text (str) – the link text (everything appearing between [[ and ]] on a wiki page)
  • source (Site or BasePage) – the Site on which the link was found (not necessarily the site to which the link refers)
  • default_namespace (int) – a namespace to use if the link does not contain one (defaults to 0)
Raises:

UnicodeError – text could not be converted to unicode.

__module__ = 'pywikibot.page'
anchor

Return the anchor of the link.

Return type:str
astext(onsite=None)[source]

Return a text representation of the link.

Parameters:onsite – if specified, present as a (possibly interwiki) link from the given site; otherwise, present as an internal link on the source site.
classmethod create_separated(link, source, default_namespace=0, section=None, label=None)[source]

Create a new instance but overwrite section or label.

The returned Link instance is already parsed.

Parameters:
  • link (str) – The original link text.
  • source (Site) – The source of the link.
  • default_namespace (int) – The namespace this link uses when no namespace is defined in the link text.
  • section (None or str) – The new section replacing the one in link. If None (default) it doesn’t replace it.
  • label – The new label replacing the one in link. If None (default) it doesn’t replace it.
classmethod fromPage(page, source=None)[source]

Create a Link to a Page.

Parameters:
  • page (Page) – target Page
  • source – Link from site source
  • source – Site
Return type:

Link

illegal_titles_pattern = re.compile('[\\x00-\\x1f\\x23\\x3c\\x3e\\x5b\\x5d\\x7b\\x7c\\x7d\\x7f]|%[0-9A-Fa-f]{2}|&[A-Za-z0-9\x80-ÿ]+;|&#[0-9]+;|&#x[0-9A-Fa-f]+;')
classmethod langlinkUnsafe(lang, title, source)[source]

Create a “lang:title” Link linked from source.

Assumes that the lang & title come clean, no checks are made.

Parameters:
  • lang (str) – target site code (language)
  • title (str) – target Page
  • source – Link from site source
  • source – Site
Return type:

Link

namespace

Return the namespace of the link.

Return type:pywikibot.Namespace
parse()[source]

Parse wikitext of the link.

Called internally when accessing attributes.

parse_site()[source]

Parse only enough text to determine which site the link points to.

This method does not parse anything after the first “:”; links with multiple interwiki prefixes (such as “wikt:fr:Parlais”) need to be re-parsed on the first linked wiki to get the actual site.

Returns:The family name and site code for the linked site. If the site is not supported by the configured families it returns None instead of a str.
Return type:tuple
section

Return the section of the link.

Return type:str
site

Return the site of the link.

Return type:pywikibot.Site
title

Return the title of the link.

Return type:str
exception pywikibot.LockedNoPage(page, message=None)[source]

Bases: pywikibot.exceptions.LockedPage

Title is locked against creation.

__module__ = 'pywikibot.exceptions'
message = 'Page %s does not exist and is locked preventing creation.'
exception pywikibot.LockedPage(page, message=None)[source]

Bases: pywikibot.exceptions.PageSaveRelatedError

Page is locked.

__module__ = 'pywikibot.exceptions'
message = 'Page %s is locked.'
pywikibot.log(text, decoder=None, newline=True, **kwargs)[source]

Output a record to the log file.

exception pywikibot.NoCreateError(page, message=None)[source]

Bases: pywikibot.exceptions.PageSaveRelatedError

Parameter nocreate doesn’t allow page creation.

__module__ = 'pywikibot.exceptions'
message = 'Page %s could not be created due to parameter nocreate'
exception pywikibot.NoMoveTarget(page, message=None)[source]

Bases: pywikibot.exceptions.PageRelatedError

Expected move target page not found.

__module__ = 'pywikibot.exceptions'
message = 'Move target page of %s not found.'
exception pywikibot.NoPage(page, message=None)[source]

Bases: pywikibot.exceptions.PageRelatedError

Page does not exist.

__module__ = 'pywikibot.exceptions'
message = "Page %s doesn't exist."
pywikibot.NoSuchSite

alias of pywikibot.exceptions.SiteDefinitionError

exception pywikibot.NoUsername(arg)[source]

Bases: pywikibot.exceptions.Error

Username is not in user-config.py.

__module__ = 'pywikibot.exceptions'
exception pywikibot.OtherPageSaveError(page, reason)[source]

Bases: pywikibot.exceptions.PageSaveRelatedError

Saving the page has failed due to uncatchable error.

__init__(page, reason)[source]

Initializer.

Parameters:reason (Exception or basestring) – Details of the problem
__module__ = 'pywikibot.exceptions'
args

Expose args.

message = 'Edit to page %(title)s failed:\n%(reason)s'
pywikibot.output(text, decoder=None, newline=True, toStdout=False, **kwargs)[source]

Output a message to the user via the userinterface.

Works like print, but uses the encoding used by the user’s console (console_encoding in the configuration file) instead of ASCII.

If decoder is None, text should be a unicode string. Otherwise it should be encoded in the given encoding.

If newline is True, a line feed will be added after printing the text.

If toStdout is True, the text will be sent to standard output, so that it can be piped to another process. All other text will be sent to stderr. See: https://en.wikipedia.org/wiki/Pipeline_%28Unix%29

text can contain special sequences to create colored output. These consist of the escape character 03 and the color name in curly braces, e. g. 03{lightpurple}. 03{default} resets the color. By using the color_format method from pywikibot.tools.formatter, the escape character may be omitted.

Other keyword arguments are passed unchanged to the logger; so far, the only argument that is useful is “exc_info=True”, which causes the log message to include an exception traceback.

class pywikibot.Page(source, title='', ns=0, defaultNamespace='[deprecated name of ns]', insite=NotImplemented)[source]

Bases: pywikibot.page.BasePage

Page: A MediaWiki page.

__init__(source, title='', ns=0, defaultNamespace='[deprecated name of ns]', insite=NotImplemented)[source]

Instantiate a Page object.

__module__ = 'pywikibot.page'
raw_extracted_templates

Extract templates using textlib.extract_templates_and_params.

Disabled parts and whitespace are stripped, except for whitespace in anonymous positional arguments.

This value is cached.

Return type:list of (str, OrderedDict)
set_redirect_target(target_page, create=False, force=False, keep_section=False, save=True, **kwargs)[source]

Change the page’s text to point to the redirect page.

Parameters:
  • target_page (pywikibot.Page or string) – target of the redirect, this argument is required.
  • create (bool) – if true, it creates the redirect even if the page doesn’t exist.
  • force (bool) – if true, it set the redirect target even the page doesn’t exist or it’s not redirect.
  • keep_section (bool) – if the old redirect links to a section and the new one doesn’t it uses the old redirect’s section.
  • save (bool) – if true, it saves the page immediately.
  • kwargs – Arguments which are used for saving the page directly afterwards, like ‘summary’ for edit summary.
templatesWithParams(get_redirect=NotImplemented)[source]

Return templates used on this Page.

The templates are extracted by textlib.extract_templates_and_params, with positional arguments placed first in order, and each named argument appearing as ‘name=value’.

All parameter keys and values for each template are stripped of whitespace.

Returns:a list of tuples with one tuple for each template invocation in the page, with the template Page as the first entry and a list of parameters as the second entry.
Return type:list of (Page, list)
exception pywikibot.PageCreatedConflict(page, message=None)[source]

Bases: pywikibot.exceptions.EditConflict

Page was created by another user.

__module__ = 'pywikibot.exceptions'
message = 'Page %s has been created since last retrieved.'
exception pywikibot.PageDeletedConflict(page, message=None)[source]

Bases: pywikibot.exceptions.EditConflict

Page was deleted since being retrieved.

__module__ = 'pywikibot.exceptions'
message = 'Page %s has been deleted since last retrieved.'
pywikibot.PageNotSaved

alias of pywikibot.exceptions.PageSaveRelatedError

exception pywikibot.PageRelatedError(page, message=None)[source]

Bases: pywikibot.exceptions.Error

Abstract Exception, used when the exception concerns a particular Page.

This class should be used when the Exception concerns a particular Page, and when a generic message can be written once for all.

__init__(page, message=None)[source]

Initializer.

Parameters:page (Page object) – Page that caused the exception
__module__ = 'pywikibot.exceptions'
getPage()[source]

Return the page related to the exception.

message = None
exception pywikibot.PageSaveRelatedError(page, message=None)[source]

Bases: pywikibot.exceptions.PageRelatedError

Saving the page has failed.

__module__ = 'pywikibot.exceptions'
args

Expose args.

message = 'Page %s was not saved.'
class pywikibot.PropertyPage(source, title=None, datatype=None)[source]

Bases: pywikibot.page.WikibasePage, pywikibot.page.Property

A Wikibase entity in the property namespace.

Should be created as:

PropertyPage(DataSite, 'P21')

or:

PropertyPage(DataSite, datatype='url')
__init__(source, title=None, datatype=None)[source]

Initializer.

Parameters:
  • source (pywikibot.site.DataSite) – data repository property is on
  • title (str) – page name of property, like “P##”, “-1” or None for an empty property.
  • datatype (str) – Datatype for a new property.
__module__ = 'pywikibot.page'
entity_type = 'property'
get(force=False, *args, **kwargs)[source]

Fetch the property entity, and cache it.

Parameters:force (bool) – override caching
Raises:NotImplementedError – a value in args or kwargs
Returns:actual data which entity holds
Return type:dict
Note:dicts returned by this method are references to content of this entity and their modifying may indirectly cause unwanted change to the live content
getID(numeric=False)[source]

Get the identifier of this property.

Parameters:numeric (bool) – Strip the first letter and return an int
get_data_for_new_entity()[source]

Return data required for creation of new property.

newClaim(*args, **kwargs)[source]

Helper function to create a new claim object for this property.

Return type:Claim
title_pattern = 'P[1-9]\\d*'
exception pywikibot.QuitKeyboardInterrupt[source]

Bases: pywikibot.bot_choice.ChoiceException, KeyboardInterrupt

The user has cancelled processing at a prompt.

__init__()[source]

Constructor using the ‘quit’ (‘q’) in input_choice.

__module__ = 'pywikibot.bot_choice'
exception pywikibot.SectionError(arg)[source]

Bases: pywikibot.exceptions.Error

The section specified by # does not exist.

__module__ = 'pywikibot.exceptions'
exception pywikibot.Server504Error(arg)[source]

Bases: pywikibot.exceptions.ServerError

Server timed out with HTTP 504 code.

__module__ = 'pywikibot.exceptions'
exception pywikibot.ServerError(arg)[source]

Bases: pywikibot.exceptions.Error

Got unexpected server response.

__module__ = 'pywikibot.exceptions'
pywikibot.showHelp(module_name=None)[source]

Show help for the Bot.

pywikibot.Site(code=None, fam=None, user=None, sysop=None, interface=None, url=None)[source]

A factory method to obtain a Site object.

Site objects are cached and reused by this method.

By default rely on config settings. These defaults may all be overridden using the method parameters.

Parameters:
  • code (str) – language code (override config.mylang)
  • fam (str or Family) – family name or object (override config.family)
  • user (str) – bot user name to use on this site (override config.usernames)
  • sysop (str) – sysop user to use on this site (override config.sysopnames)
  • interface (subclass of pywikibot.site.BaseSite or string) – site class or name of class in pywikibot.site (override config.site_interface)
  • url (str) – Instead of code and fam, does try to get a Site based on the URL. Still requires that the family supporting that URL exists.
Return type:

pywikibot.site.APISite

Raises:
  • ValueError – URL and pair of code and family given
  • ValueError – Invalid interface name
  • SiteDefinitionError – Unknown URL
exception pywikibot.SiteDefinitionError(arg)[source]

Bases: pywikibot.exceptions.Error

Site does not exist.

__module__ = 'pywikibot.exceptions'

Bases: pywikibot.page.BaseLink

A single sitelink in a Wikibase item.

Extends BaseLink by the following attribute:

  • badges: Any badges associated with the sitelink
__init__(title, site=None, badges=None)[source]

Initializer.

Parameters:
  • title (str) – the title of the linked page including namespace
  • site (pywikibot.Site or str) – the Site object for the wiki linked to. Can be provided as either a Site instance or a db key, defaults to pywikibot.Site().
  • badges ([pywikibot.ItemPage]) – list of badges
__module__ = 'pywikibot.page'
badges

Return a list of all badges associated with the link.

Return type:[pywikibot.ItemPage]
classmethod fromJSON(data, site=None)[source]

Create a SiteLink object from JSON returned in the API call.

Parameters:
Return type:

SiteLink

toJSON()[source]

Convert the SiteLink to a JSON object for the Wikibase API.

Returns:Wikibase JSON
Return type:dict
exception pywikibot.SpamfilterError(page, url)[source]

Bases: pywikibot.exceptions.PageSaveRelatedError

Page save failed because MediaWiki detected a blacklisted spam URL.

__init__(page, url)[source]

Initializer.

__module__ = 'pywikibot.exceptions'
message = 'Edit to page %(title)s rejected by spam filter due to content:\n%(url)s'
pywikibot.stdout(text, decoder=None, newline=True, **kwargs)[source]

Output script results to the user via the userinterface.

exception pywikibot.TitleblacklistError(page, message=None)[source]

Bases: pywikibot.exceptions.PageSaveRelatedError

Page save failed because MediaWiki detected a blacklisted page title.

__module__ = 'pywikibot.exceptions'
message = 'Page %s is title-blacklisted.'
pywikibot.translate(code, xdict, parameters=None, fallback=False)[source]

Return the most appropriate translation from a translation dict.

Given a language code and a dictionary, returns the dictionary’s value for key ‘code’ if this key exists; otherwise tries to return a value for an alternative language that is most applicable to use on the wiki in language ‘code’ except fallback is False.

The language itself is always checked first, then languages that have been defined to be alternatives, and finally English. If none of the options gives result, we just take the one language from xdict which may not be always the same. When fallback is iterable it’ll return None if no code applies (instead of returning one).

For PLURAL support have a look at the twtranslate method.

Parameters:
  • code (str or Site object) – The language code
  • xdict (dict, string, unicode) – dictionary with language codes as keys or extended dictionary with family names as keys containing language dictionaries or a single (unicode) string. May contain PLURAL tags as described in twtranslate
  • parameters (dict, string, unicode, int) – For passing (plural) parameters
  • fallback (boolean or iterable) – Try an alternate language code. If it’s iterable it’ll also try those entries and choose the first match.
Raises:

IndexError – If the language supports and requires more plurals than defined for the given translation template.

pywikibot.unicode2html(x, encoding)[source]

Convert unicode string to requested HTML encoding.

Attempt to encode the string into the desired format; if that doesn’t work, encode the unicode into HTML &#; entities. If it does work, return it unchanged.

Parameters:
  • x (str) – String to update
  • encoding (str) – Encoding to use
Return type:

str

class pywikibot.UnicodeMixin[source]

Bases: object

Mixin class to add __str__ method in Python 2 or 3.

__module__ = 'pywikibot.tools'
__str__()[source]

Return the unicode representation as the str representation.

exception pywikibot.UnknownExtension(arg)[source]

Bases: pywikibot.exceptions.Error, NotImplementedError

Extension is not defined.

__module__ = 'pywikibot.exceptions'
exception pywikibot.UnknownFamily(arg)[source]

Bases: pywikibot.exceptions.SiteDefinitionError

Family is not registered.

__module__ = 'pywikibot.exceptions'
exception pywikibot.UnknownSite(arg)[source]

Bases: pywikibot.exceptions.SiteDefinitionError

Site does not exist in Family.

__module__ = 'pywikibot.exceptions'
exception pywikibot.UnsupportedPage(page, message=None)[source]

Bases: pywikibot.exceptions.PageRelatedError

Unsupported page due to namespace restriction.

__module__ = 'pywikibot.exceptions'
message = 'Page %s is not supported due to namespace restriction.'
exception pywikibot.UploadWarning(code, message, file_key=None, offset=0)[source]

Bases: pywikibot.data.api.APIError

Upload failed with a warning message (passed as the argument).

__init__(code, message, file_key=None, offset=0)[source]

Create a new UploadWarning instance.

Parameters:
  • filekey (str or None) – The filekey of the uploaded file to reuse it later. If no key is known or it is an incomplete file it may be None.
  • offset (int or bool) – The starting offset for a chunked upload. Is False when there is no offset.
__module__ = 'pywikibot.data.api'
message

Return warning message.

pywikibot.url2unicode(title, encodings='utf-8', site2=NotImplemented, site='[deprecated name of encodings]')[source]

Convert URL-encoded text to unicode using several encoding.

Uses the first encoding that doesn’t cause an error.

Parameters:
  • title (str) – URL-encoded character data to convert
  • encodings (str, list or Site) – Encodings to attempt to use during conversion.
Return type:

str

Raises:

UnicodeError – Could not convert using any encoding.

class pywikibot.User(source, title='', name='[deprecated name of title]', site='[deprecated name of source]')[source]

Bases: pywikibot.page.Page

A class that represents a Wiki user.

This class also represents the Wiki page User:<username>

__init__(source, title='', name='[deprecated name of title]', site='[deprecated name of source]')[source]

Initializer for a User object.

All parameters are the same as for Page() Initializer.

__module__ = 'pywikibot.page'
block(*args, **kwargs)[source]

Block user.

Refer APISite.blockuser method for parameters.

Returns:None
contributions(total=500, **kwargs, namespace='[deprecated name of namespaces]', limit='[deprecated name of total]')[source]

Yield tuples describing this user edits.

Each tuple is composed of a pywikibot.Page object, the revision id (int), the edit timestamp (as a pywikibot.Timestamp object), and the comment (unicode). Pages returned are not guaranteed to be unique.

Parameters:

total (int) – limit result to this number of pages

Keyword Arguments:
 
  • start – Iterate contributions starting at this Timestamp
  • end – Iterate contributions ending at this Timestamp
  • reverse – Iterate oldest contributions first (default: newest)
  • namespaces – only iterate pages in these namespaces
  • showMinor – if True, iterate only minor edits; if False and not None, iterate only non-minor edits (default: iterate both)
  • top_only – if True, iterate only edits which are the latest revision (default: False)
Returns:

tuple of pywikibot.Page, revid, pywikibot.Timestamp, comment

Return type:

tuple

editCount(force=False)[source]

Return edit count for a registered user.

Always returns 0 for ‘anonymous’ users.

Parameters:force (bool) – if True, forces reloading the data from API
Return type:int
editedPages(total=500, limit='[deprecated name of total]')[source]

DEPRECATED. Use contributions().

Yields pywikibot.Page objects that this user has edited, with an upper bound of ‘total’. Pages returned are not guaranteed to be unique.

Parameters:total (int.) – limit result to this number of pages.
first_edit

Return first user contribution.

Returns:first user contribution entry
Returns:tuple of pywikibot.Page, revid, pywikibot.Timestamp, comment
Return type:tuple or None
gender(force=False)[source]

Return the gender of the user.

Parameters:force (bool) – if True, forces reloading the data from API
Returns:return ‘male’, ‘female’, or ‘unknown’
Return type:str
getUserPage(subpage='')[source]

Return a Page object relative to this user’s main page.

Parameters:subpage (str) – subpage part to be appended to the main page title (optional)
Returns:Page object of user page or user subpage
Return type:pywikibot.Page
getUserTalkPage(subpage='')[source]

Return a Page object relative to this user’s main talk page.

Parameters:subpage (str) – subpage part to be appended to the main talk page title (optional)
Returns:Page object of user talk page or user talk subpage
Return type:pywikibot.Page
getprops(force=False)[source]

Return a properties about the user.

Parameters:force (bool) – if True, forces reloading the data from API
Return type:dict
groups(force=False)[source]

Return a list of groups to which this user belongs.

The list of groups may be empty.

Parameters:force (bool) – if True, forces reloading the data from API
Returns:groups property
Return type:list
isAnonymous()[source]

Determine if the user is editing as an IP address.

Return type:bool
isBlocked(force=False)[source]

Determine whether the user is currently blocked.

Parameters:force (bool) – if True, forces reloading the data from API
Return type:bool
isEmailable(force=False)[source]

Determine whether emails may be send to this user through MediaWiki.

Parameters:force (bool) – if True, forces reloading the data from API
Return type:bool
isRegistered(force=False)[source]

Determine if the user is registered on the site.

It is possible to have a page named User:xyz and not have a corresponding user with username xyz.

The page does not need to exist for this method to return True.

Parameters:force (bool) – if True, forces reloading the data from API
Return type:bool
is_thankable

Determine if the user has thanks notifications enabled.

NOTE: This doesn’t accurately determine if thanks is enabled for user.
Privacy of thanks preferences is under discussion, please see https://phabricator.wikimedia.org/T57401#2216861, and https://phabricator.wikimedia.org/T120753#1863894
Return type:bool
last_edit

Return last user contribution.

Returns:last user contribution entry
Returns:tuple of pywikibot.Page, revid, pywikibot.Timestamp, comment
Return type:tuple or None
last_event

Return last user activity.

Returns:last user log entry
Return type:LogEntry or None
logevents(**kwargs)[source]

Yield user activities.

Keyword Arguments:
 
  • logtype – only iterate entries of this type (see mediawiki api documentation for available types)
  • page – only iterate entries affecting this page
  • namespace – namespace to retrieve logevents from
  • start – only iterate entries from and after this Timestamp
  • end – only iterate entries up to and through this Timestamp
  • reverse – if True, iterate oldest entries first (default: newest)
  • tag – only iterate entries tagged with this tag
  • total – maximum number of events to iterate
Return type:

iterable

name()[source]

The username.

DEPRECATED: use username instead.

Return type:str
registration(force=False)[source]

Fetch registration date for this user.

Parameters:force (bool) – if True, forces reloading the data from API
Return type:pywikibot.Timestamp or None
registrationTime(force=False)[source]

DEPRECATED. Fetch registration date for this user.

Parameters:force (bool) – if True, forces reloading the data from API
Returns:int (MediaWiki’s internal timestamp format) or 0
Return type:int
rights(force=False)[source]

Return user rights.

Parameters:force (bool) – if True, forces reloading the data from API
Returns:return user rights
Return type:list
send_email(subject, text, ccme=False)[source]

Send an email to this user via MediaWiki’s email interface.

Parameters:
  • subject (str) – the subject header of the mail
  • text (str) – mail body
  • ccme (bool) – if True, sends a copy of this email to the bot
Raises:
Returns:

operation successful indicator

Return type:

bool

unblock(reason=None)[source]

Remove the block for the user.

Parameters:reason (basestring) – Reason for the unblock.
uploadedImages(total=10, number='[deprecated name of total]')[source]

Yield tuples describing files uploaded by this user.

Each tuple is composed of a pywikibot.Page, the timestamp (str in ISO8601 format), comment (unicode) and a bool for pageid > 0. Pages returned are not guaranteed to be unique.

Parameters:total (int) – limit result to this number of pages
username

The username.

Convenience method that returns the title of the page with namespace prefix omitted, which is the username.

Return type:str
exception pywikibot.UserBlocked(arg)[source]

Bases: pywikibot.exceptions.Error

Your username or IP has been blocked.

__module__ = 'pywikibot.exceptions'
pywikibot.warning(text, decoder=None, newline=True, **kwargs)[source]

Output a warning message to the user via the userinterface.

Parameters:
  • text (str) – the message the user wants to display.
  • decoder (str) – If None, text should be a unicode string. Otherwise it should be encoded in the given encoding.
  • newline (bool) – If True, a line feed will be added after printing the text.
  • kwargs – The keyword arguments can be found in the python doc: https://docs.python.org/3/howto/logging-cookbook.html.
exception pywikibot.WikiBaseError(arg)[source]

Bases: pywikibot.exceptions.Error

Wikibase related error.

__module__ = 'pywikibot.exceptions'
class pywikibot.WikidataBot(**kwargs, use_from_page=NotImplemented)[source]

Bases: pywikibot.bot.Bot, pywikibot.bot.ExistingPageBot

Generic Wikidata Bot to be subclassed.

Source claims (P143) can be created for specific sites

@cvar use_from_page: If True (default) it will apply ItemPage.fromPage
for every item. If False it assumes that the pages are actually already ItemPage (page in treat_page_and_item will be None). If None it’ll use ItemPage.fromPage when the page is not in the site’s item namespace.
@cvar treat_missing_item: Whether pages without items should be treated.
Note that this is checked after create_missing_item.
@ivar create_missing_item: If True, new items will be created if the
current page doesn’t have one. Subclasses should override this in the initializer with a bool value or using self.getOption.
__init__(**kwargs, use_from_page=NotImplemented)[source]

Initializer of the WikidataBot.

__module__ = 'pywikibot.bot'
cacheSources()[source]

Fetch the sources from the list on Wikidata.

It is stored internally and reused by getSource()

create_item_for_page(page, data=None, summary=None, **kwargs)[source]

Create an ItemPage with the provided page as the sitelink.

Parameters:
  • page (pywikibot.Page) – the page for which the item will be created
  • data (dict) – additional data to be included in the new item (optional). Note that data created from the page have higher priority.
  • summary (str) – optional edit summary to replace the default one
Returns:

pywikibot.ItemPage or None

getSource(site)[source]

Create a Claim usable as a source for Wikibase statements.

Parameters:site (Site) – site that is the source of assertions.
Returns:pywikibot.Claim or None
get_property_by_name(property_name)[source]

Find given property and return its ID.

Method first uses site.search() and if the property isn’t found, then asks user to provide the property ID.

Parameters:property_name (str) – property to find
treat_missing_item = False
treat_page()[source]

Treat a page.

treat_page_and_item(page, item)[source]

Treat page together with its item (if it exists).

Must be implemented in subclasses.

use_from_page = True
user_add_claim(item, claim, source=None, bot=True, **kwargs)[source]

Add a claim to an item, with user confirmation as required.

Parameters:
Keyword Arguments:
 
  • ignore_server_errors – if True, server errors will be reported and ignored (default: False)
  • ignore_save_related_errors – if True, errors related to page save will be reported and ignored (default: False)
Returns:

whether the item was saved successfully

Return type:

bool

user_add_claim_unless_exists(item, claim, exists_arg='', source=None, logger_callback=<function log>, **kwargs)[source]

Decorator of user_add_claim.

Before adding a new claim, it checks if we can add it, using provided filters.

See:

documentation of claimit.py

Parameters:
  • exists_arg (str) – pattern for merging existing claims with new ones
  • logger_callback (callable) – function logging the output of the method
Returns:

whether the claim could be added

Return type:

bool

user_edit_entity(item, data=None, ignore_save_related_errors=None, ignore_server_errors=None, **kwargs)[source]

Edit entity with data provided, with user confirmation as required.

Parameters:
  • item (ItemPage) – page to be edited
  • data – data to be saved, or None if the diff should be created automatically
  • ignore_save_related_errors (bool or None) – Ignore save related errors and automatically print a message. If None uses this instances default.
  • ignore_server_errors (bool or None) – Ignore server errors and automatically print a message. If None uses this instances default.
Keyword Arguments:
 
  • summary – revision comment, passed to ItemPage.editEntity
  • show_diff – show changes between oldtext and newtext (default: True)
Returns:

whether the item was saved successfully

Return type:

bool

pywikibot.categoryFormat(*a, **kw)
pywikibot.compileLinkR(*a, **kw)
pywikibot.extract_templates_and_params(*a, **kw)
pywikibot.interwikiFormat(*a, **kw)
pywikibot.interwikiSort(*a, **kw)
pywikibot.isDisabled(*a, **kw)
pywikibot.removeCategoryLinksAndSeparator(*a, **kw)
pywikibot.removeDisabledParts(*a, **kw)
pywikibot.removeHTMLParts(*a, **kw)
pywikibot.removeLanguageLinksAndSeparator(*a, **kw)
pywikibot.replaceCategoryInPlace(*a, **kw)
pywikibot.replaceExcept(*a, **kw)
pywikibot.TimeStripper(*a, **kw)
pywikibot.unescape(*a, **kw)

Subpackages

Submodules

pywikibot.bot module

User-interface related functions for building bots.

This module supports several different bot classes which could be used in conjunction. Each bot should subclass at least one of these four classes:

  • BaseBot: Basic bot class in case where the site is handled differently, like working on two sites in parallel.
  • SingleSiteBot: Bot class which should only be run on a single site. They usually store site specific content and thus can’t be easily run when the generator returns a page on another site. It has a property site which can also be changed. If the generator returns a page of a different site it’ll skip that page.
  • MultipleSitesBot: Bot class which supports to be run on multiple sites without the need to manually initialize it every time. It is not possible to set the site property and it’s deprecated to request it. Instead site of the current page should be used. And out of run that sit isn’t defined.
  • ConfigParserBot: Bot class which supports reading options from a scripts.ini configuration file. That file consists of sections, led by a [section] header and followed by option: value or option=value entries. The section is the script name without .py suffix. All options identified must be predefined in availableOptions dictionary.
  • Bot: The previous base class which should be avoided. This class is mainly used for bots which work with wikibase or together with an image repository.

Additionally there is the CurrentPageBot class which automatically sets the current page to the page treated. It is recommended to use this class and to use treat_page instead of treat and put_current instead of userPut. It by default subclasses the BaseBot class.

With CurrentPageBot it’s possible to subclass one of the following classes to filter the pages which are ultimately handled by treat_page:

It is possible to combine filters by subclassing multiple of them. They are new-style classes so when a class is first subclassing ExistingPageBot and then FollowRedirectPageBot it will also work on pages which do not exist when a redirect pointed to that. If the order is inversed it’ll first follow them and then check whether they exist.

Additionally there is the AutomaticTWSummaryBot which subclasses CurrentPageBot and automatically defines the summary when put_current is used.

pywikibot.bot.critical(text, decoder=None, newline=True, **kwargs)[source]

Output a critical record to the user via the userinterface.

pywikibot.bot.debug(text, layer, decoder=None, newline=True, **kwargs)[source]

Output a debug record to the log file.

Parameters:layer – The name of the logger that text will be sent to.
pywikibot.bot.error(text, decoder=None, newline=True, **kwargs)[source]

Output an error message to the user via the userinterface.

pywikibot.bot.exception(msg=None, decoder=None, newline=True, tb=False, **kwargs)[source]

Output an error traceback to the user via the userinterface.

Use directly after an ‘except’ statement:

...
except Exception:
    pywikibot.exception()
...

or alternatively:

...
except Exception as e:
    pywikibot.exception(e)
...
Parameters:tb – Set to True in order to output traceback also.
pywikibot.bot.log(text, decoder=None, newline=True, **kwargs)[source]

Output a record to the log file.

pywikibot.bot.warning(text, decoder=None, newline=True, **kwargs)[source]

Output a warning message to the user via the userinterface.

Parameters:
  • text (str) – the message the user wants to display.
  • decoder (str) – If None, text should be a unicode string. Otherwise it should be encoded in the given encoding.
  • newline (bool) – If True, a line feed will be added after printing the text.
  • kwargs – The keyword arguments can be found in the python doc: https://docs.python.org/3/howto/logging-cookbook.html.
pywikibot.bot.output(text, decoder=None, newline=True, toStdout=False, **kwargs)[source]

Output a message to the user via the userinterface.

Works like print, but uses the encoding used by the user’s console (console_encoding in the configuration file) instead of ASCII.

If decoder is None, text should be a unicode string. Otherwise it should be encoded in the given encoding.

If newline is True, a line feed will be added after printing the text.

If toStdout is True, the text will be sent to standard output, so that it can be piped to another process. All other text will be sent to stderr. See: https://en.wikipedia.org/wiki/Pipeline_%28Unix%29

text can contain special sequences to create colored output. These consist of the escape character 03 and the color name in curly braces, e. g. 03{lightpurple}. 03{default} resets the color. By using the color_format method from pywikibot.tools.formatter, the escape character may be omitted.

Other keyword arguments are passed unchanged to the logger; so far, the only argument that is useful is “exc_info=True”, which causes the log message to include an exception traceback.

pywikibot.bot.stdout(text, decoder=None, newline=True, **kwargs)[source]

Output script results to the user via the userinterface.

class pywikibot.bot.LoggingFormatter(fmt=None, datefmt=None)[source]

Bases: pywikibot.tools._logging.LoggingFormatter

Logging formatter that uses config.console_encoding.

__init__(fmt=None, datefmt=None)[source]

Initializer setting underlying encoding to console_encoding.

__module__ = 'pywikibot.bot'
class pywikibot.bot.RotatingFileHandler(filename, mode='a', maxBytes=0, backupCount=0, encoding=None, delay=False)[source]

Bases: logging.handlers.RotatingFileHandler

Modified RotatingFileHandler supporting unlimited amount of backups.

__module__ = 'pywikibot.tools._logging'
doRollover()[source]

Modified naming system for logging files.

Overwrites the default Rollover renaming by inserting the count number between file name root and extension. If backupCount is >= 1, the system will successively create new files with the same pathname as the base file, but with inserting “.1”, “.2” etc. in front of the filename suffix. For example, with a backupCount of 5 and a base file name of “app.log”, you would get “app.log”, “app.1.log”, “app.2.log”, … through to “app.5.log”. The file being written to is always “app.log” - when it gets filled up, it is closed and renamed to “app.1.log”, and if files “app.1.log”, “app.2.log” etc. already exist, then they are renamed to “app.2.log”, “app.3.log” etc. respectively. If backupCount is == -1 do not rotate but create new numbered filenames. The newest file has the highest number except some older numbered files where deleted and the bot was restarted. In this case the ordering starts from the lowest available (unused) number.

format(record)[source]

Strip trailing newlines before outputting text to file.

pywikibot.bot.init_handlers(strm=None)[source]

Initialize logging system for terminal-based bots.

This function must be called before using pywikibot.output(); and must be called again if the destination stream is changed.

Note: this function is called by handle_args(), so it should normally not need to be called explicitly

All user output is routed through the logging module. Each type of output is handled by an appropriate handler object. This structure is used to permit eventual development of other user interfaces (GUIs) without modifying the core bot code.

The following output levels are defined:

  • DEBUG: only for file logging; debugging messages.
  • STDOUT: output that must be sent to sys.stdout (for bots that may have their output redirected to a file or other destination).
  • VERBOSE: optional progress information for display to user.
  • INFO: normal (non-optional) progress information for display to user.
  • INPUT: prompts requiring user response.
  • WARN: user warning messages.
  • ERROR: user error messages.
  • CRITICAL: fatal error messages.

Accordingly, do not use print statements in bot code; instead, use pywikibot.output function.

Parameters:strm – Output stream. If None, re-uses the last stream if one was defined, otherwise uses sys.stderr
pywikibot.bot.writelogheader()[source]

Save additional version, system and status info to the log file in use.

This may help the user to track errors or report bugs.

pywikibot.bot.input(question, password=False, default='', force=False)[source]

Ask the user a question, return the user’s answer.

Parameters:
  • question (str) – a string that will be shown to the user. Don’t add a space after the question mark/colon, this method will do this for you.
  • password (bool) – if True, hides the user’s input (for password entry).
  • default (basestring) – The default answer if none was entered. None to require an answer.
  • force (bool) – Automatically use the default
Return type:

str

pywikibot.bot.input_choice(question, answers, default=None, return_shortcut=True, automatic_quit=True, force=False)[source]

Ask the user the question and return one of the valid answers.

Parameters:
  • question (basestring) – The question asked without trailing spaces.
  • answers (iterable containing a sequence of length two or instances of ChoiceException) – The valid answers each containing a full length answer and a shortcut. Each value must be unique.
  • default (basestring) – The result if no answer was entered. It must not be in the valid answers and can be disabled by setting it to None. If it should be linked with the valid answers it must be its shortcut.
  • return_shortcut (bool) – Whether the shortcut or the index of the answer is returned.
  • automatic_quit (bool) – Adds the option ‘Quit’ (‘q’) and throw a QuitKeyboardInterrupt if selected.
  • force (bool) – Automatically use the default
Returns:

The selected answer shortcut or index. Is -1 if the default is selected, it does not return the shortcut and the default is not a valid shortcut.

Return type:

int (if not return shortcut), basestring (otherwise)

pywikibot.bot.input_yn(question, default=None, automatic_quit=True, force=False)[source]

Ask the user a yes/no question and return the answer as a bool.

Parameters:
  • question (basestring) – The question asked without trailing spaces.
  • default (basestring or bool) – The result if no answer was entered. It must be a bool or ‘y’ or ‘n’ and can be disabled by setting it to None.
  • automatic_quit (bool) – Adds the option ‘Quit’ (‘q’) and throw a QuitKeyboardInterrupt if selected.
  • force (bool) – Automatically use the default
Returns:

Return True if the user selected yes and False if the user selected no. If the default is not None it’ll return True if default is True or ‘y’ and False if default is False or ‘n’.

Return type:

bool

pywikibot.bot.inputChoice(question, answers, hotkeys, default=None)[source]

Ask the user a question with several options, return the user’s choice.

DEPRECATED: Use input_choice instead!

The user’s input will be case-insensitive, so the hotkeys should be distinctive case-insensitively.

Parameters:
  • question (basestring) – a string that will be shown to the user. Don’t add a space after the question mark/colon, this method will do this for you.
  • answers (list of basestring) – a list of strings that represent the options.
  • hotkeys – a list of one-letter strings, one for each answer.
  • default – an element of hotkeys, or None. The default choice that will be returned when the user just presses Enter.
Returns:

a one-letter string in lowercase.

Return type:

str

pywikibot.bot.input_list_choice(question, answers, default=None, force=False)[source]

Ask the user the question and return one of the valid answers.

Parameters:
  • question (basestring) – The question asked without trailing spaces.
  • answers (Iterable of basestring) – The valid answers each containing a full length answer.
  • default (basestring) – The result if no answer was entered. It must not be in the valid answers and can be disabled by setting it to None.
  • force (bool) – Automatically use the default
Returns:

The selected answer.

Return type:

basestring

class pywikibot.bot.Option(stop=True)[source]

Bases: object

A basic option for input_choice.

The following methods need to be implemented: * format(default=None) * result(value) * test(value)

The methods test and handled are in such a relationship that when handled returns itself that test must return True for that value. So if test returns False handled may not return itself but it may return not None.

Also result only returns a sensible value when test returns True for the same value.

__init__(stop=True)[source]

Initializer.

__module__ = 'pywikibot.bot_choice'
format(default=None)[source]

Return a formatted string for that option.

static formatted(text, options, default=None)[source]

Create a text with the options formatted into it.

Parameters:
  • text (str) – Text into which options are to be formatted
  • options (Iterable) – Option instances to be formatted
Returns:

Text with the options formatted into it

Return type:

str

handled(value)[source]

Return the Option object that applies to the given value.

If this Option object doesn’t know which applies it returns None.

result(value)[source]

Return the actual value which is associated by the given one.

stop

Return whether this option stops asking.

test(value)[source]

Return True whether this option applies.

class pywikibot.bot.StandardOption(option, shortcut, **kwargs)[source]

Bases: pywikibot.bot_choice.Option

An option with a description and shortcut and returning the shortcut.

__init__(option, shortcut, **kwargs)[source]

Initializer.

Parameters:
  • option (str) – option string
  • shortcut (str) – Shortcut of the option
__module__ = 'pywikibot.bot_choice'
format(default=None)[source]

Return a formatted string for that option.

result(value)[source]

Return the lowercased shortcut.

test(value)[source]

Return True whether this option applies.

class pywikibot.bot.NestedOption(option, shortcut, description, options)[source]

Bases: pywikibot.bot_choice.OutputOption, pywikibot.bot_choice.StandardOption

An option containing other options.

It will return True in test if this option applies but False if a sub option applies while handle returns the sub option.

__init__(option, shortcut, description, options)[source]

Initializer.

__module__ = 'pywikibot.bot_choice'
format(default=None)[source]

Return a formatted string for that option.

handled(value)[source]

Return itself if it applies or the applying sub option.

output()[source]

Output the suboptions.

class pywikibot.bot.IntegerOption(minimum=1, maximum=None, prefix='', **kwargs)[source]

Bases: pywikibot.bot_choice.Option

An option allowing a range of integers.

__init__(minimum=1, maximum=None, prefix='', **kwargs)[source]

Initializer.

__module__ = 'pywikibot.bot_choice'
format(default=None)[source]

Return a formatted string showing the range.

maximum

Return the upper bound of the range of allowed values.

minimum

Return the lower bound of the range of allowed values.

parse(value)[source]

Return integer from value with prefix removed.

result(value)[source]

Return the value converted into int.

test(value)[source]

Return whether the value is an int and in the specified range.

class pywikibot.bot.ContextOption(option, shortcut, text, context, delta=100, start=0, end=0)[source]

Bases: pywikibot.bot_choice.OutputOption, pywikibot.bot_choice.StandardOption

An option to show more and more context.

__init__(option, shortcut, text, context, delta=100, start=0, end=0)[source]

Initializer.

__module__ = 'pywikibot.bot_choice'
output()[source]

Output the context.

output_range(start_context, end_context)[source]

Output a section from the text.

result(value)[source]

Add the delta to the context and output it.

class pywikibot.bot.ListOption(sequence, prefix='', **kwargs)[source]

Bases: pywikibot.bot_choice.IntegerOption

An option to select something from a list.

__init__(sequence, prefix='', **kwargs)[source]

Initializer.

__module__ = 'pywikibot.bot_choice'
format(default=None)[source]

Return a string showing the range.

maximum

Return the maximum value.

result(value)[source]

Return a tuple with the prefix and selected value.

class pywikibot.bot.ShowingListOption(sequence, prefix='', pre=None, post=None, **kwargs)[source]

Bases: pywikibot.bot_choice.ListOption, pywikibot.bot_choice.OutputOption

An option to show a list and select an item.

__init__(sequence, prefix='', pre=None, post=None, **kwargs)[source]

Initializer.

Parameters:
  • pre (str) – Additional comment printed before the list.
  • post (str) – Additional comment printed after the list.
__module__ = 'pywikibot.bot_choice'
before_question = True
output()[source]

Output the enumerated list.

stop

Return whether this option stops asking.

class pywikibot.bot.MultipleChoiceList(sequence, prefix='', **kwargs)[source]

Bases: pywikibot.bot_choice.ListOption

An option to select multiple items from a list.

__module__ = 'pywikibot.bot_choice'
result(value)[source]

Return a tuple with the prefix and selected values as a list.

test(value)[source]

Return whether the values are int and in the specified range.

class pywikibot.bot.ShowingMultipleChoiceList(sequence, prefix='', pre=None, post=None, **kwargs)[source]

Bases: pywikibot.bot_choice.ShowingListOption, pywikibot.bot_choice.MultipleChoiceList

An option to show a list and select multiple items.

__module__ = 'pywikibot.bot_choice'
class pywikibot.bot.OutputProxyOption(option, shortcut, output, **kwargs)[source]

Bases: pywikibot.bot_choice.OutputOption, pywikibot.bot_choice.StandardOption

An option which calls output of the given output class.

__init__(option, shortcut, output, **kwargs)[source]

Create a new option for the given sequence.

__module__ = 'pywikibot.bot_choice'
output()[source]

Output the contents.

class pywikibot.bot.HighlightContextOption(option, shortcut, text, context, delta=100, start=0, end=0)[source]

Bases: pywikibot.bot_choice.ContextOption

Show the original region highlighted.

__module__ = 'pywikibot.bot_choice'
output_range(start, end)[source]

Show normal context with a red center region.

exception pywikibot.bot.ChoiceException(option, shortcut, **kwargs)[source]

Bases: pywikibot.bot_choice.StandardOption, Exception

A choice for input_choice which result in this exception.

__module__ = 'pywikibot.bot_choice'
result(value)[source]

Return itself to raise the exception.

exception pywikibot.bot.UnhandledAnswer(stop=False)[source]

Bases: Exception

The given answer didn’t suffice.

__init__(stop=False)[source]

Initializer.

__module__ = 'pywikibot.bot'
class pywikibot.bot.Choice(option, shortcut, replacer)[source]

Bases: pywikibot.bot_choice.StandardOption

A simple choice consisting of a option, shortcut and handler.

__init__(option, shortcut, replacer)[source]

Initializer.

__module__ = 'pywikibot.bot'
handle()[source]

Handle this choice. Must be implemented.

The current link will be handled by this choice.

replacer

The replacer.

class pywikibot.bot.AlwaysChoice(replacer, option='always', shortcut='a')[source]

Bases: pywikibot.bot.Choice

Add an option to always apply the default.

__init__(replacer, option='always', shortcut='a')[source]

Initializer.

__module__ = 'pywikibot.bot'
answer

Get the actual default answer instructing the replacement.

handle()[source]

Handle the custom shortcut.

Directly return answer whether it’s applying it always.

exception pywikibot.bot.QuitKeyboardInterrupt[source]

Bases: pywikibot.bot_choice.ChoiceException, KeyboardInterrupt

The user has cancelled processing at a prompt.

__init__()[source]

Constructor using the ‘quit’ (‘q’) in input_choice.

__module__ = 'pywikibot.bot_choice'
class pywikibot.bot.InteractiveReplace(old_link, new_link, default=None, automatic_quit=True)[source]

Bases: object

A callback class for textlib’s replace_links.

It shows various options which can be switched on and off: * allow_skip_link = True (skip the current link) * allow_unlink = True (unlink) * allow_replace = False (just replace target, keep section and label) * allow_replace_section = False (replace target and section, keep label) * allow_replace_label = False (replace target and label, keep section) * allow_replace_all = False (replace target, section and label) (The boolean values are the default values)

It has also a context attribute which must be a non-negative integer. If it is greater 0 it shows that many characters before and after the link in question. The context_delta attribute can be defined too and adds an option to increase context by the given amount each time the option is selected.

Additional choices can be defined using the ‘additional_choices’ and will be amended to the choices defined by this class. This list is mutable and the Choice instance returned and created by this class are too.

__call__(link, text, groups, rng)[source]

Ask user how the selected link should be replaced.

__init__(old_link, new_link, default=None, automatic_quit=True)[source]

Initializer.

Parameters:
  • old_link (Link or Page) – The old link which is searched. The label and section are ignored.
  • new_link (Link or Page or False) – The new link with which it should be replaced. Depending on the replacement mode it’ll use this link’s label and section. If False it’ll unlink all and the attributes beginning with allow_replace are ignored.
  • default (None or str) – The default answer as the shortcut
  • automatic_quit (bool) – Add an option to quit and raise a QuitKeyboardException.
__module__ = 'pywikibot.bot'
choices

Return the tuple of choices.

current_groups

Get the current groups when it’s handling one currently.

Get the current link when it’s handling one currently.

current_range

Get the current range when it’s handling one currently.

current_text

Get the current text when it’s handling one currently.

handle_answer(choice)[source]

Return the result for replace_links.

Handle the currently given replacement.

pywikibot.bot.calledModuleName()[source]

Return the name of the module calling this function.

This is required because the -help option loads the module’s docstring and because the module name will be used for the filename of the log.

Return type:str
pywikibot.bot.handle_args(args=None, do_help=True)[source]

Handle standard command line arguments, and return the rest as a list.

Takes the command line arguments as Unicode strings, processes all global parameters such as -lang or -log, initialises the logging layer, which emits startup information into log at level ‘verbose’.

This makes sure that global arguments are applied first, regardless of the order in which the arguments were given.

args may be passed as an argument, thereby overriding sys.argv

Parameters:
  • args (typing.Iterable) – Command line arguments
  • do_help (bool) – Handle parameter ‘-help’ to show help and invoke sys.exit
Returns:

list of arguments not recognised globally

Return type:

list of unicode

pywikibot.bot.showHelp(module_name=None)[source]

Show help for the Bot.

pywikibot.bot.suggest_help(missing_parameters=[], missing_generator=False, unknown_parameters=[], exception=None, missing_action=False, additional_text='', missing_dependencies=[])[source]

Output error message to use -help with additional text before it.

Parameters:
  • missing_parameters (list of str) – A list of parameters which are missing.
  • missing_generator (bool) – Whether a generator is missing.
  • unknown_parameters (list of str) – A list of parameters which are unknown.
  • exception (Exception) – An exception thrown.
  • missing_action (bool) – Add an entry that no action was defined.
  • additional_text (str) – Additional text added to the end.
  • missing_dependencies (list of str) – A list of dependencies which can not be imported.
pywikibot.bot.writeToCommandLogFile()[source]

Save name of the called module along with all params to logs/commands.log.

This can be used by user later to track errors or report bugs.

pywikibot.bot.open_webbrowser(page)[source]

Open the web browser displaying the page and wait for input.

class pywikibot.bot.OptionHandler(**kwargs)[source]

Bases: object

Class to get and set options.

__init__(**kwargs)[source]

Only accept options defined in availableOptions.

Parameters:kwargs – bot options
__module__ = 'pywikibot.bot'
availableOptions = {}
getOption(option)[source]

Get the current value of an option.

Parameters:option – key defined in OptionHandler.availableOptions
Raises:Error – No valid option is given with option parameter
setOptions(**kwargs)[source]

Set the instance options.

Parameters:kwargs – options
class pywikibot.bot.BaseBot(**kwargs)[source]

Bases: pywikibot.bot.OptionHandler

Generic Bot to be subclassed.

This class provides a run() method for basic processing of a generator one page at a time.

If the subclass places a page generator in self.generator, Bot will process each page in the generator, invoking the method treat() which must then be implemented by subclasses.

If the subclass does not set a generator, or does not override treat() or run(), NotImplementedError is raised.

__init__(**kwargs)[source]

Only accept options defined in availableOptions.

Parameters:kwargs – bot options
__module__ = 'pywikibot.bot'
availableOptions = {'always': False}
current_page

Return the current working page as a property.

exit()[source]

Cleanup and exit processing.

Invoked when Bot.run() is finished. Prints treat and save counters and informs whether the script terminated gracefully or was halted by exception. May be overridden by subclasses.

init_page(item)[source]

Initialize a generator item before treating.

Ensure that the result of init_page is always a pywikibot.Page object even when the generator returns something else.

Also used to set the arrange the current site. This is called before skip_page and treat.

Parameters:item – any item from self.generator
Returns:return the page object to be processed further or None if page is a pywikibot.Page already and superclass’ init_page isn’t to be called
Return type:pywikibot.Page or None
quit()[source]

Cleanup and quit processing.

run()[source]

Process all pages in generator.

Raises:AssertionError – “page” is not a pywikibot.page.BasePage object
setup()[source]

Some initial setup before run operation starts.

This can be used for reading huge parts from life wiki or file operation which is more than just initialize the instance. Invoked by run() before running through generator loop.

skip_page(page)[source]

Return whether treat should be skipped for the page.

Parameters:page (pywikibot.Page) – Page object to be processed
stop()[source]

Stop iterating.

teardown()[source]

Some cleanups after run operation. Invoked by exit().

treat(page)[source]

Process one page (abstract method).

Parameters:page (pywikibot.Page) – Page object to be processed
userPut(page, oldtext, newtext, **kwargs, comment='[deprecated name of summary]', async='[deprecated name of asynchronous]')[source]

Save a new revision of a page, with user confirmation as required.

Print differences, ask user for confirmation, and puts the page if needed.

Option used:

  • ‘always’

Keyword args used:

  • ‘asynchronous’ - passed to page.save
  • ‘summary’ - passed to page.save
  • ‘show_diff’ - show changes between oldtext and newtext (enabled)
  • ‘ignore_save_related_errors’ - report and ignore (disabled)
  • ‘ignore_server_errors’ - report and ignore (disabled)
Returns:whether the page was saved successfully
Return type:bool
user_confirm(question)[source]

Obtain user response if bot option ‘always’ not enabled.

class pywikibot.bot.Bot(site=None, **kwargs)[source]

Bases: pywikibot.bot.BaseBot

Generic bot subclass for multiple sites.

If possible the MultipleSitesBot or SingleSiteBot classes should be used instead which specifically handle multiple or single sites.

__init__(site=None, **kwargs)[source]

Create a Bot instance and initialize cached sites.

__module__ = 'pywikibot.bot'
init_page(item)[source]

Update site before calling treat.

run()[source]

Check if it automatically updates the site before run.

site

Get the current site.

class pywikibot.bot.ConfigParserBot(**kwargs)[source]

Bases: pywikibot.bot.BaseBot

A bot class that can read options from scripts.ini file.

All options must be predefined in availableOptions dictionary. The type of these options is responsible for the correct interpretation of the options type given by the .ini file. They can be interpreted as bool, int, float or str (default). The settings file may be like:

[add_text] # edit summary for the bot. summary = Bot: Aggiungo template Categorizzare

[shell] ; Shell options always: true

The option values are interpreted in this order:

- availableOptions default setting
- script.ini options settings
- command line arguments
INI = 'scripts.ini'
__module__ = 'pywikibot.bot'
setOptions(**kwargs)[source]

Read settings from scripts.ini file.

class pywikibot.bot.SingleSiteBot(site=True, **kwargs)[source]

Bases: pywikibot.bot.BaseBot

A bot only working on one site and ignoring the others.

If no site is given from the start it’ll use the first page’s site. Any page after the site has been defined and is not on the defined site will be ignored.

__init__(site=True, **kwargs)[source]

Create a SingleSiteBot instance.

Parameters:site (True or None or Site) – If True it’ll be set to the configured site using pywikibot.Site.
__module__ = 'pywikibot.bot'
init_page(item)[source]

Set site if not defined.

site

Site that the bot is using.

skip_page(page)[source]

Skip page if it is not on the defined site.

class pywikibot.bot.MultipleSitesBot(**kwargs)[source]

Bases: pywikibot.bot.BaseBot

A bot class working on multiple sites.

The bot should accommodate for that case and not store site specific information on only one site.

__init__(**kwargs)[source]

Initializer.

__module__ = 'pywikibot.bot'
init_page(item)[source]

Define the site for this page.

run()[source]

Reset the bot’s site after run.

class pywikibot.bot.CurrentPageBot(**kwargs)[source]

Bases: pywikibot.bot.BaseBot

A bot which automatically sets ‘current_page’ on each treat().

This class should be always used together with either the MultipleSitesBot or SingleSiteBot class as there is no site management in this class.

__module__ = 'pywikibot.bot'
ignore_server_errors = False
put_current(new_text, ignore_save_related_errors=None, ignore_server_errors=None, **kwargs, comment='[deprecated name of summary]')[source]

Call Bot.userPut but use the current page.

It compares the new_text to the current page text.

Parameters:
  • new_text (basestring) – The new text
  • ignore_save_related_errors (bool or None) – Ignore save related errors and automatically print a message. If None uses this instances default.
  • ignore_server_errors (bool or None) – Ignore server errors and automatically print a message. If None uses this instances default.
  • kwargs – Additional parameters directly given to Bot.userPut.
Returns:

whether the page was saved successfully

Return type:

bool

treat(page)[source]

Set page to current page and treat that page.

treat_page()[source]

Process one page (Abstract method).

class pywikibot.bot.AutomaticTWSummaryBot(**kwargs)[source]

Bases: pywikibot.bot.CurrentPageBot

A class which automatically defines summary for put_current.

The class must defined a summary_key string which contains the i18n key for pywikibot.i18n.twtranslate. It can also override the summary_parameters property to specify any parameters for the translated message.

__module__ = 'pywikibot.bot'
put_current(*args, **kwargs)[source]

Defining a summary if not already defined and then call original.

summary_key = None
summary_parameters

A dictionary of all parameters for i18n.

class pywikibot.bot.ExistingPageBot(**kwargs)[source]

Bases: pywikibot.bot.CurrentPageBot

A CurrentPageBot class which only treats existing pages.

__module__ = 'pywikibot.bot'
skip_page(page)[source]

Treat page if it exists and handle NoPage from it.

class pywikibot.bot.FollowRedirectPageBot(**kwargs)[source]

Bases: pywikibot.bot.CurrentPageBot

A CurrentPageBot class which follows the redirect.

__module__ = 'pywikibot.bot'
treat(page)[source]

Treat target if page is redirect and the page otherwise.

class pywikibot.bot.CreatingPageBot(**kwargs)[source]

Bases: pywikibot.bot.CurrentPageBot

A CurrentPageBot class which only treats nonexistent pages.

__module__ = 'pywikibot.bot'
skip_page(page)[source]

Treat page if doesn’t exist.

class pywikibot.bot.RedirectPageBot(**kwargs)[source]

Bases: pywikibot.bot.CurrentPageBot

A RedirectPageBot class which only treats redirects.

__module__ = 'pywikibot.bot'
skip_page(page)[source]

Treat only redirect pages and handle IsNotRedirectPage from it.

class pywikibot.bot.NoRedirectPageBot(**kwargs)[source]

Bases: pywikibot.bot.CurrentPageBot

A NoRedirectPageBot class which only treats non-redirects.

__module__ = 'pywikibot.bot'
skip_page(page)[source]

Treat only non-redirect pages and handle IsRedirectPage from it.

class pywikibot.bot.WikidataBot(**kwargs, use_from_page=NotImplemented)[source]

Bases: pywikibot.bot.Bot, pywikibot.bot.ExistingPageBot

Generic Wikidata Bot to be subclassed.

Source claims (P143) can be created for specific sites

@cvar use_from_page: If True (default) it will apply ItemPage.fromPage
for every item. If False it assumes that the pages are actually already ItemPage (page in treat_page_and_item will be None). If None it’ll use ItemPage.fromPage when the page is not in the site’s item namespace.
@cvar treat_missing_item: Whether pages without items should be treated.
Note that this is checked after create_missing_item.
@ivar create_missing_item: If True, new items will be created if the
current page doesn’t have one. Subclasses should override this in the initializer with a bool value or using self.getOption.
__init__(**kwargs, use_from_page=NotImplemented)[source]

Initializer of the WikidataBot.

__module__ = 'pywikibot.bot'
cacheSources()[source]

Fetch the sources from the list on Wikidata.

It is stored internally and reused by getSource()

create_item_for_page(page, data=None, summary=None, **kwargs)[source]

Create an ItemPage with the provided page as the sitelink.

Parameters:
  • page (pywikibot.Page) – the page for which the item will be created
  • data (dict) – additional data to be included in the new item (optional). Note that data created from the page have higher priority.
  • summary (str) – optional edit summary to replace the default one
Returns:

pywikibot.ItemPage or None

getSource(site)[source]

Create a Claim usable as a source for Wikibase statements.

Parameters:site (Site) – site that is the source of assertions.
Returns:pywikibot.Claim or None
get_property_by_name(property_name)[source]

Find given property and return its ID.

Method first uses site.search() and if the property isn’t found, then asks user to provide the property ID.

Parameters:property_name (str) – property to find
treat_missing_item = False
treat_page()[source]

Treat a page.

treat_page_and_item(page, item)[source]

Treat page together with its item (if it exists).

Must be implemented in subclasses.

use_from_page = True
user_add_claim(item, claim, source=None, bot=True, **kwargs)[source]

Add a claim to an item, with user confirmation as required.

Parameters:
Keyword Arguments:
 
  • ignore_server_errors – if True, server errors will be reported and ignored (default: False)
  • ignore_save_related_errors – if True, errors related to page save will be reported and ignored (default: False)
Returns:

whether the item was saved successfully

Return type:

bool

user_add_claim_unless_exists(item, claim, exists_arg='', source=None, logger_callback=<function log>, **kwargs)[source]

Decorator of user_add_claim.

Before adding a new claim, it checks if we can add it, using provided filters.

See:

documentation of claimit.py

Parameters:
  • exists_arg (str) – pattern for merging existing claims with new ones
  • logger_callback (callable) – function logging the output of the method
Returns:

whether the claim could be added

Return type:

bool

user_edit_entity(item, data=None, ignore_save_related_errors=None, ignore_server_errors=None, **kwargs)[source]

Edit entity with data provided, with user confirmation as required.

Parameters:
  • item (ItemPage) – page to be edited
  • data – data to be saved, or None if the diff should be created automatically
  • ignore_save_related_errors (bool or None) – Ignore save related errors and automatically print a message. If None uses this instances default.
  • ignore_server_errors (bool or None) – Ignore server errors and automatically print a message. If None uses this instances default.
Keyword Arguments:
 
  • summary – revision comment, passed to ItemPage.editEntity
  • show_diff – show changes between oldtext and newtext (default: True)
Returns:

whether the item was saved successfully

Return type:

bool

pywikibot.bot_choice module

Choices for input_choice.

exception pywikibot.bot_choice.ChoiceException(option, shortcut, **kwargs)[source]

Bases: pywikibot.bot_choice.StandardOption, Exception

A choice for input_choice which result in this exception.

__module__ = 'pywikibot.bot_choice'
result(value)[source]

Return itself to raise the exception.

class pywikibot.bot_choice.ContextOption(option, shortcut, text, context, delta=100, start=0, end=0)[source]

Bases: pywikibot.bot_choice.OutputOption, pywikibot.bot_choice.StandardOption

An option to show more and more context.

__init__(option, shortcut, text, context, delta=100, start=0, end=0)[source]

Initializer.

__module__ = 'pywikibot.bot_choice'
output()[source]

Output the context.

output_range(start_context, end_context)[source]

Output a section from the text.

result(value)[source]

Add the delta to the context and output it.

class pywikibot.bot_choice.HighlightContextOption(option, shortcut, text, context, delta=100, start=0, end=0)[source]

Bases: pywikibot.bot_choice.ContextOption

Show the original region highlighted.

__module__ = 'pywikibot.bot_choice'
output_range(start, end)[source]

Show normal context with a red center region.

class pywikibot.bot_choice.IntegerOption(minimum=1, maximum=None, prefix='', **kwargs)[source]

Bases: pywikibot.bot_choice.Option

An option allowing a range of integers.

__init__(minimum=1, maximum=None, prefix='', **kwargs)[source]

Initializer.

__module__ = 'pywikibot.bot_choice'
format(default=None)[source]

Return a formatted string showing the range.

maximum

Return the upper bound of the range of allowed values.

minimum

Return the lower bound of the range of allowed values.

parse(value)[source]

Return integer from value with prefix removed.

result(value)[source]

Return the value converted into int.

test(value)[source]

Return whether the value is an int and in the specified range.

class pywikibot.bot_choice.ListOption(sequence, prefix='', **kwargs)[source]

Bases: pywikibot.bot_choice.IntegerOption

An option to select something from a list.

__init__(sequence, prefix='', **kwargs)[source]

Initializer.

__module__ = 'pywikibot.bot_choice'
format(default=None)[source]

Return a string showing the range.

maximum

Return the maximum value.

result(value)[source]

Return a tuple with the prefix and selected value.

class pywikibot.bot_choice.MultipleChoiceList(sequence, prefix='', **kwargs)[source]

Bases: pywikibot.bot_choice.ListOption

An option to select multiple items from a list.

__module__ = 'pywikibot.bot_choice'
result(value)[source]

Return a tuple with the prefix and selected values as a list.

test(value)[source]

Return whether the values are int and in the specified range.

class pywikibot.bot_choice.NestedOption(option, shortcut, description, options)[source]

Bases: pywikibot.bot_choice.OutputOption, pywikibot.bot_choice.StandardOption

An option containing other options.

It will return True in test if this option applies but False if a sub option applies while handle returns the sub option.

__init__(option, shortcut, description, options)[source]

Initializer.

__module__ = 'pywikibot.bot_choice'
format(default=None)[source]

Return a formatted string for that option.

handled(value)[source]

Return itself if it applies or the applying sub option.

output()[source]

Output the suboptions.

class pywikibot.bot_choice.Option(stop=True)[source]

Bases: object

A basic option for input_choice.

The following methods need to be implemented: * format(default=None) * result(value) * test(value)

The methods test and handled are in such a relationship that when handled returns itself that test must return True for that value. So if test returns False handled may not return itself but it may return not None.

Also result only returns a sensible value when test returns True for the same value.

__init__(stop=True)[source]

Initializer.

__module__ = 'pywikibot.bot_choice'
format(default=None)[source]

Return a formatted string for that option.

static formatted(text, options, default=None)[source]

Create a text with the options formatted into it.

Parameters:
  • text (str) – Text into which options are to be formatted
  • options (Iterable) – Option instances to be formatted
Returns:

Text with the options formatted into it

Return type:

str

handled(value)[source]

Return the Option object that applies to the given value.

If this Option object doesn’t know which applies it returns None.

result(value)[source]

Return the actual value which is associated by the given one.

stop

Return whether this option stops asking.

test(value)[source]

Return True whether this option applies.

class pywikibot.bot_choice.OutputOption(stop=True)[source]

Bases: pywikibot.bot_choice.Option

An option that never stops and can output on each question.

__module__ = 'pywikibot.bot_choice'
before_question = False
output()[source]

Output a string when selected and possibly before the question.

result(value)[source]

Just output the value.

stop

Never stop asking.

class pywikibot.bot_choice.OutputProxyOption(option, shortcut, output, **kwargs)[source]

Bases: pywikibot.bot_choice.OutputOption, pywikibot.bot_choice.StandardOption

An option which calls output of the given output class.

__init__(option, shortcut, output, **kwargs)[source]

Create a new option for the given sequence.

__module__ = 'pywikibot.bot_choice'
output()[source]

Output the contents.

exception pywikibot.bot_choice.QuitKeyboardInterrupt[source]

Bases: pywikibot.bot_choice.ChoiceException, KeyboardInterrupt

The user has cancelled processing at a prompt.

__init__()[source]

Constructor using the ‘quit’ (‘q’) in input_choice.

__module__ = 'pywikibot.bot_choice'
class pywikibot.bot_choice.ShowingListOption(sequence, prefix='', pre=None, post=None, **kwargs)[source]

Bases: pywikibot.bot_choice.ListOption, pywikibot.bot_choice.OutputOption

An option to show a list and select an item.

__init__(sequence, prefix='', pre=None, post=None, **kwargs)[source]

Initializer.

Parameters:
  • pre (str) – Additional comment printed before the list.
  • post (str) – Additional comment printed after the list.
__module__ = 'pywikibot.bot_choice'
before_question = True
output()[source]

Output the enumerated list.

stop

Return whether this option stops asking.

class pywikibot.bot_choice.ShowingMultipleChoiceList(sequence, prefix='', pre=None, post=None, **kwargs)[source]

Bases: pywikibot.bot_choice.ShowingListOption, pywikibot.bot_choice.MultipleChoiceList

An option to show a list and select multiple items.

__module__ = 'pywikibot.bot_choice'
class pywikibot.bot_choice.StandardOption(option, shortcut, **kwargs)[source]

Bases: pywikibot.bot_choice.Option

An option with a description and shortcut and returning the shortcut.

__init__(option, shortcut, **kwargs)[source]

Initializer.

Parameters:
  • option (str) – option string
  • shortcut (str) – Shortcut of the option
__module__ = 'pywikibot.bot_choice'
format(default=None)[source]

Return a formatted string for that option.

result(value)[source]

Return the lowercased shortcut.

test(value)[source]

Return True whether this option applies.

pywikibot.botirc module

WARNING: THIS MODULE EXISTS SOLELY TO PROVIDE BACKWARDS-COMPATIBILITY.

IT MAY BE REMOVED SOON.

Deprecated user-interface related functions for building bots.

note:the script requires the irc library
class pywikibot.botirc.IRCBot(site, channel, nickname, server, port=6667, **kwargs)[source]

Bases: pywikibot.bot.Bot, pywikibot.botirc.SingleServerIRCBot

A generic IRC Bot to be subclassed.

A Bot that displays the ordinal number of the new articles being created visible on the Recent Changes list. The Bot doesn’t make any edits, no account needed.

__init__(site, channel, nickname, server, port=6667, **kwargs)[source]

Initializer.

__module__ = 'pywikibot.botirc'
availableOptions = {}
do_command(e, cmd)[source]

Ignore command request.

on_dccchat(c, e)[source]

Ignore DCC chat.

on_dccmsg(c, e)[source]

Ignore DCC message.

on_nicknameinuse(c, e)[source]

Provide an alternative nickname.

on_privmsg(c, e)[source]

Ignore private message.

on_pubmsg(c, e)[source]

Respond to public message.

on_quit(e, cmd)[source]

Ignore quit request.

on_welcome(c, e)[source]

Join channel.

pywikibot.config2 module

Module to define and load pywikibot configuration default and user preferences.

User preferences are loaded from a python file called user-config.py, which may be located in directory specified by the environment variable PYWIKIBOT_DIR, or the same directory as pwb.py, or in a directory within the users home. See get_base_dir for more information.

If user-config.py can not be found in any of those locations, this module will fail to load unless the environment variable PYWIKIBOT_NO_USER_CONFIG is set to a value other than ‘0’. i.e. PYWIKIBOT_NO_USER_CONFIG=1 will allow config to load without a user-config.py. However, warnings will be shown if user-config.py was not loaded. To prevent these warnings, set PYWIKIBOT_NO_USER_CONFIG=2.

Provides two functions to register family classes which can be used in the user-config:

  • register_family_file
  • register_families_folder

Other functions made available to user-config:

  • user_home_path

Sets module global base_dir and provides utility methods to build paths relative to base_dir:

  • makepath
  • datafilepath
  • shortpath
pywikibot.config2.datafilepath(*filename, **kwargs)[source]

Return an absolute path to a data file in a standard location.

Argument(s) are zero or more directory names, optionally followed by a data file name. The return path is offset to config.base_dir. Any directories in the path that do not already exist are created if create is True, otherwise the filesystem keeps unchanged.

Parameters:path (str) – path in the filesystem
Keyword Arguments:
 create – create the directory if it is True. Otherwise don’t change the filesystem. Default is True.
pywikibot.config2.get_base_dir(test_directory=None)[source]

Return the directory in which user-specific information is stored.

This is determined in the following order:
  1. If the script was called with a -dir: argument, use the directory provided in this argument.
  2. If the user has a PYWIKIBOT_DIR environment variable, use the value of it.
  3. If user-config is present in current directory, use the current directory.
  4. If user-config is present in pwb.py directory, use that directory
  5. Use (and if necessary create) a ‘pywikibot’ folder under ‘Application Data’ or ‘AppDataRoaming’ (Windows) or ‘.pywikibot’ directory (Unix and similar) under the user’s home directory.

Set PYWIKIBOT_NO_USER_CONFIG=1 to disable loading user-config.py

Parameters:test_directory (str or None) – Assume that a user config file exists in this directory. Used to test whether placing a user config file in this directory will cause it to be selected as the base directory.
Return type:str
pywikibot.config2.makepath(path, create=True)[source]

Return a normalized absolute version of the path argument.

If the given path already exists in the filesystem or create is False the filesystem is not modified. Otherwise if create is True makepath creates directories along the given path using the dirname() of the path. You may append a ‘/’ to the path if you want it to be a directory path.

from holger@trillke.net 2002/03/18

Parameters:
  • path (str) – path in the filesystem
  • create (bool) – create the directory if it is True. Otherwise do not change the filesystem. Default is True.
pywikibot.config2.register_families_folder(folder_path)[source]

Register all family class files contained in a directory.

pywikibot.config2.register_family_file(family_name, file_path)[source]

Register a single family class file.

Parameter file_path may be a path or an url. family.AutoFamily function is used when the url is given.

pywikibot.config2.shortpath(path)[source]

Return a file path relative to config.base_dir.

pywikibot.config2.user_home_path(path)[source]

Return a file path to a file in the user home.

pywikibot.cosmetic_changes module

This module can do slight modifications to tidy a wiki page’s source code.

The changes are not supposed to change the look of the rendered wiki page.

If you wish to run this as an stand-alone script, use:

scripts/cosmetic_changes.py

For regular use, it is recommended to put this line into your user-config.py:

cosmetic_changes = True

You may enable cosmetic changes for additional languages by adding the dictionary cosmetic_changes_enable to your user-config.py. It should contain a tuple of languages for each site where you wish to enable in addition to your own langlanguage if cosmetic_changes_mylang_only is True (see below). Please set your dictionary by adding such lines to your user-config.py:

cosmetic_changes_enable[‘wikipedia’] = (‘de’, ‘en’, ‘fr’)

There is another config variable: You can set

cosmetic_changes_mylang_only = False

if you’re running a bot on multiple sites and want to do cosmetic changes on all of them, but be careful if you do.

You may disable cosmetic changes by adding the all unwanted languages to the dictionary cosmetic_changes_disable in your user-config.py. It should contain a tuple of languages for each site where you wish to disable cosmetic changes. You may use it with cosmetic_changes_mylang_only is False, but you can also disable your own language. This also overrides the settings in the dictionary cosmetic_changes_enable. Please set this dictionary by adding such lines to your user-config.py:

cosmetic_changes_disable[‘wikipedia’] = (‘de’, ‘en’, ‘fr’)

You may disable cosmetic changes for a given script by appending the all unwanted scripts to the list cosmetic_changes_deny_script in your user-config.py. By default it contains cosmetic_changes.py itself and touch.py. This overrides all other enabling settings for cosmetic changes. Please modify the given list by adding such lines to your user-config.py:

cosmetic_changes_deny_script.append(‘your_script_name_1’)

or by adding a list to the given one:

cosmetic_changes_deny_script += [‘your_script_name_1’,
‘your_script_name_2’]
class pywikibot.cosmetic_changes.CosmeticChangesToolkit(site, diff=False, namespace=None, pageTitle=None, ignore=False, redirect=NotImplemented, debug='[deprecated name of diff]')[source]

Bases: object

Cosmetic changes toolkit.

__init__(site, diff=False, namespace=None, pageTitle=None, ignore=False, redirect=NotImplemented, debug='[deprecated name of diff]')[source]

Initializer.

__module__ = 'pywikibot.cosmetic_changes'
change(text)[source]

Execute all clean up methods and catch errors if activated.

Tidy up wikilinks found in a string.

This function will: * Replace underscores with spaces

  • Move leading and trailing spaces out of the wikilink and into the surrounding text
  • Convert URL-encoded characters into Unicode-encoded characters
  • Move trailing characters out of the link and make the link without using a pipe, if possible
  • Capitalize the article title of the link, if appropriate
Parameters:text (str) – string to perform the clean-up on
Returns:text with tidied wikilinks
Return type:str
cleanUpSectionHeaders(text)[source]

Add a space between the equal signs and the section title.

Example: ==Section title== becomes == Section title ==

NOTE: This space is recommended in the syntax help on the English and German Wikipedia. It is not wanted on Lojban and English Wiktionary (T168399, T169064) and it might be that it is not wanted on other wikis. If there are any complaints, please file a bug report.

commonsfiledesc(text)[source]

Clean up file descriptions on the Wikimedia Commons.

It is working according to [1] and works only on pages in the file namespace on the Wikimedia Commons.

[1]: https://commons.wikimedia.org/wiki/Commons:Tools/pywiki_file_description_cleanup

fixArabicLetters(text)[source]

Fix arabic and persian letters.

fixHtml(text)[source]

Relace html markups with wikitext markups.

fixReferences(text)[source]

Fix references tags.

fixSelfInterwiki(text)[source]

Interwiki links to the site itself are displayed like local links.

Remove their language code prefix.

fixStyle(text)[source]

Convert prettytable to wikitable class.

fixSyntaxSave(text)[source]

Convert weblinks to wikilink, fix link syntax.

fixTypo(text)[source]

Fix units.

fix_ISBN(text)[source]

Hyphenate ISBN numbers.

classmethod from_page(page, diff, ignore)[source]

Create toolkit based on the page.

putSpacesInLists(text)[source]

Add a space between the * or # and the text.

NOTE: This space is recommended in the syntax help on the English, German, and French Wikipedia. It might be that it is not wanted on other wikis. If there are any complaints, please file a bug report.

removeEmptySections(text)[source]

Cleanup empty sections.

removeNonBreakingSpaceBeforePercent(text)[source]

Remove a non-breaking space between number and percent sign.

Newer MediaWiki versions automatically place a non-breaking space in front of a percent sign, so it is no longer required to place it manually.

removeUselessSpaces(text)[source]

Cleanup multiple or trailing spaces.

replaceDeprecatedTemplates(text)[source]

Replace deprecated templates.

resolveHtmlEntities(text)[source]

Replace HTML entities with unicode.

safe_execute(method, text)[source]

Execute the method and catch exceptions if enabled.

standardizePageFooter(text)[source]

Standardize page footer.

Makes sure that interwiki links and categories are put into the correct position and into the right order. This combines the old instances of standardizeInterwiki and standardizeCategories.

The page footer consists of the following parts in that sequence: 1. categories 2. additional information depending on the local site policy 3. interwiki

translateAndCapitalizeNamespaces(text)[source]

Use localized namespace names.

translateMagicWords(text)[source]

Use localized magic words.

pywikibot.daemonize module

Module to daemonize the current process on Unix.

pywikibot.daemonize.daemonize(close_fd=True, chdir=True, redirect_std=None, write_pid=NotImplemented)[source]

Daemonize the current process.

Only works on POSIX compatible operating systems. The process will fork to the background and return control to terminal.

Parameters:
  • close_fd (bool) – Close the standard streams and replace them by /dev/null
  • chdir (bool) – Change the current working directory to /
  • redirect_std (str) – Filename to redirect stdout and stdin to

pywikibot.date module

Date data and manipulation module.

class pywikibot.date.FormatDate(site)[source]

Bases: object

Format a date.

__call__(m, d)[source]

Return a formatted month and day.

__init__(site)[source]

Initializer.

__module__ = 'pywikibot.date'
pywikibot.date.addFmt1(lang, isMnthOfYear, patterns)[source]

Add 12 month formats for a specific type (‘January’, ‘Feb.’).

The function must accept one parameter for the ->int or ->string conversions, just like everywhere else in the formats map. The patterns parameter is a list of 12 elements to be used for each month.

Parameters:lang (str) – language code
pywikibot.date.addFmt2(lang, isMnthOfYear, pattern, makeUpperCase=None)[source]

Update yrMnthFmts and dayMnthFmts using addFmt1.

pywikibot.date.alwaysTrue(x)[source]

Return True, always.

Used for multiple value selection function to accept all other values.

Parameters:x – not used
Returns:True
Return type:bool
pywikibot.date.apply_month_delta(date, month_delta=1, add_overlap=False)[source]

Add or subtract months from the date.

By default if the new month has less days then the day of the date it chooses the last day in the new month. For example a date in the March 31st added by one month will result in April 30th.

When the overlap is enabled, and there is overlap, then the new_date will be one month off and get_month_delta will report a number one higher.

It does only work on calendars with 12 months per year, and where the months are numbered consecutively beginning by 1.

Parameters:
  • date (date) – The starting date
  • month_delta (int) – The amount of months added or subtracted.
  • add_overlap (bool) – Add any missing days to the date, increasing the month once more.
Returns:

The end date

Return type:

type of date

pywikibot.date.decSinglVal(v)[source]

Return first item in list v.

pywikibot.date.dh(value, pattern, encf, decf, filter=None)[source]

Function to help with year parsing.

Usually it will be used as a lambda call in a map:

lambda v: dh(v, 'pattern string', encf, decf)
Parameters:
  • encf

    Converts from an integer parameter to another integer or a tuple of integers. Depending on the pattern, each integer will be converted to a proper string representation, and will be passed as a format argument to the pattern:

    pattern % encf(value)
    

    This function is a complement of decf.

  • decf – Converts a tuple/list of non-negative integers found in the original value string into a normalized value. The normalized value can be passed right back into dh() to produce the original string. This function is a complement of encf. dh() interprets %d as a decimal and %s as a roman numeral number.
pywikibot.date.dh_centuryAD(value, pattern)[source]

Helper for decoding an AD century.

pywikibot.date.dh_centuryBC(value, pattern)[source]

Helper for decoding an BC century.

pywikibot.date.dh_constVal(value, ind, match)[source]

Helper function to match a single value to a constant.

formats[‘CurrEvents’][‘en’](ind) => ‘Current Events’ formats[‘CurrEvents’][‘en’](‘Current Events’) => ind

pywikibot.date.dh_dayOfMnth(value, pattern)[source]

Helper for decoding a single integer value.

The single integer should be <=31, no conversion, no rounding (used in days of month).

pywikibot.date.dh_decAD(value, pattern)[source]

Helper for decoding a single integer value.

It should be no conversion, round to decimals (used in decades)

pywikibot.date.dh_decBC(value, pattern)[source]

Helper for decoding a single integer value.

It should be no conversion, round to decimals (used in decades)

pywikibot.date.dh_millenniumAD(value, pattern)[source]

Helper for decoding an AD millennium.

pywikibot.date.dh_millenniumBC(value, pattern)[source]

Helper for decoding an BC millennium.

pywikibot.date.dh_mnthOfYear(value, pattern)[source]

Helper for decoding a single integer value.

The value should be >=1000, no conversion, no rounding (used in month of the year)

pywikibot.date.dh_noConv(value, pattern, limit)[source]

Helper for decoding an integer value, no conversion, no rounding.

pywikibot.date.dh_number(value, pattern)[source]

Helper for decoding a number.

pywikibot.date.dh_simpleYearAD(value)[source]

Helper for decoding a single integer value.

This value should be representing a year with no extra symbols.

pywikibot.date.dh_singVal(value, match)[source]

Helper function to match a single value to a constant.

pywikibot.date.dh_yearAD(value, pattern)[source]

Helper for decoding a year value.

The value should have no conversion, no rounding, limits to 3000.

pywikibot.date.dh_yearBC(value, pattern)[source]

Helper for decoding a year value.

The value should have no conversion, no rounding, limits to 3000.

pywikibot.date.encDec0(i)[source]

Round to the nearest decade, decade starts with a ‘0’-ending year.

pywikibot.date.encDec1(i)[source]

Round to the nearest decade, decade starts with a ‘1’-ending year.

pywikibot.date.escapePattern2(pattern)[source]

Convert a string pattern into a regex expression and cache.

Allows matching of any _digitDecoders inside the string. Returns a compiled regex object and a list of digit decoders.

pywikibot.date.formatYear(lang, year)[source]

Return year name in a language.

pywikibot.date.getAutoFormat(lang, title, ignoreFirstLetterCase=True)[source]

Return first matching formatted date value.

Parameters:
  • lang – language code
  • title – value to format
Returns:

dictName (‘YearBC’, ‘December’, …) and value (a year, date, …)

Return type:

tuple

pywikibot.date.get_month_delta(date1, date2)[source]

Return the difference between to dates in months.

It does only work on calendars with 12 months per year, and where the months are consecutive and non-negative numbers.

pywikibot.date.intToLocalDigitsStr(value, digitsToLocalDict)[source]

Encode an integer value into a textual form.

pywikibot.date.intToRomanNum(i)[source]

Convert integer to roman numeral.

pywikibot.date.localDigitsStrToInt(value, digitsToLocalDict, localToDigitsDict)[source]

Convert digits to integer.

pywikibot.date.makeMonthList(pattern)[source]

Return a list of 12 elements based on the number of the month.

pywikibot.date.makeMonthNamedList(lang, pattern, makeUpperCase=None)[source]

Create a list of 12 elements based on the name of the month.

The language-dependent month name is used as a formatting argument to the pattern. The pattern must be have one %s that will be replaced by the localized month name. Use %%d for any other parameters that should be preserved.

pywikibot.date.monthName(lang, ind)[source]

Return the month name for a language.

pywikibot.date.multi(value, tuplst)[source]

Run multiple pattern checks for the same entry.

For example: 1st century, 2nd century, etc.

The tuplst is a list of tuples. Each tuple must contain two functions: first to encode/decode a single value (e.g. simpleInt), second is a predicate function with an integer parameter that returns true or false. When the 2nd function evaluates to true, the 1st function is used.

pywikibot.date.romanNumToInt(v)[source]

Convert roman numeral to integer.

pywikibot.date.slh(value, lst)[source]

Helper function for simple list value matching.

!!!!! The index starts at 1, so 1st element has index 1, not 0 !!!!!

Usually it will be used as a lambda call in a map:

lambda v: slh(v, ['January','February',...])

Usage scenarios:

formats['MonthName']['en'](1) => 'January'
formats['MonthName']['en']('January') => 1
formats['MonthName']['en']('anything else') => raise ValueError

pywikibot.diff module

Diff module.

class pywikibot.diff.Hunk(a, b, grouped_opcode)[source]

Bases: object

One change hunk between a and b.

Note: parts of this code are taken from by difflib.get_grouped_opcodes().

APPR = 1
NOT_APPR = -1
PENDING = 0
__init__(a, b, grouped_opcode)[source]

Initializer.

Parameters:
  • a – sequence of lines
  • b – sequence of lines
  • grouped_opcode – list of 5-tuples describing how to turn a into b. It has the same format as returned by difflib.get_opcodes().
__module__ = 'pywikibot.diff'
__repr__()[source]

Return a reconstructable representation.

__str__()[source]

Return the diff as plain text.

apply()[source]

Turn a into b for this hunk.

color_line(line, line_ref=None)[source]

Color line characters.

If line_ref is None, the whole line is colored. If line_ref[i] is not blank, line[i] is colored. Color depends if line starts with +/-.

line: string line_ref: string.

create_diff()[source]

Generator of diff text for this hunk, without formatting.

format_diff()[source]

Color diff lines.

get_header()[source]

Provide header of unified diff.

static get_header_text(a_rng, b_rng, affix='@@')[source]

Provide header for any ranges.

class pywikibot.diff.PatchManager(text_a, text_b, context=0, by_letter=False, replace_invisible=False, n='[deprecated name of context]')[source]

Bases: object

Apply patches to text_a to obtain a new text.

If all hunks are approved, text_b will be obtained.

__init__(text_a, text_b, context=0, by_letter=False, replace_invisible=False, n='[deprecated name of context]')[source]

Initializer.

Parameters:
  • text_a (basestring) – base text
  • text_b (basestring) – target text
  • context (int) – number of lines which are context
  • by_letter (bool) – if text_a and text_b are single lines, comparison can be done letter by letter.
  • replace_invisible (bool) – Replace invisible characters like U+200e with the charnumber in brackets (e.g. <200e>).
__module__ = 'pywikibot.diff'
apply()[source]

Apply changes. If there are undecided changes, ask to review.

get_blocks()[source]

Return list with blocks of indexes.

Format of each block:

[-1, (i1, i2), (-1, -1)] -> block a[i1:i2] does not change from
    a to b then is there is no corresponding hunk.
[hunk index, (i1, i2), (j1, j2)] -> block a[i1:i2] becomes b[j1:j2]
print_hunks()[source]

Print the headers and diff texts of all hunks to the output.

review_hunks()[source]

Review hunks.

pywikibot.diff.cherry_pick(oldtext, newtext, n=0, by_letter=False)[source]

Propose a list of changes for approval.

Text with approved changes will be returned. n: int, line of context as defined in difflib.get_grouped_opcodes(). by_letter: if text_a and text_b are single lines, comparison can be done

pywikibot.diff.html_comparator(compare_string)[source]

List of added and deleted contexts from ‘action=compare’ html string.

This function is useful when combineds with site.py’s “compare” method. Site.compare() returns HTML that is useful for displaying on a page. Here we use BeautifulSoup to get the un-HTML-ify the context of changes. Finally we present the added and deleted contexts. :param compare_string: HTML string from mediawiki API :type compare_string: str :return: deleted and added list of contexts :rtype: dict

pywikibot.echo module

Classes and functions for working with the Echo extension.

class pywikibot.echo.Notification(site)[source]

Bases: object

A notification issued by the Echo extension.

__init__(site)[source]

Initialize an empty Notification object.

__module__ = 'pywikibot.echo'
classmethod fromJSON(site, data)[source]

Construct a Notification object from JSON data returned by the API.

Return type:Notification
id

Return notification id as unicode.

Return type:str
Type:DEPRECATED
mark_as_read()[source]

Mark the notification as read.

pywikibot.editor module

Text editor class for your favourite editor.

class pywikibot.editor.TextEditor[source]

Bases: object

Text editor.

__module__ = 'pywikibot.editor'
edit(text, jumpIndex=None, highlight=None)[source]

Call the editor and thus allows the user to change the text.

Halts the thread’s operation until the editor is closed.

Parameters:
  • text (str) – the text to be edited
  • jumpIndex (int) – position at which to put the caret
  • highlight (str) – each occurrence of this substring will be highlighted
Returns:

the modified text, or None if the user didn’t save the text file in his text editor

Return type:

str or None

pywikibot.exceptions module

Exception and warning classes used throughout the framework.

Error: Base class, all exceptions should the subclass of this class.

  • NoUsername: Username is not in user-config.py, or it is invalid.
  • UserBlocked: Username or IP has been blocked
  • AutoblockUser: requested action on a virtual autoblock user not valid
  • UserRightsError: insufficient rights for requested action
  • BadTitle: Server responded with BadTitle
  • InvalidTitle: Invalid page title
  • CaptchaError: Captcha is asked and config.solve_captcha == False
  • Server504Error: Server timed out with HTTP 504 code
  • i18n.TranslationError: i18n/l10n message not available
  • UnknownExtension: Extension is not defined for this site

SiteDefinitionError: Site loading problem

  • UnknownSite: Site does not exist in Family
  • UnknownFamily: Family is not registered

PageRelatedError: any exception which is caused by an operation on a Page.

  • NoPage: Page does not exist
  • UnsupportedPage: Page is not supported due to a namespace restriction
  • IsRedirectPage: Page is a redirect page
  • IsNotRedirectPage: Page is not a redirect page
  • CircularRedirect: Page is a circular redirect
  • InterwikiRedirectPage: Page is a redirect to another site
  • SectionError: The section specified by # does not exist
  • NotEmailableError: The target user has disabled email
  • NoMoveTarget: An expected move target page does not exist
PageLoadRelatedError: any exception which happens while loading a Page.
  • InconsistentTitleReceived: Page receives a title inconsistent with query

PageSaveRelatedError: page exceptions within the save operation on a Page (alias: PageNotSaved).

  • SpamfilterError: MediaWiki spam filter detected a blacklisted URL
  • TitleblacklistError: MediaWiki detected a blacklisted page title
  • OtherPageSaveError: misc. other save related exception.
  • LockedPage: Page is locked
    • LockedNoPage: Title is locked against creation
    • CascadeLockedPage: Page is locked due to cascading protection
  • EditConflict: Edit conflict while uploading the page
    • PageDeletedConflict: Page was deleted since being retrieved
    • PageCreatedConflict: Page was created by another user
    • ArticleExistsConflict: Page article already exists
  • NoCreateError: parameter nocreate not allow page creation

ServerError: a problem with the server.

  • FatalServerError: A fatal/non-recoverable server error

WikiBaseError: any issue specific to Wikibase.

  • CoordinateGlobeUnknownException: globe is not implemented yet.
  • EntityTypeUnknownException: entity type is not available on the site.

TimeoutError: request failed with a timeout

DeprecationWarning: old functionality replaced by new functionality

PendingDeprecationWarning: problematic code which has not yet been fully deprecated, possibly because a replacement is not available

RuntimeWarning: problems developers should have fixed, and users need to be aware of its status.

  • tools._NotImplementedWarning: do not use
  • NotImplementedWarning: functionality not implemented

UserWarning: warnings targeted at users

  • config2._ConfigurationDeprecationWarning: user configuration file problems
  • login._PasswordFileWarning: password file problems
  • ArgumentDeprecationWarning: command line argument problems
  • FamilyMaintenanceWarning: missing information in family definition
exception pywikibot.exceptions.ArgumentDeprecationWarning[source]

Bases: UserWarning

Command line argument that is no longer supported.

__module__ = 'pywikibot.exceptions'
exception pywikibot.exceptions.ArticleExistsConflict(page, message=None)[source]

Bases: pywikibot.exceptions.EditConflict

Page already exists.

__module__ = 'pywikibot.exceptions'
message = 'Destination article %s already exists and is not a redirect to the source article'
exception pywikibot.exceptions.AutoblockUser(arg)[source]

Bases: pywikibot.exceptions.Error

Requested action on a virtual autoblock user not valid.

The class AutoblockUserError is an exception that is raised whenever an action is requested on a virtual autoblock user that’s not available for him (i.e. roughly everything except unblock).

__module__ = 'pywikibot.exceptions'
exception pywikibot.exceptions.BadTitle(arg)[source]

Bases: pywikibot.exceptions.Error

Server responded with BadTitle.

__module__ = 'pywikibot.exceptions'
exception pywikibot.exceptions.CaptchaError(arg)[source]

Bases: pywikibot.exceptions.Error

Captcha is asked and config.solve_captcha == False.

__module__ = 'pywikibot.exceptions'
exception pywikibot.exceptions.CascadeLockedPage(page, message=None)[source]

Bases: pywikibot.exceptions.LockedPage

Page is locked due to cascading protection.

__module__ = 'pywikibot.exceptions'
message = 'Page %s is locked due to cascading protection.'
exception pywikibot.exceptions.CircularRedirect(page, message=None)[source]

Bases: pywikibot.exceptions.PageRelatedError

Page is a circular redirect.

Exception argument is the redirect target; this may be the same title as this page or a different title (in which case the target page directly or indirectly redirects back to this one)

__module__ = 'pywikibot.exceptions'
message = 'Page %s is a circular redirect.'
exception pywikibot.exceptions.CoordinateGlobeUnknownException(arg)[source]

Bases: pywikibot.exceptions.WikiBaseError, NotImplementedError

This globe is not implemented yet in either WikiBase or pywikibot.

__module__ = 'pywikibot.exceptions'
exception pywikibot.exceptions.EditConflict(page, message=None)[source]

Bases: pywikibot.exceptions.PageSaveRelatedError

There has been an edit conflict while uploading the page.

__module__ = 'pywikibot.exceptions'
message = 'Page %s could not be saved due to an edit conflict'
exception pywikibot.exceptions.EntityTypeUnknownException(arg)[source]

Bases: pywikibot.exceptions.WikiBaseError

The requested entity type is not recognised on this site.

__module__ = 'pywikibot.exceptions'
exception pywikibot.exceptions.Error(arg)[source]

Bases: pywikibot.tools.UnicodeMixin, Exception

Pywikibot error.

__init__(arg)[source]

Initializer.

__module__ = 'pywikibot.exceptions'
__unicode__()[source]

Return a unicode string representation.

exception pywikibot.exceptions.FamilyMaintenanceWarning[source]

Bases: UserWarning

Family class is missing definitions.

__module__ = 'pywikibot.exceptions'
exception pywikibot.exceptions.FatalServerError(arg)[source]

Bases: pywikibot.exceptions.ServerError

A fatal server error will not be corrected by resending the request.

__module__ = 'pywikibot.exceptions'
exception pywikibot.exceptions.HiddenKeyError(arg)[source]

Bases: pywikibot.exceptions.UserRightsError, KeyError

Insufficient user rights to view the hidden key.

__module__ = 'pywikibot.exceptions'
exception pywikibot.exceptions.InconsistentTitleReceived(page, actual)[source]

Bases: pywikibot.exceptions.PageLoadRelatedError

Page receives a title inconsistent with query.

__init__(page, actual)[source]

Initializer.

Parameters:
  • page (Page object) – Page that caused the exception
  • actual – title obtained by query
__module__ = 'pywikibot.exceptions'
exception pywikibot.exceptions.InterwikiRedirectPage(page, target_page)[source]

Bases: pywikibot.exceptions.PageRelatedError

Page is a redirect to another site.

This is considered invalid in Pywikibot. See bug T75184.

__init__(page, target_page)[source]

Initializer.

Parameters:target_page – Target page of the redirect.
__module__ = 'pywikibot.exceptions'
message = 'Page redirects to a page on another Site.\nPage: %(page)s\nTarget page: %(target_page)s on %(target_site)s.'
exception pywikibot.exceptions.InvalidTitle(arg)[source]

Bases: pywikibot.exceptions.Error

Invalid page title.

__module__ = 'pywikibot.exceptions'
exception pywikibot.exceptions.IsNotRedirectPage(page, message=None)[source]

Bases: pywikibot.exceptions.PageRelatedError

Page is not a redirect page.

__module__ = 'pywikibot.exceptions'
message = 'Page %s is not a redirect page.'
exception pywikibot.exceptions.IsRedirectPage(page, message=None)[source]

Bases: pywikibot.exceptions.PageRelatedError

Page is a redirect page.

__module__ = 'pywikibot.exceptions'
message = 'Page %s is a redirect page.'
exception pywikibot.exceptions.LockedNoPage(page, message=None)[source]

Bases: pywikibot.exceptions.LockedPage

Title is locked against creation.

__module__ = 'pywikibot.exceptions'
message = 'Page %s does not exist and is locked preventing creation.'
exception pywikibot.exceptions.LockedPage(page, message=None)[source]

Bases: pywikibot.exceptions.PageSaveRelatedError

Page is locked.

__module__ = 'pywikibot.exceptions'
message = 'Page %s is locked.'
exception pywikibot.exceptions.NoCreateError(page, message=None)[source]

Bases: pywikibot.exceptions.PageSaveRelatedError

Parameter nocreate doesn’t allow page creation.

__module__ = 'pywikibot.exceptions'
message = 'Page %s could not be created due to parameter nocreate'
exception pywikibot.exceptions.NoMoveTarget(page, message=None)[source]

Bases: pywikibot.exceptions.PageRelatedError

Expected move target page not found.

__module__ = 'pywikibot.exceptions'
message = 'Move target page of %s not found.'
exception pywikibot.exceptions.NoPage(page, message=None)[source]

Bases: pywikibot.exceptions.PageRelatedError

Page does not exist.

__module__ = 'pywikibot.exceptions'
message = "Page %s doesn't exist."
pywikibot.exceptions.NoSuchSite

alias of pywikibot.exceptions.SiteDefinitionError

exception pywikibot.exceptions.NoUsername(arg)[source]

Bases: pywikibot.exceptions.Error

Username is not in user-config.py.

__module__ = 'pywikibot.exceptions'
exception pywikibot.exceptions.NotEmailableError(page, message=None)[source]

Bases: pywikibot.exceptions.PageRelatedError

This user is not emailable.

__module__ = 'pywikibot.exceptions'
message = '%s is not emailable.'
exception pywikibot.exceptions.NotImplementedWarning[source]

Bases: pywikibot.tools._NotImplementedWarning

Feature that is no longer implemented.

__module__ = 'pywikibot.exceptions'
exception pywikibot.exceptions.OtherPageSaveError(page, reason)[source]

Bases: pywikibot.exceptions.PageSaveRelatedError

Saving the page has failed due to uncatchable error.

__init__(page, reason)[source]

Initializer.

Parameters:reason (Exception or basestring) – Details of the problem
__module__ = 'pywikibot.exceptions'
args

Expose args.

message = 'Edit to page %(title)s failed:\n%(reason)s'
exception pywikibot.exceptions.PageCreatedConflict(page, message=None)[source]

Bases: pywikibot.exceptions.EditConflict

Page was created by another user.

__module__ = 'pywikibot.exceptions'
message = 'Page %s has been created since last retrieved.'
exception pywikibot.exceptions.PageDeletedConflict(page, message=None)[source]

Bases: pywikibot.exceptions.EditConflict

Page was deleted since being retrieved.

__module__ = 'pywikibot.exceptions'
message = 'Page %s has been deleted since last retrieved.'
exception pywikibot.exceptions.PageLoadRelatedError(page, message=None)[source]

Bases: pywikibot.exceptions.PageRelatedError

Loading the contents of a Page object has failed.

__module__ = 'pywikibot.exceptions'
message = 'Page %s was not loaded.'
pywikibot.exceptions.PageNotSaved

alias of pywikibot.exceptions.PageSaveRelatedError

exception pywikibot.exceptions.PageRelatedError(page, message=None)[source]

Bases: pywikibot.exceptions.Error

Abstract Exception, used when the exception concerns a particular Page.

This class should be used when the Exception concerns a particular Page, and when a generic message can be written once for all.

__init__(page, message=None)[source]

Initializer.

Parameters:page (Page object) – Page that caused the exception
__module__ = 'pywikibot.exceptions'
getPage()[source]

Return the page related to the exception.

message = None
exception pywikibot.exceptions.PageSaveRelatedError(page, message=None)[source]

Bases: pywikibot.exceptions.PageRelatedError

Saving the page has failed.

__module__ = 'pywikibot.exceptions'
args

Expose args.

message = 'Page %s was not saved.'
exception pywikibot.exceptions.SectionError(arg)[source]

Bases: pywikibot.exceptions.Error

The section specified by # does not exist.

__module__ = 'pywikibot.exceptions'
exception pywikibot.exceptions.Server414Error(arg)[source]

Bases: pywikibot.exceptions.ServerError

Server returned with HTTP 414 code.

__module__ = 'pywikibot.exceptions'
exception pywikibot.exceptions.Server504Error(arg)[source]

Bases: pywikibot.exceptions.ServerError

Server timed out with HTTP 504 code.

__module__ = 'pywikibot.exceptions'
exception pywikibot.exceptions.ServerError(arg)[source]

Bases: pywikibot.exceptions.Error

Got unexpected server response.

__module__ = 'pywikibot.exceptions'
exception pywikibot.exceptions.SiteDefinitionError(arg)[source]

Bases: pywikibot.exceptions.Error

Site does not exist.

__module__ = 'pywikibot.exceptions'
exception pywikibot.exceptions.SpamfilterError(page, url)[source]

Bases: pywikibot.exceptions.PageSaveRelatedError

Page save failed because MediaWiki detected a blacklisted spam URL.

__init__(page, url)[source]

Initializer.

__module__ = 'pywikibot.exceptions'
message = 'Edit to page %(title)s rejected by spam filter due to content:\n%(url)s'
exception pywikibot.exceptions.TimeoutError(arg)[source]

Bases: pywikibot.exceptions.Error

Request failed with a timeout error.

__module__ = 'pywikibot.exceptions'
exception pywikibot.exceptions.TitleblacklistError(page, message=None)[source]

Bases: pywikibot.exceptions.PageSaveRelatedError

Page save failed because MediaWiki detected a blacklisted page title.

__module__ = 'pywikibot.exceptions'
message = 'Page %s is title-blacklisted.'
exception pywikibot.exceptions.UnknownExtension(arg)[source]

Bases: pywikibot.exceptions.Error, NotImplementedError

Extension is not defined.

__module__ = 'pywikibot.exceptions'
exception pywikibot.exceptions.UnknownFamily(arg)[source]

Bases: pywikibot.exceptions.SiteDefinitionError

Family is not registered.

__module__ = 'pywikibot.exceptions'
exception pywikibot.exceptions.UnknownSite(arg)[source]

Bases: pywikibot.exceptions.SiteDefinitionError

Site does not exist in Family.

__module__ = 'pywikibot.exceptions'
exception pywikibot.exceptions.UnsupportedPage(page, message=None)[source]

Bases: pywikibot.exceptions.PageRelatedError

Unsupported page due to namespace restriction.

__module__ = 'pywikibot.exceptions'
message = 'Page %s is not supported due to namespace restriction.'
exception pywikibot.exceptions.UserBlocked(arg)[source]

Bases: pywikibot.exceptions.Error

Your username or IP has been blocked.

__module__ = 'pywikibot.exceptions'
exception pywikibot.exceptions.UserRightsError(arg)[source]

Bases: pywikibot.exceptions.Error

Insufficient user rights to perform an action.

__module__ = 'pywikibot.exceptions'
exception pywikibot.exceptions.WikiBaseError(arg)[source]

Bases: pywikibot.exceptions.Error

Wikibase related error.

__module__ = 'pywikibot.exceptions'

pywikibot.family module

Objects representing MediaWiki families.

pywikibot.family.AutoFamily(name, url, site=NotImplemented)[source]

Family that automatically loads the site configuration.

Parameters:
  • name (str) – Name for the family
  • url (str) – API endpoint URL of the wiki
Returns:

Generated family class

Return type:

SingleSiteFamily

class pywikibot.family.Family[source]

Bases: object

Parent singleton class for all wiki families.

__eq__(other)[source]

Compare self with other.

If other is not a Family() object, try to create one.

__getattribute__(name)[source]

Check if attribute is deprecated and warn accordingly.

This is necessary as subclasses could prevent that message by using a class variable. Only penalize getting it because it must be set so that the backwards compatibility is still available.

__hash__()[source]

Return hash(self).

__module__ = 'pywikibot.family'
__ne__(other)[source]

Return self!=value.

static __new__(cls)[source]

Allocator.

__repr__()[source]

Return repr(self).

__str__()[source]

Return str(self).

alphabetic = ['ace', 'kbd', 'ady', 'af', 'ak', 'als', 'am', 'ang', 'ab', 'ar', 'an', 'arc', 'roa-rup', 'frp', 'as', 'ast', 'atj', 'gn', 'av', 'ay', 'az', 'bm', 'bn', 'bjn', 'zh-min-nan', 'nan', 'map-bms', 'ba', 'be', 'be-tarask', 'bh', 'bcl', 'bi', 'bg', 'bar', 'bo', 'bs', 'br', 'bxr', 'ca', 'cv', 'ceb', 'cs', 'ch', 'cbk-zam', 'ny', 'sn', 'tum', 'cho', 'co', 'cy', 'da', 'dk', 'pdc', 'de', 'dv', 'nv', 'dsb', 'dty', 'dz', 'mh', 'et', 'el', 'eml', 'en', 'myv', 'es', 'eo', 'ext', 'eu', 'ee', 'fa', 'hif', 'fo', 'fr', 'fy', 'ff', 'fur', 'ga', 'gv', 'gag', 'gd', 'gl', 'gan', 'ki', 'glk', 'gu', 'gor', 'got', 'hak', 'xal', 'ko', 'ha', 'haw', 'hy', 'hi', 'ho', 'hsb', 'hr', 'hyw', 'io', 'ig', 'ilo', 'inh', 'bpy', 'id', 'ia', 'ie', 'iu', 'ik', 'os', 'xh', 'zu', 'is', 'it', 'he', 'jv', 'kbp', 'kl', 'kn', 'kr', 'pam', 'krc', 'ka', 'ks', 'csb', 'kk', 'kw', 'rw', 'rn', 'sw', 'kv', 'kg', 'gom', 'ht', 'ku', 'kj', 'ky', 'mrj', 'lad', 'lbe', 'lo', 'ltg', 'la', 'lv', 'lb', 'lez', 'lfn', 'lt', 'lij', 'li', 'ln', 'olo', 'jbo', 'lg', 'lmo', 'lrc', 'hu', 'mai', 'mk', 'mg', 'ml', 'mt', 'mi', 'mr', 'xmf', 'arz', 'mzn', 'ms', 'min', 'cdo', 'mwl', 'mdf', 'mo', 'mn', 'mus', 'my', 'nah', 'na', 'fj', 'nl', 'nds-nl', 'cr', 'ne', 'new', 'ja', 'nap', 'ce', 'frr', 'pih', 'no', 'nb', 'nn', 'nrm', 'nov', 'ii', 'oc', 'mhr', 'or', 'om', 'ng', 'hz', 'uz', 'pa', 'pi', 'pfl', 'pag', 'pnb', 'pap', 'ps', 'jam', 'koi', 'km', 'pcd', 'pms', 'tpi', 'nds', 'pl', 'pnt', 'pt', 'aa', 'kaa', 'crh', 'ty', 'ksh', 'ro', 'rmy', 'rm', 'qu', 'rue', 'ru', 'sah', 'se', 'sm', 'sa', 'sg', 'sat', 'sc', 'sco', 'stq', 'st', 'nso', 'tn', 'sq', 'scn', 'si', 'simple', 'sd', 'ss', 'sk', 'sl', 'cu', 'szl', 'so', 'ckb', 'srn', 'sr', 'sh', 'su', 'fi', 'sv', 'tl', 'shn', 'ta', 'kab', 'roa-tara', 'tt', 'te', 'tet', 'th', 'ti', 'tg', 'to', 'chr', 'chy', 've', 'tcy', 'tr', 'azb', 'tk', 'tw', 'tyv', 'din', 'udm', 'bug', 'uk', 'ur', 'ug', 'za', 'vec', 'vep', 'vi', 'vo', 'fiu-vro', 'wa', 'zh-classical', 'vls', 'war', 'wo', 'wuu', 'ts', 'yi', 'yo', 'zh-yue', 'diq', 'zea', 'bat-smg', 'zh', 'zh-tw', 'zh-cn']
alphabetic_revised = ['ace', 'ady', 'kbd', 'af', 'ak', 'als', 'am', 'ang', 'ab', 'ar', 'an', 'arc', 'roa-rup', 'frp', 'as', 'ast', 'atj', 'gn', 'av', 'ay', 'az', 'bjn', 'id', 'ms', 'bm', 'bn', 'zh-min-nan', 'nan', 'map-bms', 'jv', 'su', 'ba', 'min', 'be', 'be-tarask', 'bh', 'bcl', 'bi', 'bar', 'bo', 'bs', 'br', 'bug', 'bg', 'bxr', 'ca', 'ceb', 'cv', 'cs', 'ch', 'cbk-zam', 'ny', 'sn', 'tum', 'cho', 'co', 'cy', 'da', 'dk', 'pdc', 'de', 'dv', 'nv', 'dsb', 'na', 'dty', 'dz', 'mh', 'et', 'el', 'eml', 'en', 'myv', 'es', 'eo', 'ext', 'eu', 'ee', 'fa', 'hif', 'fo', 'fr', 'fy', 'ff', 'fur', 'ga', 'gv', 'sm', 'gag', 'gd', 'gl', 'gan', 'ki', 'glk', 'gu', 'got', 'hak', 'xal', 'ko', 'ha', 'haw', 'hy', 'hi', 'ho', 'hsb', 'hr', 'hyw', 'io', 'ig', 'ilo', 'inh', 'bpy', 'ia', 'ie', 'iu', 'ik', 'os', 'xh', 'zu', 'is', 'it', 'he', 'kl', 'kn', 'kr', 'pam', 'ka', 'ks', 'csb', 'kk', 'kw', 'rw', 'ky', 'rn', 'mrj', 'sw', 'kv', 'kg', 'gom', 'gor', 'ht', 'ku', 'shn', 'kj', 'lad', 'lbe', 'lez', 'lfn', 'lo', 'la', 'ltg', 'lv', 'to', 'lb', 'lt', 'lij', 'li', 'ln', 'olo', 'jbo', 'lg', 'lmo', 'lrc', 'hu', 'mai', 'mk', 'mg', 'ml', 'krc', 'mt', 'mi', 'mr', 'xmf', 'arz', 'mzn', 'cdo', 'mwl', 'koi', 'mdf', 'mo', 'mn', 'mus', 'my', 'nah', 'fj', 'nl', 'nds-nl', 'cr', 'ne', 'new', 'ja', 'nap', 'ce', 'frr', 'pih', 'no', 'nb', 'nn', 'nrm', 'nov', 'ii', 'oc', 'mhr', 'or', 'om', 'ng', 'hz', 'uz', 'pa', 'pi', 'pfl', 'pag', 'pnb', 'pap', 'ps', 'jam', 'km', 'pcd', 'pms', 'nds', 'pl', 'pnt', 'pt', 'aa', 'kaa', 'crh', 'ty', 'ksh', 'ro', 'rmy', 'rm', 'qu', 'ru', 'rue', 'sah', 'se', 'sa', 'sg', 'sat', 'sc', 'sco', 'stq', 'st', 'nso', 'tn', 'sq', 'scn', 'si', 'simple', 'sd', 'ss', 'sk', 'sl', 'cu', 'szl', 'so', 'ckb', 'srn', 'sr', 'sh', 'fi', 'sv', 'tl', 'ta', 'kab', 'kbp', 'roa-tara', 'tt', 'te', 'tet', 'th', 'vi', 'ti', 'tg', 'tpi', 'chr', 'chy', 've', 'tcy', 'tr', 'azb', 'tk', 'tw', 'tyv', 'din', 'udm', 'uk', 'ur', 'ug', 'za', 'vec', 'vep', 'vo', 'fiu-vro', 'wa', 'zh-classical', 'vls', 'war', 'wo', 'wuu', 'ts', 'yi', 'yo', 'zh-yue', 'diq', 'zea', 'bat-smg', 'zh', 'zh-tw', 'zh-cn']
apipath(code)[source]

Return path to api.php.

archived_page_templates = {}
base_url(code, uri, protocol=None)[source]

Prefix uri with port and hostname.

Parameters:
  • code (str) – The site code
  • uri (str) – The absolute path after the hostname
  • protocol – The protocol which is used. If None it’ll determine the protocol from the code.
Returns:

The full URL ending with uri

Return type:

str

categories_last = []
category_attop = []
category_on_one_line = []
category_redirect_templates = {'_default': []}
category_redirects(code, fallback='_default')[source]

Return list of category redirect templates.

category_text_separator = '\n\n'
code2encoding(code)[source]

Return the encoding for a specific language wiki.

code2encodings(code)[source]

Return list of historical encodings for a specific language Wiki.

codes

Get list of codes used by this family.

Return type:iterable of str
cross_allowed = []
cross_projects = []
cross_projects_cookies = ['centralauth_Session', 'centralauth_Token', 'centralauth_User']
crossnamespace = {}
dbName(code)[source]

Return the name of the MySQL database.

disambcatname = {}
disambig(code, fallback='_default')[source]

Return list of disambiguation templates.

disambiguationTemplates = {'_default': []}
domains

Get list of unique domain names included in this family.

These domains may also exist in another family.

Return type:iterable of str
edit_restricted_templates = {}
encoding(code)[source]

Return the encoding for a specific language Wiki.

encodings(code)[source]

Return list of historical encodings for a specific language Wiki.

eventstreams_host(code)[source]

Hostname for EventStreams.

eventstreams_path(code)[source]

Return path for EventStreams.

force_version(code)[source]

Return a manual version number.

The site is usually using the version number from the servers’ siteinfo, but if there is a problem with that it’s possible to return a non-empty string here representing another version number.

For example, pywikibot.tools.MediaWikiVersion treats version numbers ending with ‘alpha’, ‘beta’ or ‘rc’ as newer than any version ending with ‘wmf<number>’. But if that causes breakage it’s possible to override it here to a version number which doesn’t cause breakage.

Returns:A version number which can be parsed using pywikibot.tools.MediaWikiVersion. If empty/None it uses the version returned via siteinfo.
Return type:str
from_url(url)[source]

Return whether this family matches the given url.

It is first checking if a domain of this family is in the the domain of the URL. If that is the case it’s checking all codes and verifies that a path generated via APISite.article_path and Family.path matches the path of the URL together with the hostname for that code.

It is using Family.domains to first check if a domain applies and then iterates over Family.codes to actually determine which code applies.

Parameters:

url (str) – the URL which may contain a $1. If it’s missing it is assumed to be at the end and if it’s present nothing is allowed after it.

Returns:

The language code of the url. None if that url is not from this family.

Return type:

str or None

Raises:
  • RuntimeError – When there are multiple languages in this family which would work with the given URL.
  • ValueError – When text is present after $1.
fyinterwiki = ['aa', 'ab', 'ace', 'ady', 'af', 'ay', 'ak', 'als', 'am', 'an', 'ang', 'ar', 'arc', 'arz', 'as', 'ast', 'atj', 'av', 'az', 'azb', 'ba', 'bar', 'bat-smg', 'bcl', 'be', 'be-tarask', 'bg', 'bh', 'bi', 'bjn', 'bm', 'bn', 'bo', 'bpy', 'br', 'bs', 'bug', 'bxr', 'ca', 'cbk-zam', 'cdo', 'ce', 'ceb', 'ch', 'chy', 'cho', 'chr', 'cy', 'ckb', 'co', 'cr', 'crh', 'cs', 'csb', 'cu', 'cv', 'da', 'de', 'din', 'diq', 'dk', 'dsb', 'dty', 'dv', 'dz', 'ee', 'el', 'eml', 'en', 'eo', 'es', 'et', 'eu', 'ext', 'fa', 'ff', 'fi', 'fy', 'fiu-vro', 'fj', 'fo', 'fr', 'frp', 'frr', 'fur', 'ga', 'gag', 'gan', 'gd', 'gl', 'glk', 'gn', 'gom', 'gor', 'got', 'gu', 'gv', 'ha', 'hak', 'haw', 'he', 'hi', 'hy', 'hif', 'hyw', 'ho', 'hr', 'hsb', 'ht', 'hu', 'hz', 'ia', 'id', 'ie', 'ig', 'ii', 'yi', 'ik', 'ilo', 'inh', 'io', 'yo', 'is', 'it', 'iu', 'ja', 'jam', 'jbo', 'jv', 'ka', 'kaa', 'kab', 'kbd', 'kbp', 'kg', 'ki', 'ky', 'kj', 'kk', 'kl', 'km', 'kn', 'ko', 'koi', 'kr', 'krc', 'ks', 'ksh', 'ku', 'kv', 'kw', 'la', 'lad', 'lb', 'lbe', 'lez', 'lfn', 'lg', 'li', 'lij', 'lmo', 'ln', 'lo', 'lrc', 'lt', 'ltg', 'lv', 'mai', 'map-bms', 'mdf', 'mg', 'mh', 'mhr', 'mi', 'my', 'min', 'myv', 'mk', 'ml', 'mn', 'mo', 'mr', 'mrj', 'ms', 'mt', 'mus', 'mwl', 'mzn', 'na', 'nah', 'nan', 'nap', 'nds', 'nds-nl', 'ne', 'new', 'ng', 'ny', 'nl', 'nn', 'no', 'nov', 'nrm', 'nso', 'nv', 'oc', 'olo', 'om', 'or', 'os', 'pa', 'pag', 'pam', 'pap', 'pcd', 'pdc', 'pfl', 'pi', 'pih', 'pl', 'pms', 'pnb', 'pnt', 'ps', 'pt', 'qu', 'rm', 'rmy', 'rn', 'ro', 'roa-rup', 'roa-tara', 'ru', 'rue', 'rw', 'sa', 'sah', 'sat', 'sc', 'scn', 'sco', 'sd', 'se', 'sg', 'sh', 'shn', 'si', 'simple', 'sk', 'sl', 'sm', 'sn', 'so', 'sq', 'sr', 'srn', 'ss', 'st', 'stq', 'su', 'sv', 'sw', 'szl', 'ta', 'tcy', 'te', 'tet', 'tg', 'th', 'ti', 'ty', 'tyv', 'tk', 'tl', 'tn', 'to', 'tpi', 'tr', 'ts', 'tt', 'tum', 'tw', 'udm', 'ug', 'uk', 'ur', 'uz', 've', 'vec', 'vep', 'vi', 'vls', 'vo', 'wa', 'war', 'wo', 'wuu', 'xal', 'xh', 'xmf', 'za', 'zea', 'zh', 'zh-classical', 'zh-cn', 'zh-yue', 'zh-min-nan', 'zh-tw', 'zu']
get_address(code, title, name='[deprecated name of title]')[source]

Return the path to title using index.php with redirects disabled.

hostname(code)[source]

The hostname to use for standard http connections.

ignore_certificate_error(code)[source]

Return whether a HTTPS certificate error should be ignored.

Parameters:code (str) – language code
Returns:flag to allow access if certificate has an error.
Return type:bool
instance

Get the singleton instance.

interface(code)[source]

Return interface to use for code.

Return type:str or subclass of BaseSite
interwiki_attop = []
interwiki_forward = None
interwiki_forwarded_from = {}
interwiki_on_one_line = []
interwiki_putfirst = {}
interwiki_removals = []
interwiki_replacements = {}
interwiki_text_separator = '\n\n'
isPublic(code)[source]

Check the wiki require logging in before viewing it.

known_families = {'acronym': 'acronym', 'advisory': 'advisory', 'advogato': 'advogato', 'aew': 'aew', 'appropedia': 'appropedia', 'aquariumwiki': 'aquariumwiki', 'arborwiki': 'arborwiki', 'arxiv': 'arxiv', 'atmwiki': 'atmwiki', 'b': 'wikibooks', 'baden': 'baden', 'battlestarwiki': 'battlestarwiki', 'bcnbio': 'bcnbio', 'beacha': 'beacha', 'betawiki': 'translatewiki', 'betawikiversity': 'betawikiversity', 'bibcode': 'bibcode', 'bibliowiki': 'bibliowiki', 'bluwiki': 'bluwiki', 'blw': 'blw', 'botwiki': 'botwiki', 'boxrec': 'boxrec', 'brickwiki': 'brickwiki', 'bugzilla': 'bugzilla', 'bulba': 'bulba', 'c': 'commons', 'c2': 'c2', 'c2find': 'c2find', 'cellwiki': 'cellwiki', 'centralwikia': 'centralwikia', 'chapter': 'wikimedia', 'chej': 'chej', 'choralwiki': 'choralwiki', 'citizendium': 'citizendium', 'ckwiss': 'ckwiss', 'comixpedia': 'comixpedia', 'commons': 'commons', 'communityscheme': 'communityscheme', 'comune': 'comune', 'creativecommonswiki': 'creativecommonswiki', 'cxej': 'cxej', 'dbdump': 'dbdump', 'dcc': 'dcc', 'dcdatabase': 'dcdatabase', 'dcma': 'dcma', 'debian': 'debian', 'devmo': 'devmo', 'dict': 'dictionary', 'dictionary': 'dictionary', 'disinfopedia': 'disinfopedia', 'distributedproofreaders': 'distributedproofreaders', 'distributedproofreadersca': 'distributedproofreadersca', 'dk': 'dk', 'dmoz': 'dmoz', 'dmozs': 'dmozs', 'doom_wiki': 'doom_wiki', 'download': 'download', 'dpd': 'dpd', 'drae': 'drae', 'dreamhost': 'dreamhost', 'drumcorpswiki': 'drumcorpswiki', 'dwjwiki': 'dwjwiki', 'ecoreality': 'ecoreality', 'ecxei': 'ecxei', 'elibre': 'elibre', 'emacswiki': 'emacswiki', 'encyc': 'encyc', 'energiewiki': 'energiewiki', 'englyphwiki': 'englyphwiki', 'enkol': 'enkol', 'eokulturcentro': 'eokulturcentro', 'esolang': 'esolang', 'etherpad': 'etherpad', 'evowiki': 'evowiki', 'exotica': 'exotica', 'eĉei': 'eĉei', 'fanimutationwiki': 'fanimutationwiki', 'finalfantasy': 'finalfantasy', 'finnix': 'finnix', 'floralwiki': 'floralwiki', 'foldoc': 'foldoc', 'foundation': 'wikimedia', 'foundationsite': 'foundationsite', 'foxwiki': 'foxwiki', 'freebio': 'freebio', 'freebsdman': 'freebsdman', 'freeculturewiki': 'freeculturewiki', 'freedomdefined': 'freedomdefined', 'freefeel': 'freefeel', 'freekiwiki': 'freekiwiki', 'ganfyd': 'ganfyd', 'gardenology': 'gardenology', 'gausswiki': 'gausswiki', 'gentoo': 'gentoo', 'genwiki': 'genwiki', 'gerrit': 'gerrit', 'git': 'git', 'google': 'google', 'googledefine': 'googledefine', 'googlegroups': 'googlegroups', 'guc': 'guc', 'gucprefix': 'guc', 'guildwiki': 'guildwiki', 'gutenberg': 'gutenberg', 'gutenbergwiki': 'gutenbergwiki', 'h2wiki': 'h2wiki', 'hackerspaces': 'hackerspaces', 'hammondwiki': 'hammondwiki', 'hdl': 'hdl', 'heraldik': 'heraldik', 'heroeswiki': 'heroeswiki', 'horizonlabs': 'horizonlabs', 'hrfwiki': 'hrfwiki', 'hrwiki': 'hrwiki', 'hupwiki': 'hupwiki', 'iarchive': 'iarchive', 'imdbcharacter': 'imdbcharacter', 'imdbcompany': 'imdbcompany', 'imdbname': 'imdbname', 'imdbtitle': 'imdbtitle', 'incubator': 'incubator', 'infosecpedia': 'infosecpedia', 'infosphere': 'infosphere', 'irc': 'irc', 'ircs': 'ircs', 'iso639-3': 'iso639-3', 'issn': 'issn', 'iuridictum': 'iuridictum', 'jaglyphwiki': 'jaglyphwiki', 'javanet': 'javanet', 'javapedia': 'javapedia', 'jefo': 'jefo', 'jerseydatabase': 'jerseydatabase', 'jira': 'jira', 'jspwiki': 'jspwiki', 'jstor': 'jstor', 'kamelo': 'kamelo', 'karlsruhe': 'karlsruhe', 'kinowiki': 'kinowiki', 'komicawiki': 'komicawiki', 'kontuwiki': 'kontuwiki', 'labsconsole': 'labsconsole', 'libreplanet': 'libreplanet', 'linguistlist': 'linguistlist', 'linuxwiki': 'linuxwiki', 'linuxwikide': 'linuxwikide', 'liswiki': 'liswiki', 'literateprograms': 'literateprograms', 'livepedia': 'livepedia', 'localwiki': 'localwiki', 'lojban': 'lojban', 'lostpedia': 'lostpedia', 'lqwiki': 'lqwiki', 'lugkr': 'lugkr', 'luxo': 'luxo', 'm': 'meta', 'm-w': 'm-w', 'mail': 'mail', 'mailarchive': 'mailarchive', 'mariowiki': 'mariowiki', 'marveldatabase': 'marveldatabase', 'meatball': 'meatball', 'mediazilla': 'mediazilla', 'memoryalpha': 'memoryalpha', 'meta': 'metawiki', 'metawiki': 'metawiki', 'metawikimedia': 'metawiki', 'metawikipedia': 'metawiki', 'metawikisearch': 'metawikisearch', 'mineralienatlas': 'mineralienatlas', 'moinmoin': 'moinmoin', 'monstropedia': 'monstropedia', 'mosapedia': 'mosapedia', 'mozcom': 'mozcom', 'mozillawiki': 'mozillawiki', 'mozillazinekb': 'mozillazinekb', 'musicbrainz': 'musicbrainz', 'mw': 'mediawiki', 'mwod': 'mwod', 'mwot': 'mwot', 'n': 'wikinews', 'nara': 'nara', 'nkcells': 'nkcells', 'nosmoke': 'nosmoke', 'nost': 'nost', 'nostalgia': 'nostalgia', 'oeis': 'oeis', 'oldwikisource': 'oldwikisource', 'olpc': 'olpc', 'omegawiki': 'omegawiki', 'onelook': 'onelook', 'openlibrary': 'openlibrary', 'openstreetmap': 'openstreetmap', 'openwetware': 'openwetware', 'opera7wiki': 'opera7wiki', 'organicdesign': 'organicdesign', 'orthodoxwiki': 'orthodoxwiki', 'otrs': 'otrs', 'otrswiki': 'otrswiki', 'ourmedia': 'ourmedia', 'outreach': 'outreach', 'outreachwiki': 'outreach', 'owasp': 'owasp', 'panawiki': 'panawiki', 'patwiki': 'patwiki', 'personaltelco': 'personaltelco', 'petscan': 'petscan', 'phab': 'phabricator', 'phabricator': 'phabricator', 'phpwiki': 'phpwiki', 'phwiki': 'phwiki', 'planetmath': 'planetmath', 'pmeg': 'pmeg', 'pmid': 'pmid', 'pokewiki': 'pokewiki', 'pokéwiki': 'pokewiki', 'policy': 'policy', 'psycle': 'psycle', 'purlnet': 'purlnet', 'pyrev': 'pyrev', 'pythonwiki': 'pythonwiki', 'pywiki': 'pywiki', 'q': 'wikiquote', 'quality': 'quality', 'quarry': 'quarry', 'rcirc': 'rcirc', 'reuterswiki': 'reuterswiki', 'rev': 'rev', 'revo': 'revo', 'rheinneckar': 'rheinneckar', 'robowiki': 'robowiki', 'rodovid': 'rodovid', 'rowiki': 'rowiki', 'rt': 'rt', 'rtfm': 'rtfm', 's': 'wikisource', 's23wiki': 's23wiki', 'schoolswp': 'schoolswp', 'scores': 'scores', 'scoutwiki': 'scoutwiki', 'scramble': 'scramble', 'seapig': 'seapig', 'seattlewiki': 'seattlewiki', 'securewikidc': 'securewikidc', 'senseislibrary': 'senseislibrary', 'silcode': 'silcode', 'slashdot': 'slashdot', 'slwiki': 'slwiki', 'sourceforge': 'sourceforge', 'spcom': 'spcom', 'species': 'species', 'squeak': 'squeak', 'stats': 'stats', 'stewardry': 'stewardry', 'strategy': 'strategy', 'strategywiki': 'strategywiki', 'sulutil': 'sulutil', 'svn': 'svn', 'swtrain': 'swtrain', 'tabwiki': 'tabwiki', 'tclerswiki': 'tclerswiki', 'technorati': 'technorati', 'tenwiki': 'tenwiki', 'test2wiki': 'test2wiki', 'testwiki': 'testwiki', 'testwikidata': 'testwikidata', 'tfwiki': 'tfwiki', 'thelemapedia': 'thelemapedia', 'theopedia': 'theopedia', 'thinkwiki': 'thinkwiki', 'ticket': 'ticket', 'tmbw': 'tmbw', 'tmnet': 'tmnet', 'tmwiki': 'tmwiki', 'toolforge': 'toollabs', 'toollabs': 'toollabs', 'translatewiki': 'translatewiki', 'tviv': 'tviv', 'tvtropes': 'tvtropes', 'twiki': 'twiki', 'tyvawiki': 'tyvawiki', 'umap': 'umap', 'uncyclopedia': 'uncyclopedia', 'unihan': 'unihan', 'unreal': 'unreal', 'urbandict': 'urbandict', 'usability': 'usability', 'usej': 'usej', 'usemod': 'usemod', 'utrs': 'utrs', 'v': 'wikiversity', 'viaf': 'viaf', 'vikidia': 'vikidia', 'vkol': 'vkol', 'vlos': 'vlos', 'voipinfo': 'voipinfo', 'votewiki': 'votewiki', 'voy': 'wikivoyage', 'w': 'wikipedia', 'werelate': 'werelate', 'wg': 'wg', 'wikia': 'wikia', 'wikiasite': 'wikia', 'wikibooks': 'wikibooks', 'wikichristian': 'wikichristian', 'wikicities': 'wikicities', 'wikicity': 'wikicity', 'wikiconference': 'wikiconference', 'wikidata': 'wikidata', 'wikif1': 'wikif1', 'wikifur': 'wikifur', 'wikihow': 'wikihow', 'wikiindex': 'wikiindex', 'wikilemon': 'wikilemon', 'wikilivres': 'wikilivres', 'wikimac-de': 'wikimac-de', 'wikimania': 'wikimania', 'wikimedia': 'wikimedia', 'wikinews': 'wikinews', 'wikinfo': 'wikinfo', 'wikinvest': 'wikinvest', 'wikipapers': 'wikipapers', 'wikipedia': 'wikipedia', 'wikipediawikipedia': 'wikipedia', 'wikiquote': 'wikiquote', 'wikiskripta': 'wikiscripta', 'wikisophia': 'wikisophoa', 'wikisource': 'wikisource', 'wikispecies': 'wikispecies', 'wikispot': 'wikispot', 'wikitech': 'wikitech', 'wikiti': 'wikiti', 'wikiversity': 'wikiversity', 'wikivoyage': 'wikivoyage', 'wikiwikiweb': 'wikiwikiweb', 'wikt': 'wiktionary', 'wiktionary': 'wiktionary', 'wipipedia': 'wipipedia', 'wlug': 'wlug', 'wm2005': 'wm2005', 'wm2006': 'wm2006', 'wm2007': 'wm2007', 'wm2008': 'wm2008', 'wm2009': 'wm2009', 'wm2010': 'wm2010', 'wm2011': 'wm2011', 'wm2012': 'wm2012', 'wm2013': 'wm2013', 'wm2014': 'wm2014', 'wm2015': 'wm2015', 'wm2016': 'wm2016', 'wm2017': 'wm2017', 'wm2018': 'wm2018', 'wmam': 'wmam', 'wmania': 'wikimania', 'wmar': 'wmar', 'wmat': 'wmat', 'wmau': 'wmau', 'wmbd': 'wmbd', 'wmbe': 'wmbe', 'wmbr': 'wmbr', 'wmca': 'wmca', 'wmch': 'wmch', 'wmcl': 'wmcl', 'wmcn': 'wmcn', 'wmco': 'wmco', 'wmcz': 'wmcz', 'wmdc': 'wmdc', 'wmdk': 'wmdk', 'wmec': 'wmec', 'wmee': 'wmee', 'wmes': 'wmes', 'wmet': 'wmet', 'wmf': 'wmf', 'wmfdashboard': 'wmfdashboard', 'wmfi': 'wmfi', 'wmfr': 'wmfr', 'wmhi': 'wmhi', 'wmhk': 'wmhk', 'wmid': 'wmid', 'wmil': 'wmil', 'wmin': 'wmin', 'wmit': 'wmit', 'wmke': 'wmke', 'wmmk': 'wmmk', 'wmmx': 'wmmx', 'wmnl': 'wmnl', 'wmno': 'wmno', 'wmnyc': 'wmnyc', 'wmpa-us': 'wmpa-us', 'wmph': 'wmph', 'wmpl': 'wmpl', 'wmpt': 'wmpt', 'wmpunjabi': 'wmpunjabi', 'wmromd': 'wmromd', 'wmrs': 'wmrs', 'wmru': 'wmru', 'wmse': 'wmse', 'wmsk': 'wmsk', 'wmteam': 'wmteam', 'wmtr': 'wmtr', 'wmtw': 'wmtw', 'wmua': 'wmua', 'wmuk': 'wmuk', 'wmve': 'wmve', 'wmza': 'wmza', 'wookieepedia': 'wookieepedia', 'wowwiki': 'wowwiki', 'wqy': 'wqy', 'wurmpedia': 'wurmpedia', 'zrhwiki': 'zrhwiki', 'zum': 'zum', 'zwiki': 'zwiki', 'Ĉej': 'Ĉej'}
langs = {}
language_groups = {'arab': ['ar', 'arz', 'ps', 'sd', 'ur', 'bjn', 'ckb', 'kk', 'ku', 'tt', 'ug', 'pnb'], 'chinese': ['wuu', 'zh', 'zh-classical', 'zh-yue', 'gan', 'ii', 'ja', 'za'], 'cyril': ['ab', 'av', 'ba', 'be', 'be-tarask', 'bg', 'bxr', 'ce', 'cu', 'cv', 'kbd', 'koi', 'kv', 'ky', 'mk', 'lbe', 'mdf', 'mn', 'mo', 'myv', 'mhr', 'mrj', 'os', 'ru', 'rue', 'sah', 'tg', 'tk', 'udm', 'uk', 'xal', 'ha', 'kk', 'sh', 'sr', 'tt'], 'grec': ['el', 'grc', 'pnt'], 'latin': ['aa', 'ace', 'af', 'ak', 'als', 'an', 'ang', 'ast', 'ay', 'bar', 'bat-smg', 'bcl', 'bi', 'bm', 'br', 'bs', 'ca', 'cbk-zam', 'cdo', 'ceb', 'ch', 'cho', 'chy', 'co', 'crh', 'cs', 'csb', 'cy', 'da', 'de', 'diq', 'dsb', 'ee', 'eml', 'en', 'eo', 'es', 'et', 'eu', 'ext', 'ff', 'fi', 'fiu-vro', 'fj', 'fo', 'fr', 'frp', 'frr', 'fur', 'fy', 'ga', 'gag', 'gd', 'gl', 'gn', 'gv', 'hak', 'haw', 'hif', 'ho', 'hr', 'hsb', 'ht', 'hu', 'hz', 'ia', 'id', 'ie', 'ig', 'ik', 'ilo', 'io', 'is', 'it', 'jbo', 'jv', 'kaa', 'kab', 'kg', 'ki', 'kj', 'kl', 'kr', 'ksh', 'kw', 'la', 'lad', 'lb', 'lg', 'li', 'lij', 'lmo', 'ln', 'lt', 'ltg', 'lv', 'map-bms', 'mg', 'mh', 'mi', 'ms', 'mt', 'mus', 'mwl', 'na', 'nah', 'nap', 'nds', 'nds-nl', 'ng', 'nl', 'nn', 'no', 'nov', 'nrm', 'nv', 'ny', 'oc', 'om', 'pag', 'pam', 'pap', 'pcd', 'pdc', 'pfl', 'pih', 'pl', 'pms', 'pt', 'qu', 'rm', 'rn', 'ro', 'roa-rup', 'roa-tara', 'rw', 'sc', 'scn', 'sco', 'se', 'sg', 'simple', 'sk', 'sl', 'sm', 'sn', 'so', 'sq', 'srn', 'ss', 'st', 'stq', 'su', 'sv', 'sw', 'szl', 'tet', 'tl', 'tn', 'to', 'tpi', 'tr', 'ts', 'tum', 'tw', 'ty', 'uz', 've', 'vec', 'vi', 'vls', 'vo', 'wa', 'war', 'wo', 'xh', 'yo', 'zea', 'zh-min-nan', 'zu', 'az', 'chr', 'ckb', 'ha', 'iu', 'kk', 'ku', 'rmy', 'sh', 'sr', 'tt', 'ug', 'za'], 'scand': ['da', 'fo', 'is', 'nb', 'nn', 'no', 'sv']}
languages_by_size = []
ldapDomain = ()
linktrail(code, fallback='_default')[source]

Return regex for trailing chars displayed as part of a link.

Returns a string, not a compiled regular expression object.

This reads from the family file, and not from [[MediaWiki:Linktrail]], because the MW software currently uses a built-in linktrail from its message files and ignores the wiki value.

linktrails = {'_default': '[a-z]*', 'ab': '[a-zабвгҕдежзӡикқҟлмнопҧрстҭуфхҳцҵчҷҽҿшыҩџьә]*', 'als': '[äöüßa-z]*', 'an': '[a-záéíóúñ]*', 'ar': '[a-zء-ي]*', 'arz': '[a-zء-ي]*', 'ast': '[a-záéíóúñ]*', 'atj': '[a-zàâçéèêîôûäëïöüùÇÉÂÊÎÔÛÄËÏÖÜÀÈÙ]*', 'av': '[a-zабвгдеёжзийклмнопрстуфхцчшщъыьэюя]*', 'ay': '[a-záéíóúñ]*', 'azb': '[ابپتثجچحخدذرزژسشصضطظعغفقکگلمنوهیآأئؤة\u200c]*', 'bar': '[äöüßa-z]*', 'bat-smg': '[a-ząčęėįšųūž]*', 'be': '[абвгґджзеёжзійклмнопрстуўфхцчшыьэюяćčłńśšŭźža-z]*', 'be-tarask': '[абвгґджзеёжзійклмнопрстуўфхцчшыьэюяćčłńśšŭźža-z]*', 'bg': '[a-zабвгдежзийклмнопрстуфхцчшщъыьэюя]*', 'bm': '[a-zàâçéèêîôûäëïöüùÇÉÂÊÎÔÛÄËÏÖÜÀÈÙ]*', 'bn': '[\u0980-\u09ff]*', 'bpy': '[\u0980-\u09ff]*', 'bs': '[a-zćčžšđž]*', 'bxr': '[a-zабвгдеёжзийклмнопрстуфхцчшщъыьэюя]*', 'ca': '[a-zàèéíòóúç·ïü]*', 'cbk-zam': '[a-záéíóúñ]*', 'ce': '[a-zабвгдеёжзийклмнопрстуфхцчшщъыьэюя]*', 'ckb': '[ئابپتجچحخدرڕزژسشعغفڤقکگلڵمنوۆهھەیێ\u200c]*', 'co': '[a-zàéèíîìóòúù]*', 'crh': '[a-zâçğıñöşüа-яёʺʹ“»]*', 'cs': '[a-záčďéěíňóřšťúůýž]*', 'csb': '[a-zęóąśłżźćńĘÓĄŚŁŻŹĆŃ]*', 'cu': '[a-zабвгдеєжѕзїіıићклмнопсстѹфхѡѿцчшщъыьѣюѥѧѩѫѭѯѱѳѷѵґѓђёјйљњќуўџэ҄я\uf011“»]*', 'cv': '[a-zа-яĕçăӳ"»]*', 'cy': '[àáâèéêìíîïòóôûŵŷa-z]*', 'da': '[a-zæøå]*', 'de': '[a-zäöüß]*', 'din': '[äëɛɛ̈éɣïŋöɔɔ̈óa-z]*', 'dsb': '[äöüßa-z]*', 'el': '[a-zαβγδεζηθικλμνξοπρστυφχψωςΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩάέήίόύώϊϋΐΰΆΈΉΊΌΎΏΪΫ]*', 'eml': '[a-zàéèíîìóòúù]*', 'es': '[a-záéíóúñ]*', 'et': '[äöõšüža-z]*', 'eu': '[a-záéíóúñ]*', 'ext': '[a-záéíóúñ]*', 'fa': '[ابپتثجچحخدذرزژسشصضطظعغفقکگلمنوهیآأئؤة\u200c]*', 'ff': '[a-zàâçéèêîôûäëïöüùÇÉÂÊÎÔÛÄËÏÖÜÀÈÙ]*', 'fi': '[a-zäö]*', 'fiu-vro': '[äöõšüža-z]*', 'fo': '[áðíóúýæøa-z]*', 'fr': '[a-zàâçéèêîôûäëïöüùÇÉÂÊÎÔÛÄËÏÖÜÀÈÙ]*', 'frp': '[a-zàâçéèêîœôû·’æäåāăëēïīòöōùü‘]*', 'frr': '[a-zäöüßåāđē]*', 'fur': '[a-zàéèíîìóòúù]*', 'fy': '[a-zàáèéìíòóùúâêîôûäëïöü]*', 'gag': '[a-zÇĞçğİıÖöŞşÜüÂâÎîÛû]*', 'gl': '[áâãàéêẽçíòóôõq̃úüűũa-z]*', 'glk': '[ابپتثجچحخدذرزژسشصضطظعغفقکگلمنوهیآأئؤة\u200c]*', 'gn': '[a-záéíóúñ]*', 'gu': '[\u0a80-\u0aff]*', 'he': '[a-zא-ת]*', 'hi': '[a-zऀ-ॣ०-꣠-\ua8ff]*', 'hr': '[čšžćđßa-z]*', 'hsb': '[äöüßa-z]*', 'ht': '[a-zàèòÀÈÒ]*', 'hu': '[a-záéíóúöüőűÁÉÍÓÚÖÜŐŰ]*', 'hy': '[a-zաբգդեզէըթժիլխծկհձղճմյնշոչպջռսվտրցւփքօֆև«»]*', 'inh': '[a-zабвгдеёжзийклмнопрстуфхцчшщъыьэюя]*', 'is': '[áðéíóúýþæöa-z-–]*', 'it': '[a-zàéèíîìóòúù]*', 'ka': '[a-zაბგდევზთიკლმნოპჟრსტუფქღყშჩცძწჭხჯჰ“»]*', 'kbp': '[a-zàâçéèêîôûäëïöüùÇÉÂÊÎÔÛÄËÏÖÜÀÈÙ]*', 'kk': '[a-zäçéğıïñöşüýʺʹа-яёәғіқңөұүһٴابپتجحدرزسشعفقكلمنڭەوۇۋۆىيچھ“»]*', 'kl': '[a-zæøå]*', 'koi': '[a-zабвгдеёжзийклмнопрстуфхцчшщъыьэюя]*', 'krc': '[a-zабвгдеёжзийклмнопрстуфхцчшщъыьэюя]*', 'ksh': '[a-zäöüėëijßəğåůæœç]*', 'ku': '[a-zçêîşûẍḧÇÊÎŞÛẌḦ]*', 'kv': '[a-zабвгдеёжзийклмнопрстуфхцчшщъыьэюя]*', 'lad': '[a-záéíóúñ]*', 'lb': '[äöüßa-z]*', 'lbe': '[a-zабвгдеёжзийклмнопрстуфхцчшщъыьэюяӀ1“»]*', 'lez': '[a-zабвгдеёжзийклмнопрстуфхцчшщъыьэюя]*', 'li': '[a-zäöüïëéèà]*', 'lij': '[a-zàéèíîìóòúù]*', 'lmo': '[a-zàéèíîìóòúù]*', 'ln': '[a-zàâçéèêîôûäëïöüùÇÉÂÊÎÔÛÄËÏÖÜÀÈÙ]*', 'lrc': '[ابپتثجچحخدذرزژسشصضطظعغفقکگلمنوهیآأئؤة\u200c]*', 'lt': '[a-ząčęėįšųūž]*', 'ltg': '[a-zA-ZĀāČčĒēĢģĪīĶķĻļŅņŠšŪūŽž]*', 'lv': '[a-zA-ZĀāČčĒēĢģĪīĶķĻļŅņŠšŪūŽž]*', 'mai': '[a-zऀ-ॣ०-꣠-\ua8ff]*', 'mdf': '[a-zабвгдеёжзийклмнопрстуфхцчшщъыьэюя]*', 'mg': '[a-zàâçéèêîôûäëïöüùÇÉÂÊÎÔÛÄËÏÖÜÀÈÙ]*', 'mhr': '[a-zабвгдеёжзийклмнопрстуфхцчшщъыьэюя]*', 'mk': '[a-zабвгдѓежзѕијклљмнњопрстќуфхцчџш]*', 'ml': '[a-zം-ൿ]*', 'mn': '[a-zабвгдеёжзийклмнопрстуфхцчшщъыьэюя“»]*', 'mr': '[ऀ-ॣॱ-ॿ\ufeff\u200d]*', 'mrj': '[a-zабвгдеёжзийклмнопрстуфхцчшщъыьэюя]*', 'mwl': '[áâãàéêẽçíòóôõq̃úüűũa-z]*', 'myv': '[a-zабвгдеёжзийклмнопрстуфхцчшщъыьэюя]*', 'mzn': '[ابپتثجچحخدذرزژسشصضطظعغفقکگلمنوهیآأئؤة\u200c]*', 'nah': '[a-záéíóúñ]*', 'nap': '[a-zàéèíîìóòúù]*', 'nds': '[äöüßa-z]*', 'nds-nl': '[a-zäöüïëéèà]*', 'nl': '[a-zäöüïëéèà]*', 'nn': '[æøåa-z]*', 'no': '[æøåa-z]*', 'nrm': '[a-zàâçéèêîôûäëïöüùÇÉÂÊÎÔÛÄËÏÖÜÀÈÙ]*', 'oc': '[a-zàâçéèêîôû]*', 'olo': '[a-zčČšŠžŽäÄöÖ]*', 'or': '[a-z\u0b00-\u0b7f]*', 'pa': '[ਁਂਃਅਆਇਈਉਊਏਐਓਔਕਖਗਘਙਚਛਜਝਞਟਠਡਢਣਤਥਦਧਨਪਫਬਭਮਯਰਲਲ਼ਵਸ਼ਸਹ਼ਾਿੀੁੂੇੈੋੌ੍ਖ਼ਗ਼ਜ਼ੜਫ਼ੰੱੲੳa-z]*', 'pcd': '[a-zàâçéèêîôûäëïöüùÇÉÂÊÎÔÛÄËÏÖÜÀÈÙ]*', 'pdc': '[äöüßa-z]*', 'pfl': '[äöüßa-z]*', 'pl': '[a-zęóąśłżźćńĘÓĄŚŁŻŹĆŃ]*', 'pms': '[a-zàéèíîìóòúù]*', 'pnt': '[a-zαβγδεζηθικλμνξοπρστυφχψωςΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩάέήίόύώϊϋΐΰΆΈΉΊΌΎΏΪΫ]*', 'pt': '[a-záâãàéêẽçíòóôõq̃úüűũ]*', 'qu': '[a-záéíóúñ]*', 'rmy': '[a-zăâîşţșțĂÂÎŞŢȘȚ]*', 'ro': '[a-zăâîşţșțĂÂÎŞŢȘȚ]*', 'roa-rup': '[a-zăâîşţșțĂÂÎŞŢȘȚ]*', 'roa-tara': '[a-zàéèíîìóòúù]*', 'ru': '[a-zабвгдеёжзийклмнопрстуфхцчшщъыьэюя]*', 'rue': '[a-zабвгґдеєжзиіїйклмнопрстуфхцчшщьєюяёъы“»]*', 'sa': '[a-zऀ-ॣ०-꣠-\ua8ff]*', 'sah': '[a-zабвгҕдеёжзийклмнҥоөпрсһтуүфхцчшщъыьэюя]*', 'scn': '[a-zàéèíîìóòúù]*', 'sg': '[a-zàâçéèêîôûäëïöüùÇÉÂÊÎÔÛÄËÏÖÜÀÈÙ]*', 'sh': '[a-zčćđžš]*', 'sk': '[a-záäčďéíľĺňóôŕšťúýž]*', 'sl': '[a-zčćđžš]*', 'sr': '[abvgdđežzijklljmnnjoprstćufhcčdžšабвгдђежзијклљмнњопрстћуфхцчџш]*', 'srn': '[a-zäöüïëéèà]*', 'stq': '[äöüßa-z]*', 'sv': '[a-zåäöéÅÄÖÉ]*', 'szl': '[a-zęóąśłżźćńĘÓĄŚŁŻŹĆŃ]*', 'ta': '[\u0b80-\u0bff]*', 'te': '[ఁ-౯]*', 'tet': '[a-záâãàéêẽçíòóôõq̃úüűũ]*', 'tg': '[a-zабвгдеёжзийклмнопрстуфхчшъэюяғӣқўҳҷцщыь]*', 'tk': '[a-zÄäÇçĞğŇňÖöŞşÜüÝýŽž]*', 'tr': '[a-zÇĞçğİıÖöŞşÜüÂâÎîÛû]*', 'tt': '[a-zабвгдеёжзийклмнопрстуфхцчшщъыьэюяӘәӨөҮүҖҗҢңҺһ]*', 'ty': '[a-zàâçéèêîôûäëïöüùÇÉÂÊÎÔÛÄËÏÖÜÀÈÙ]*', 'tyv': '[a-zабвгдеёжзийклмнопрстуфхцчшщъыьэюя]*', 'udm': '[a-zа-яёӝӟӥӧӵ]*', 'uk': '[a-zабвгґдеєжзиіїйклмнопрстуфхцчшщьєюяёъы“»]*', 'ur': '[ابپتٹثجچحخدڈذر\u200bڑ\u200bزژسشصضطظعغفقکگل\u200bم\u200bنںوؤہھیئےآأءۃ]*', 'uz': '[a-zʻʼ“»]*', 'vec': '[a-zàéèíîìóòúù]*', 'vep': '[äöõšüža-z]*', 'vi': '[a-zàâçéèêîôûäëïöüùÇÉÂÊÎÔÛÄËÏÖÜÀÈÙ]*', 'vls': '[a-zäöüïëéèà]*', 'wa': '[a-zåâêîôûçéè]*', 'wo': '[a-zàâçéèêîôûäëïöüùÇÉÂÊÎÔÛÄËÏÖÜÀÈÙ]*', 'xal': '[a-zабвгдеёжзийклмнопрстуфхцчшщъыьэюя]*', 'xmf': '[a-zაბგდევზთიკლმნოპჟრსტუფქღყშჩცძწჭხჯჰ“»]*', 'yi': '[a-zא-ת]*', 'zea': '[a-zäöüïëéèà]*'}
static load(fam=None, fatal=NotImplemented)[source]

Import the named family.

Parameters:fam (str) – family name (if omitted, uses the configured default)
Returns:a Family instance configured for the named family.
Raises:UnknownFamily – family not known
maximum_GET_length(code)[source]

Return the maximum URL length for GET instead of POST.

name = None
nocapitalize = []
obsolete

Old codes that are not part of the family.

Interwiki replacements override removals for the same code.

Returns:mapping of old codes to new codes (or None)
Return type:dict
path(code)[source]

Return path to index.php.

post_get_convert(site, getText)[source]

Do a conversion on the retrieved text from the Wiki.

For example a X-conversion in Esperanto https://en.wikipedia.org/wiki/Esperanto_orthography#X-system.

pre_put_convert(site, putText)[source]

Do a conversion on the text to insert on the Wiki.

For example a X-conversion in Esperanto https://en.wikipedia.org/wiki/Esperanto_orthography#X-system.

protocol(code)[source]

The protocol to use to connect to the site.

May be overridden to return ‘https’. Other protocols are not supported.

Parameters:code (str) – language code
Returns:protocol that this family uses
Return type:str
querypath(code)[source]

Return path to query.php.

rcstream_host(code)[source]

Hostname for RCStream.

rcstream_path(code)[source]

Return path for RCStream.

rcstream_port(code)[source]

Return port for RCStream.

scriptpath(code)[source]

The prefix used to locate scripts on this wiki.

This is the value displayed when you enter {{SCRIPTPATH}} on a wiki page (often displayed at [[Help:Variables]] if the wiki has copied the master help page correctly).

The default value is the one used on Wikimedia Foundation wikis, but needs to be overridden in the family file for any wiki that uses a different value.

Parameters:code (str) – Site code
Raises:KeyError – code is not recognised
Returns:URL path without ending ‘/’
Return type:str
server_time(code)[source]

DEPRECATED, use Site.server_time instead.

Return a datetime object representing server time.

shared_data_repository(code)[source]

Return the shared Wikibase repository, if any.

shared_image_repository(code)[source]

Return the shared image repository, if any.

shared_urlshortner_wiki = None
ssl_hostname(code)[source]

The hostname to use for SSL connections.

ssl_pathprefix(code)[source]

The path prefix for secure HTTP access.

use_hard_category_redirects = []
class pywikibot.family.FandomFamily[source]

Bases: pywikibot.family.Family

Common features of Fandom families.

__module__ = 'pywikibot.family'
langs

Property listing family languages.

protocol(code)[source]

Return ‘https’ as the protocol.

scriptpath(code)[source]

Return the script path for this family.

class pywikibot.family.SingleSiteFamily[source]

Bases: pywikibot.family.Family

Single site family.

__module__ = 'pywikibot.family'
static __new__(cls)[source]

Initializer.

domains

Return the full domain name of the site.

hostname(code)[source]

Return the domain as the hostname.

class pywikibot.family.SubdomainFamily[source]

Bases: pywikibot.family.Family

Multi site wikis that are subdomains of the same top level domain.

__module__ = 'pywikibot.family'
static __new__(cls)[source]

Initializer.

codes

Property listing family codes.

domains

Return the domain name of the sites in this family.

langs

Property listing family languages.

class pywikibot.family.WikimediaFamily[source]

Bases: pywikibot.family.Family

Class for all wikimedia families.

__module__ = 'pywikibot.family'
closed_wikis = []
code_aliases = {'-': 'mul', 'be-x-old': 'be-tarask', 'dk': 'da', 'jp': 'ja', 'minnan': 'zh-min-nan', 'mo': 'ro', 'nan': 'zh-min-nan', 'nb': 'no', 'nl_nds': 'nl-nds', 'zh-cn': 'zh', 'zh-tw': 'zh'}
content_families = {'commons', 'incubator', 'mediawiki', 'species', 'test', 'wikibooks', 'wikidata', 'wikinews', 'wikipedia', 'wikiquote', 'wikisource', 'wikiversity', 'wikivoyage', 'wiktionary'}
cross_projects = {'commons', 'incubator', 'mediawiki', 'meta', 'outreach', 'species', 'strategy', 'test', 'wikibooks', 'wikidata', 'wikimania', 'wikimediachapter', 'wikinews', 'wikipedia', 'wikiquote', 'wikisource', 'wikiversity', 'wikivoyage', 'wiktionary'}
disambcatname = {'wikidata': 'Q1982926'}
domain

Domain property.

eventstreams_host(code)[source]

Return ‘https://stream.wikimedia.org’ as the stream hostname.

eventstreams_path(code)[source]

Return path for EventStreams.

interwiki_removals

Return a list of interwiki codes to be removed from wiki pages.

interwiki_replacements

Return an interwiki code replacement mapping.

multi_language_content_families = ['wikipedia', 'test', 'wiktionary', 'wikisource', 'wikibooks', 'wikinews', 'wikiquote', 'wikiversity', 'wikivoyage']
other_content_families = ['wikidata', 'mediawiki']
protocol(code)[source]

Return ‘https’ as the protocol.

removed_wikis = []
shared_image_repository(code)[source]

Return Wikimedia Commons as the shared image repository.

shared_urlshortner_wiki = ('meta', 'meta')
wikimedia_org_content_families = ['commons', 'incubator', 'species']
wikimedia_org_families = {'commons', 'incubator', 'meta', 'outreach', 'species', 'strategy', 'wikimania', 'wikimediachapter', 'wikitech'}
wikimedia_org_meta_families = ['meta', 'outreach', 'strategy', 'wikimediachapter', 'wikimania']
wikimedia_org_other_families = ['wikitech']
class pywikibot.family.WikimediaOrgFamily[source]

Bases: pywikibot.family.SingleSiteFamily, pywikibot.family.WikimediaFamily

Single site family for sites hosted at *.wikimedia.org.

__module__ = 'pywikibot.family'
domain

Return the parents domain with a subdomain prefix.

pywikibot.fixes module

File containing all standard fixes. Currently available predefined fixes are:

  • HTML - Convert HTML tags to wiki syntax, and
    fix XHTML.
  • isbn - Fix badly formatted ISBNs.
  • syntax - Try to fix bad wiki markup. Do not run
    this in automatic mode, as the bot may make mistakes.
  • syntax-safe - Like syntax, but less risky, so you can
    run this in automatic mode.
  • case-de - fix upper/lower case errors in German
  • grammar-de - fix grammar and typography in German
  • vonbis - Ersetze Binde-/Gedankenstrich durch “bis”
    in German
  • music - Links auf Begriffsklärungen in German
  • datum - specific date formats in German
  • correct-ar - Typo corrections for Arabic Wikipedia and any
    Arabic wiki.
  • yu-tld - Fix links to .yu domains because it is
    disabled, see: https://lists.wikimedia.org/pipermail/wikibots-l/2009-February/000290.html
  • fckeditor - Try to convert FCKeditor HTML tags to wiki
    syntax.

pywikibot.flow module

Objects representing Flow entities, like boards, topics, and posts.

class pywikibot.flow.Board(source, title='')[source]

Bases: pywikibot.flow.FlowPage

A Flow discussion board.

__module__ = 'pywikibot.flow'
new_topic(title, content, format='wikitext')[source]

Create and return a Topic object for a new topic on this Board.

Parameters:
  • title (str) – The title of the new topic (must be in plaintext)
  • content (str) – The content of the topic’s initial post
  • format (str (either 'wikitext' or 'html')) – The content format of the value supplied for content
Returns:

The new topic

Return type:

Topic

topics(format='wikitext', limit=100, sort_by='newest', offset=None, offset_uuid='', reverse=False, include_offset=False, toc_only=False)[source]

Load this board’s topics.

Parameters:
  • format (str (either 'wikitext', 'html', or 'fixed-html')) – The content format to request the data in.
  • limit (int) – The number of topics to fetch in each request.
  • sort_by (str (either 'newest' or 'updated')) – Algorithm to sort topics by.
  • offset (Timestamp or equivalent str) – The timestamp to start at (when sortby is ‘updated’).
  • offset_uuid (str (in the form of a UUID)) – The UUID to start at (when sortby is ‘newest’).
  • reverse (bool) – Whether to reverse the topic ordering.
  • include_offset (bool) – Whether to include the offset topic.
  • toc_only (bool) – Whether to only include information for the TOC.
Returns:

A generator of this board’s topics.

Return type:

generator of Topic objects

class pywikibot.flow.FlowPage(source, title='')[source]

Bases: pywikibot.page.BasePage

The base page for the Flow extension.

There should be no need to instantiate this directly.

Subclasses must provide a _load() method to load and cache the object’s internal data from the API.

__init__(source, title='')[source]

Initializer.

Parameters:
  • source (Site, Link, or Page) – A Flow-enabled site or a Link or Page on such a site
  • title (str) – normalized title of the page
Raises:
  • TypeError – incorrect use of parameters
  • ValueError – use of non-Flow-enabled Site
__module__ = 'pywikibot.flow'
get(force=False, get_redirect=False, sysop=False)[source]

Get the page’s content.

uuid

Return the UUID of the page.

Returns:UUID of the page
Return type:str
class pywikibot.flow.Post(page, uuid)[source]

Bases: object

A post to a Flow discussion topic.

__init__(page, uuid)[source]

Initializer.

Parameters:
  • page (Topic) – Flow topic
  • uuid (str) – UUID of a Flow post
Raises:

TypeError – incorrect types of parameters

__module__ = 'pywikibot.flow'
creator

The creator of this post.

delete(reason)[source]

Delete this post through the Flow moderation system.

Parameters:reason (str) – The reason for deleting this post.
classmethod fromJSON(page, post_uuid, data)[source]

Create a Post object using the data returned from the API call.

Parameters:
  • page (Topic) – A Flow topic
  • post_uuid (str) – The UUID of the post
  • data (dict) – The JSON data returned from the API
Returns:

A Post object

Raises:
  • TypeError – data is not a dict
  • ValueError – data is missing required entries
get(format='wikitext', force=False, sysop=False)[source]

Return the contents of the post in the given format.

Parameters:
  • force (bool) – Whether to reload from the API instead of using the cache
  • sysop (bool) – Whether to load using sysop rights. Implies force.
  • format (str) – Content format to return contents in
Returns:

The contents of the post in the given content format

Return type:

str

Raises:

NotImplementedError – use of ‘sysop’

hide(reason)[source]

Hide this post.

Parameters:reason (str) – The reason for hiding this post.
is_moderated

Whether this post is moderated.

page

Return the page associated with the post.

Returns:Page associated with the post
Return type:FlowPage
replies(format='wikitext', force=False)[source]

Return this post’s replies.

Parameters:
  • format (str ('wikitext', 'html', or 'fixed-html')) – Content format to return contents in
  • force (bool) – Whether to reload from the API instead of using the cache
Returns:

This post’s replies

Return type:

list of Posts

reply(content, format='wikitext')[source]

Reply to this post.

Parameters:
  • content (str) – The content of the new post
  • format (str ('wikitext' or 'html')) – The format of the given content
Returns:

The new reply post

Return type:

Post

restore(reason)[source]

Restore this post.

Parameters:reason (str) – The reason for restoring this post.
site

Return the site associated with the post.

Returns:Site associated with the post
Return type:Site
suppress(reason)[source]

Suppress this post.

Parameters:reason (str) – The reason for suppressing this post.
thank()[source]

Thank the user who made this post.

uuid

Return the UUID of the post.

Returns:UUID of the post
Return type:str
class pywikibot.flow.Topic(source, title='')[source]

Bases: pywikibot.flow.FlowPage

A Flow discussion topic.

__module__ = 'pywikibot.flow'
classmethod create_topic(board, title, content, format='wikitext')[source]

Create and return a Topic object for a new topic on a Board.

Parameters:
  • board (Board) – The topic’s parent board
  • title (str) – The title of the new topic (must be in plaintext)
  • content (str) – The content of the topic’s initial post
  • format (str (either 'wikitext' or 'html')) – The content format of the value supplied for content
Returns:

The new topic

Return type:

Topic

delete_mod(reason)[source]

Delete this topic through the Flow moderation system.

Parameters:reason (str) – The reason for deleting this topic.
classmethod from_topiclist_data(board, root_uuid, topiclist_data)[source]

Create a Topic object from API data.

Parameters:
  • board (Board) – The topic’s parent Flow board
  • root_uuid (str) – The UUID of the topic and its root post
  • topiclist_data (dict) – The data returned by view-topiclist
Returns:

A Topic object derived from the supplied data

Return type:

Topic

Raises:
  • TypeError – any passed parameters have wrong types
  • ValueError – the passed topiclist_data is missing required data
hide(reason)[source]

Hide this topic.

Parameters:reason (str) – The reason for hiding this topic.
is_locked

Whether this topic is locked.

is_moderated

Whether this topic is moderated.

lock(reason)[source]

Lock this topic.

Parameters:reason (str) – The reason for locking this topic
replies(format='wikitext', force=False)[source]

A list of replies to this topic’s root post.

Parameters:
  • format (str ('wikitext', 'html', or 'fixed-html')) – Content format to return contents in
  • force (bool) – Whether to reload from the API instead of using the cache
Returns:

The replies of this topic’s root post

Return type:

list of Posts

reply(content, format='wikitext')[source]

A convenience method to reply to this topic’s root post.

Parameters:
  • content (str) – The content of the new post
  • format (str ('wikitext' or 'html')) – The format of the given content
Returns:

The new reply to this topic’s root post

Return type:

Post

restore(reason)[source]

Restore this topic.

Parameters:reason (str) – The reason for restoring this topic.
root

The root post of this topic.

suppress(reason)[source]

Suppress this topic.

Parameters:reason (str) – The reason for suppressing this topic.
unlock(reason)[source]

Unlock this topic.

Parameters:reason (str) – The reason for unlocking this topic

pywikibot.i18n module

Various i18n functions.

Helper functions for both the internal translation system and for TranslateWiki-based translations.

By default messages are assumed to reside in a package called ‘scripts.i18n’. In pywikibot 3.0, that package is not packaged with pywikibot, and pywikibot 3.0 does not have a hard dependency on any i18n messages. However, there are three user input questions in pagegenerators which will use i18 messages if they can be loaded.

The default message location may be changed by calling set_message_package with a package name. The package must contain an __init__.py, and a message bundle called ‘pywikibot’ containing messages. See twtranslate for more information on the messages.

exception pywikibot.i18n.TranslationError(arg)[source]

Bases: pywikibot.exceptions.Error, ImportError

Raised when no correct translation could be found.

__module__ = 'pywikibot.i18n'
pywikibot.i18n.input(twtitle, parameters=None, password=False, fallback_prompt=None)[source]

Ask the user a question, return the user’s answer.

The prompt message is retrieved via twtranslate and uses the config variable ‘userinterface_lang’.

Parameters:
  • twtitle – The TranslateWiki string title, in <package>-<key> format
  • parameters – The values which will be applied to the translated text
  • password – Hides the user’s input (for password entry)
  • fallback_prompt – The English prompt if i18n is not available.
Return type:

str

pywikibot.i18n.messages_available()[source]

Return False if there are no i18n messages available.

To determine if messages are available, it looks for the package name set using set_messages_package for a message bundle called ‘pywikibot’ containing messages.

Return type:bool
pywikibot.i18n.set_messages_package(package_name)[source]

Set the package name where i18n messages are located.

pywikibot.i18n.translate(code, xdict, parameters=None, fallback=False)[source]

Return the most appropriate translation from a translation dict.

Given a language code and a dictionary, returns the dictionary’s value for key ‘code’ if this key exists; otherwise tries to return a value for an alternative language that is most applicable to use on the wiki in language ‘code’ except fallback is False.

The language itself is always checked first, then languages that have been defined to be alternatives, and finally English. If none of the options gives result, we just take the one language from xdict which may not be always the same. When fallback is iterable it’ll return None if no code applies (instead of returning one).

For PLURAL support have a look at the twtranslate method.

Parameters:
  • code (str or Site object) – The language code
  • xdict (dict, string, unicode) – dictionary with language codes as keys or extended dictionary with family names as keys containing language dictionaries or a single (unicode) string. May contain PLURAL tags as described in twtranslate
  • parameters (dict, string, unicode, int) – For passing (plural) parameters
  • fallback (boolean or iterable) – Try an alternate language code. If it’s iterable it’ll also try those entries and choose the first match.
Raises:

IndexError – If the language supports and requires more plurals than defined for the given translation template.

pywikibot.i18n.twget_keys(twtitle)[source]

Return all language codes for a special message.

Parameters:twtitle – The TranslateWiki string title, in <package>-<key> format
Raises:OSError – the package i18n can not be loaded
pywikibot.i18n.twhas_key(source, twtitle, code='[deprecated name of source]')[source]

Check if a message has a translation in the specified language code.

The translations are retrieved from i18n.<package>, based on the callers import table.

No code fallback is made.

Parameters:
  • source (BaseSite or str) – When it’s a site it’s using the lang attribute and otherwise it is using the value directly.
  • twtitle – The TranslateWiki string title, in <package>-<key> format
pywikibot.i18n.twtranslate(source, twtitle, parameters=None, fallback=True, only_plural=False, code='[deprecated name of source]')[source]

Translate a message using JSON files in messages_package_name.

fallback parameter must be True for i18n and False for L10N or testing purposes.

Support for plural is implemented like in MediaWiki extension. If the TranslateWiki message contains a plural tag inside which looks like:

{{PLURAL:<number>|<variant1>|<variant2>[|<variantn>]}}

it takes that variant calculated by the plural_rules depending on the number value. Multiple plurals are allowed.

As an examples, if we had several json dictionaries in test folder like:

en.json:

{
   "test-plural": "Bot: Changing %(num)s {{PLURAL:%(num)d|page|pages}}.",
}

fr.json:

{
   "test-plural": \
   "Robot: Changer %(descr)s {{PLURAL:num|une page|quelques pages}}.",
}

and so on.

>>> from pywikibot import i18n
>>> i18n.set_messages_package('tests.i18n')
>>> # use a dictionary
>>> str(i18n.twtranslate('en', 'test-plural', {'num':2}))
'Bot: Changing 2 pages.'
>>> # use additional format strings
>>> str(i18n.twtranslate(
...    'fr', 'test-plural', {'num': 1, 'descr': 'seulement'}))
'Robot: Changer seulement une page.'
>>> # use format strings also outside
>>> str(i18n.twtranslate(
...    'fr', 'test-plural', {'num': 10}, only_plural=True
... ) % {'descr': 'seulement'})
'Robot: Changer seulement quelques pages.'
Parameters:
  • source (BaseSite or str) – When it’s a site it’s using the lang attribute and otherwise it is using the value directly.
  • twtitle – The TranslateWiki string title, in <package>-<key> format
  • parameters – For passing parameters. It should be a mapping but for backwards compatibility can also be a list, tuple or a single value. They are also used for plural entries in which case they must be a Mapping and will cause a TypeError otherwise.
  • fallback (boolean) – Try an alternate language code
  • only_plural (bool) – Define whether the parameters should be only applied to plural instances. If this is False it will apply the parameters also to the resulting string. If this is True the placeholders must be manually applied afterwards.
Raises:

IndexError – If the language supports and requires more plurals than defined for the given translation template.

pywikibot.interwiki_graph module

Module with the Graphviz drawing calls.

class pywikibot.interwiki_graph.GraphDrawer(subject)[source]

Bases: object

Graphviz (dot) code creator.

__init__(subject)[source]

Initializer.

Parameters:subject (Subject) – page data to graph
Raises:GraphImpossible – pydot is not installed
__module__ = 'pywikibot.interwiki_graph'
addDirectedEdge(page, refPage)[source]

Add a directed edge from refPage to page.

addNode(page)[source]

Add a node for page.

createGraph()[source]

Create graph of the interwiki links.

For more info see https://meta.wikimedia.org/wiki/Interwiki_graphs

getLabel(page)[source]

Get label for page.

saveGraphFile()[source]

Write graphs to the data directory.

exception pywikibot.interwiki_graph.GraphImpossible[source]

Bases: Exception

Drawing a graph is not possible on your system.

__module__ = 'pywikibot.interwiki_graph'
class pywikibot.interwiki_graph.GraphSavingThread(graph, originPage)[source]

Bases: threading.Thread

Threaded graph renderer.

Rendering a graph can take extremely long. We use multithreading because of that.

TODO: Find out if several threads running in parallel can slow down the system too much. Consider adding a mechanism to kill a thread if it takes too long.

__init__(graph, originPage)[source]

Initializer.

__module__ = 'pywikibot.interwiki_graph'
run()[source]

Write graphs to the data directory.

class pywikibot.interwiki_graph.Subject(origin=None)[source]

Bases: object

Data about a page with translations on multiple wikis.

__init__(origin=None)[source]

Initializer.

Parameters:originPage (Page) – the page on the ‘origin’ wiki
__module__ = 'pywikibot.interwiki_graph'
foundIn

Mapping of pages to others pages interwiki linked to it.

DEPRECATED. Use found_in.

origin

Page on the origin wiki.

pywikibot.interwiki_graph.getFilename(page, extension=None)[source]

Create a filename that is unique for the page.

Parameters:
  • page (Page) – page used to create the new filename
  • extension (str) – file extension
Returns:

filename of <family>-<lang>-<page>.<ext>

Return type:

str

pywikibot.logentries module

Objects representing Mediawiki log entries.

class pywikibot.logentries.BlockEntry(apidata, site)[source]

Bases: pywikibot.logentries.LogEntry

Block or unblock log entry.

It might contain a block or unblock depending on the action. The duration, expiry and flags are not available on unblock log entries.

__init__(apidata, site)[source]

Initializer.

__module__ = 'pywikibot.logentries'
duration()[source]

Return a datetime.timedelta representing the block duration.

Returns:datetime.timedelta, or None if block is indefinite.
expiry()[source]

Return a Timestamp representing the block expiry date.

Return type:pywikibot.Timestamp or None
flags()[source]

Return a list of (str) flags associated with the block entry.

It raises an Error if the entry is an unblocking log entry.

Returns:list of flags strings
Return type:list
page()[source]

Return the blocked account or IP.

Returns:the Page object of username or IP if this block action targets a username or IP, or the blockid if this log reflects the removal of an autoblock
Return type:pywikibot.Page or int
class pywikibot.logentries.DeleteEntry(apidata, site)

Bases: pywikibot.logentries.OtherLogEntry

__module__ = 'pywikibot.logentries'
class pywikibot.logentries.ImportEntry(apidata, site)

Bases: pywikibot.logentries.OtherLogEntry

__module__ = 'pywikibot.logentries'
class pywikibot.logentries.LogDict[source]

Bases: dict

Simple custom dict that raises custom Errors when a key is missing.

HiddenKeyError is raised when the user does not have permission. KeyError is raised otherwise.

It also logs debugging information when a key is missing.

__missing__(key)[source]

Debug when the key is missing.

__module__ = 'pywikibot.logentries'
class pywikibot.logentries.LogEntry(apidata, site)[source]

Bases: object

Generic log entry.

__eq__(other)[source]

Compare if self is equal to other.

__hash__()[source]

Combine site and logid as the hash.

__init__(apidata, site)[source]

Initialize object from a logevent dict returned by MW API.

__module__ = 'pywikibot.logentries'
__ne__(other)[source]

Compare if self is not equal to other.

__repr__()[source]

Return a string representation of LogEntry object.

action()[source]

The action of this log entry.

comment()[source]

Return the logentry’s comment.

Return type:str
logid()[source]

Return the id of the log entry.

ns()[source]

Return the namespace id of the page handled by this log entry.

page()[source]

Page on which action was performed.

Returns:page on action was performed
Return type:pywikibot.Page
pageid()[source]

Return the log id of the page handled by this log entry.

timestamp()[source]

Timestamp object corresponding to event timestamp.

title()[source]

DEPRECATED: Alias for page().

This is going to be replaced by just returning the title as a string instead of a Page instance.

type()[source]

The type of this logentry.

user()[source]

Return the user name doing this action.

class pywikibot.logentries.LogEntryFactory(site, logtype=None)[source]

Bases: object

LogEntry Factory.

Only available method is create()

__init__(site, logtype=None)[source]

Initializer.

Parameters:
  • site (BaseSite) – The site on which the log entries are created.
  • logtype ((letype) str : move/block/patrol/etc...) – The log type of the log entries, if known in advance. If None, the Factory will fetch the log entry from the data to create each object.
__module__ = 'pywikibot.logentries'
create(logdata)[source]

Instantiate the LogEntry object representing logdata.

Parameters:logdata (dict) – <item> returned by the api
Returns:LogEntry object representing logdata
classmethod get_entry_class(logtype)[source]

Return the class corresponding to the @logtype string parameter.

Returns:specified subclass of LogEntry
Return type:LogEntry
Note:this class method cannot verify whether the given logtype already exits for a given site; to verify use Site.logtypes or use the get_valid_entry_class instance method instead.
get_valid_entry_class(logtype)[source]

Return the class corresponding to the @logtype string parameter.

Returns:specified subclass of LogEntry
Return type:LogEntry
Raises:KeyError – logtype is not valid
logtypes = {'block': <class 'pywikibot.logentries.BlockEntry'>, 'delete': <class 'pywikibot.logentries.DeleteEntry'>, 'import': <class 'pywikibot.logentries.ImportEntry'>, 'move': <class 'pywikibot.logentries.MoveEntry'>, 'newusers': <class 'pywikibot.logentries.NewusersEntry'>, 'patrol': <class 'pywikibot.logentries.PatrolEntry'>, 'protect': <class 'pywikibot.logentries.ProtectEntry'>, 'rights': <class 'pywikibot.logentries.RightsEntry'>, 'thanks': <class 'pywikibot.logentries.ThanksEntry'>, 'upload': <class 'pywikibot.logentries.UploadEntry'>}
class pywikibot.logentries.MoveEntry(apidata, site)[source]

Bases: pywikibot.logentries.LogEntry

Move log entry.

__module__ = 'pywikibot.logentries'
suppressedredirect()[source]

Return True if no redirect was created during the move.

Return type:bool
target_ns

Return namespace object of target page.

target_page

Return target page object.

Return type:pywikibot.Page
target_title

Return the target title.

pywikibot.logentries.NewUsersEntry

alias of pywikibot.logentries.NewusersEntry

class pywikibot.logentries.OtherLogEntry(apidata, site)[source]

Bases: pywikibot.logentries.LogEntry

A log entry class for unspecified log events.

__module__ = 'pywikibot.logentries'
class pywikibot.logentries.PatrolEntry(apidata, site)[source]

Bases: pywikibot.logentries.LogEntry

Patrol log entry.

__module__ = 'pywikibot.logentries'
auto

Return auto patrolled.

current_id

Return the current id.

Return type:int
previous_id

Return the previous id.

Return type:int
class pywikibot.logentries.ProtectEntry(apidata, site)

Bases: pywikibot.logentries.OtherLogEntry

__module__ = 'pywikibot.logentries'
class pywikibot.logentries.RightsEntry(apidata, site)[source]

Bases: pywikibot.logentries.LogEntry

Rights log entry.

__module__ = 'pywikibot.logentries'
newgroups

Return new rights groups.

oldgroups

Return old rights groups.

class pywikibot.logentries.ThanksEntry(apidata, site)

Bases: pywikibot.logentries.UserTargetLogEntry, pywikibot.logentries.OtherLogEntry

__module__ = 'pywikibot.logentries'
class pywikibot.logentries.UploadEntry(apidata, site)[source]

Bases: pywikibot.logentries.LogEntry

Upload log entry.

__module__ = 'pywikibot.logentries'
page()[source]

Return FilePage on which action was performed.

Return type:pywikibot.FilePage
class pywikibot.logentries.UserTargetLogEntry(apidata, site)[source]

Bases: pywikibot.logentries.LogEntry

A log entry whose target is a user page.

__module__ = 'pywikibot.logentries'
page()[source]

Return the target user.

This returns a User object instead of the Page object returned by the superclass method.

Returns:target user
Return type:pywikibot.User

pywikibot.logging module

Logging functions.

pywikibot.logging.add_init_routine(routine)[source]

Add a routine to be run as soon as possible.

pywikibot.logging.critical(text, decoder=None, newline=True, **kwargs)[source]

Output a critical record to the user via the userinterface.

pywikibot.logging.debug(text, layer, decoder=None, newline=True, **kwargs)[source]

Output a debug record to the log file.

Parameters:layer – The name of the logger that text will be sent to.
pywikibot.logging.error(text, decoder=None, newline=True, **kwargs)[source]

Output an error message to the user via the userinterface.

pywikibot.logging.exception(msg=None, decoder=None, newline=True, tb=False, **kwargs)[source]

Output an error traceback to the user via the userinterface.

Use directly after an ‘except’ statement:

...
except Exception:
    pywikibot.exception()
...

or alternatively:

...
except Exception as e:
    pywikibot.exception(e)
...
Parameters:tb – Set to True in order to output traceback also.
pywikibot.logging.log(text, decoder=None, newline=True, **kwargs)[source]

Output a record to the log file.

pywikibot.logging.logoutput(text, decoder=None, newline=True, _level=20, _logger='', **kwargs)[source]

Format output and send to the logging module.

Helper function used by all the user-output convenience functions.

pywikibot.logging.output(text, decoder=None, newline=True, toStdout=False, **kwargs)[source]

Output a message to the user via the userinterface.

Works like print, but uses the encoding used by the user’s console (console_encoding in the configuration file) instead of ASCII.

If decoder is None, text should be a unicode string. Otherwise it should be encoded in the given encoding.

If newline is True, a line feed will be added after printing the text.

If toStdout is True, the text will be sent to standard output, so that it can be piped to another process. All other text will be sent to stderr. See: https://en.wikipedia.org/wiki/Pipeline_%28Unix%29

text can contain special sequences to create colored output. These consist of the escape character 03 and the color name in curly braces, e. g. 03{lightpurple}. 03{default} resets the color. By using the color_format method from pywikibot.tools.formatter, the escape character may be omitted.

Other keyword arguments are passed unchanged to the logger; so far, the only argument that is useful is “exc_info=True”, which causes the log message to include an exception traceback.

pywikibot.logging.stdout(text, decoder=None, newline=True, **kwargs)[source]

Output script results to the user via the userinterface.

pywikibot.logging.warning(text, decoder=None, newline=True, **kwargs)[source]

Output a warning message to the user via the userinterface.

Parameters:
  • text (str) – the message the user wants to display.
  • decoder (str) – If None, text should be a unicode string. Otherwise it should be encoded in the given encoding.
  • newline (bool) – If True, a line feed will be added after printing the text.
  • kwargs – The keyword arguments can be found in the python doc: https://docs.python.org/3/howto/logging-cookbook.html.

pywikibot.login module

Library to log the bot in to a wiki account.

class pywikibot.login.BotPassword(suffix, password)[source]

Bases: object

BotPassword object for storage in password file.

__init__(suffix, password)[source]

Initializer.

BotPassword function by using a separate password paired with a suffixed username of the form <username>@<suffix>.

Parameters:
  • suffix (basestring) – Suffix of the login name
  • password (basestring) – bot password
Raises:

_PasswordFileWarning – suffix improperly specified

__module__ = 'pywikibot.login'
login_name(username)[source]

Construct the login name from the username and suffix.

Parameters:user (basestring) – username (without suffix)
Return type:basestring
class pywikibot.login.LoginManager(password=None, site=None, user=None, sysop=NotImplemented, verbose=NotImplemented, username='[deprecated name of user]')[source]

Bases: object

Site login manager.

__init__(password=None, site=None, user=None, sysop=NotImplemented, verbose=NotImplemented, username='[deprecated name of user]')[source]

Initializer.

All parameters default to defaults in user-config.

Parameters:
  • site (BaseSite) – Site object to log into
  • user (basestring) – username to use. If user is None, the username is loaded from config.usernames.
  • password (basestring) – password to use
Raises:

NoUsername – No username is configured for the requested site.

__module__ = 'pywikibot.login'
botAllowed()[source]

Check whether the bot is listed on a specific page.

This allows bots to comply with the policy on the respective wiki.

check_user_exists()[source]

Check that the username exists on the site.

See:https://www.mediawiki.org/wiki/API:Users
Raises:NoUsername – Username doesn’t exist in user list.
getCookie()[source]

Login to the site.

See:https://www.mediawiki.org/wiki/API:Login
Returns:cookie data if successful, None otherwise.
login(retry=False, autocreate=False)[source]

Attempt to log into the server.

See:

https://www.mediawiki.org/wiki/API:Login

Parameters:
  • retry (bool) – infinitely retry if the API returns an unknown error
  • autocreate (bool) – if true, allow auto-creation of the account using unified login
Raises:

NoUsername – Username is not recognised by the site.

readPassword()[source]

Read passwords from a file.

DO NOT FORGET TO REMOVE READ ACCESS FOR OTHER USERS!!! Use chmod 600 password-file.

All lines below should be valid Python tuples in the form (code, family, username, password), (family, username, password) or (username, password) to set a default password for an username. The last matching entry will be used, so default usernames should occur above specific usernames.

For BotPasswords the password should be given as a BotPassword object.

The file must be either encoded in ASCII or UTF-8.

Example:

('my_username', 'my_default_password')
('wikipedia', 'my_wikipedia_user', 'my_wikipedia_pass')
('en', 'wikipedia', 'my_en_wikipedia_user', 'my_en_wikipedia_pass')
('my_username', BotPassword(
 'my_BotPassword_suffix', 'my_BotPassword_password'))
storecookiedata(data)[source]

Store cookie data.

Parameters:data (str) – The raw data as returned by getCookie()
Returns:None
exception pywikibot.login.OAuthImpossible[source]

Bases: ImportError

OAuth authentication is not possible on your system.

__module__ = 'pywikibot.login'
class pywikibot.login.OauthLoginManager(password=None, site=None, user=None, sysop=NotImplemented)[source]

Bases: pywikibot.login.LoginManager

Site login manager using OAuth.

__init__(password=None, site=None, user=None, sysop=NotImplemented)[source]

Initializer.

All parameters default to defaults in user-config.

Parameters:
  • site (BaseSite) – Site object to log into
  • user (basestring) – consumer key
  • password (basestring) – consumer secret
Raises:
__module__ = 'pywikibot.login'
access_token

Return OAuth access key token and secret token.

See:https://www.mediawiki.org/wiki/API:Tokens
Return type:tuple of two str
consumer_token

Return OAuth consumer key token and secret token.

See:https://www.mediawiki.org/wiki/API:Tokens
Return type:tuple of two str
identity

Get identifying information about a user via an authorized token.

Return type:None or dict
login(retry=False, force=False)[source]

Attempt to log into the server.

See:

https://www.mediawiki.org/wiki/API:Login

Parameters:
  • retry (bool) – infinitely retry if exception occurs during authentication.
  • force (bool) – force to re-authenticate

pywikibot.page module

Objects representing various types of MediaWiki, including Wikibase, pages.

This module also includes objects:

  • Property: a type of semantic data.
  • Claim: an instance of a semantic assertion.
  • Revision: a single change to a wiki page.
  • FileInfo: a structure holding imageinfo of latest rev. of FilePage
  • Link: an internal or interwiki link in wikitext.
class pywikibot.page.BasePage(source, title='', ns=0)[source]

Bases: pywikibot.tools.UnicodeMixin, pywikibot.tools.ComparableMixin

BasePage: Base object for a MediaWiki page.

This object only implements internally methods that do not require reading from or writing to the wiki. All other methods are delegated to the Site object.

Will be subclassed by Page, WikibasePage, and FlowPage.

__hash__()[source]

A stable identifier to be used as a key in hash-tables.

This relies on the fact that the string representation of an instance can not change after the construction.

__init__(source, title='', ns=0)[source]

Instantiate a Page object.

Three calling formats are supported:

  • If the first argument is a Page, create a copy of that object. This can be used to convert an existing Page into a subclass object, such as Category or FilePage. (If the title is also given as the second argument, creates a copy with that title; this is used when pages are moved.)
  • If the first argument is a Site, create a Page on that Site using the second argument as the title (may include a section), and the third as the namespace number. The namespace number is mandatory, even if the title includes the namespace prefix. This is the preferred syntax when using an already-normalized title obtained from api.php or a database dump. WARNING: may produce invalid objects if page title isn’t in normal form!
  • If the first argument is a BaseLink, create a Page from that link. This is the preferred syntax when using a title scraped from wikitext, URLs, or another non-normalized source.
Parameters:
  • source (BaseLink (or subclass), Page (or subclass), or Site) – the source of the page
  • title (str) – normalized title of the page; required if source is a Site, ignored otherwise
  • ns (int) – namespace number; required if source is a Site, ignored otherwise
__module__ = 'pywikibot.page'
__repr__()[source]

Return a more complete string representation.

__unicode__()[source]

Return a unicode string representation.

applicable_protections()[source]

Return the protection types allowed for that page.

If the page doesn’t exists it only returns “create”. Otherwise it returns all protection types provided by the site, except “create”. It also removes “upload” if that page is not in the File namespace.

It is possible, that it returns an empty set, but only if original protection types were removed.

Returns:set of unicode
Return type:set
autoFormat()[source]

Return date.getAutoFormat dictName and value, if any.

Value can be a year, date, etc., and dictName is ‘YearBC’, ‘Year_December’, or another dictionary name. Please note that two entries may have exactly the same autoFormat, but be in two different namespaces, as some sites have categories with the same names. Regular titles return (None, None).

Return an iterator for pages that link to this page.

Parameters:
  • follow_redirects – if True, also iterate pages that link to a redirect pointing to the page.
  • filter_redirects – if True, only iterate redirects; if False, omit redirects; if None, do not filter
  • namespaces – only iterate pages in these namespaces
  • total – iterate no more than this number of pages in total
  • content – if True, retrieve the content of the current version of each referring page (default False)
botMayEdit()[source]

Determine whether the active bot is allowed to edit the page.

This will be True if the page doesn’t contain {{bots}} or {{nobots}} or any other template from edit_restricted_templates list in x_family.py file, or it contains them and the active bot is allowed to edit this page. (This method is only useful on those sites that recognize the bot-exclusion protocol; on other sites, it will always return True.)

The framework enforces this restriction by default. It is possible to override this by setting ignore_bot_templates=True in user-config.py, or using page.put(force=True).

Return type:bool
canBeEdited()[source]

Determine whether the page may be edited.

This returns True if and only if:
  • page is unprotected, and bot has an account for this site, or
  • page is protected, and bot has a sysop account for this site.
Return type:bool
categories(with_sort_key=False, total=None, content=False, step=NotImplemented, withSortKey='[deprecated name of with_sort_key]', get_redirect=NotImplemented, nofollow_redirects=NotImplemented)[source]

Iterate categories that the article is in.

Parameters:
  • with_sort_key – if True, include the sort key in each Category.
  • total – iterate no more than this number of pages in total
  • content – if True, retrieve the content of the current version of each category description page (default False)
Returns:

a generator that yields Category objects.

Return type:

generator

change_category(old_cat, new_cat, summary=None, sort_key=None, in_place=True, include=[], inPlace='[deprecated name of in_place]', sortKey='[deprecated name of sort_key]', oldCat='[deprecated name of old_cat]', comment='[deprecated name of summary]', newCat='[deprecated name of new_cat]')[source]

Remove page from oldCat and add it to newCat.

Parameters:
  • old_cat (Category) – category to be removed
  • new_cat (Category or None) – category to be added, if any
  • summary – string to use as an edit summary
  • sort_key – sortKey to use for the added category. Unused if newCat is None, or if inPlace=True If sortKey=True, the sortKey used for oldCat will be used.
  • in_place – if True, change categories in place rather than rearranging them.
  • include (list) – list of tags not to be disabled by default in relevant textlib functions, where CategoryLinks can be searched.
Returns:

True if page was saved changed, otherwise False.

Return type:

bool

clear_cache()[source]

Clear the cached attributes of the page.

content_model

Return the content model for this page.

If it cannot be reliably determined via the API, None is returned.

contributors(total=None, starttime=None, endtime=None, step=NotImplemented)[source]

Compile contributors of this page with edit counts.

Parameters:
  • total – iterate no more than this number of revisions in total
  • starttime – retrieve revisions starting at this Timestamp
  • endtime – retrieve revisions ending at this Timestamp
Returns:

number of edits for each username

Return type:

collections.Counter

coordinates(primary_only=False)[source]

Return a list of Coordinate objects for points on the page.

Uses the MediaWiki extension GeoData.

Parameters:primary_only – Only return the coordinate indicated to be primary
Returns:A list of Coordinate objects
Return type:list

Return a shortened link that points to that page.

If shared_urlshortner_wiki is defined in family config, it’ll use that site to create the link instead of the current wiki.

Parameters:
  • permalink (bool) – If true, the link will point to the actual revision of the page.
  • with_protocol (bool) – If true, and if it’s not already included, the link will have http(s) protocol prepended. On Wikimedia wikis the protocol is already present.
Returns:

The reduced link.

Return type:

str

data_item()[source]

Convenience function to get the Wikibase item of a page.

Return type:ItemPage
data_repository

Return the Site object for the data repository.

defaultsort(force=False)[source]

Extract value of the {{DEFAULTSORT:}} magic word from the page.

Parameters:force – force updating from the live site
Return type:str or None
delete(reason=None, prompt=True, mark=False, quit=False, throttle=NotImplemented)[source]

Delete the page from the wiki. Requires administrator status.

Parameters:
  • reason – The edit summary for the deletion, or rationale for deletion if requesting. If None, ask for it.
  • prompt – If true, prompt user for confirmation before deleting.
  • mark – If true, and user does not have sysop rights, place a speedy-deletion request on the page instead. If false, non-sysops will be asked before marking pages for deletion.
  • quit – show also the quit option, when asking for confirmation.
depth

Return the depth/subpage level of the page.

editTime()[source]

Return timestamp of last revision to page.

Return type:pywikibot.Timestamp
embeddedin(filter_redirects=None, namespaces=None, total=None, content=False, step=NotImplemented)[source]

Return an iterator for pages that embed this page as a template.

Parameters:
  • filter_redirects – if True, only iterate redirects; if False, omit redirects; if None, do not filter
  • namespaces – only iterate pages in these namespaces
  • total – iterate no more than this number of pages in total
  • content – if True, retrieve the content of the current version of each embedding page (default False)
exists()[source]

Return True if page exists on the wiki, even if it’s a redirect.

If the title includes a section, return False if this section isn’t found.

Return type:bool
expand_text(force=False, includecomments=False, refresh='[deprecated name of force]')[source]

Return the page text with all templates and parser words expanded.

Parameters:
  • force – force updating from the live site
  • includecomments – Also strip comments if includecomments parameter is not True.

:rtype unicode or None

Iterate all external URLs (not interwiki links) from this page.

Parameters:total – iterate no more than this number of pages in total
Returns:a generator that yields unicode objects containing URLs.
Return type:generator
full_url()[source]

Return the full URL.

get(force=False, get_redirect=False, sysop=False, expandtemplates=NotImplemented, throttle=NotImplemented, change_edit_time=NotImplemented)[source]

Return the wiki-text of the page.

This will retrieve the page from the server if it has not been retrieved yet, or if force is True. This can raise the following exceptions that should be caught by the calling code:

Raises:
  • NoPage – The page does not exist
  • IsRedirectPage – The page is a redirect. The argument of the exception is the title of the page it redirects to.
  • SectionError – The section does not exist on a page with a # link
Parameters:
  • force – reload all page attributes, including errors.
  • get_redirect – return the redirect text, do not follow the redirect, do not raise an exception.
  • sysop – if the user has a sysop account, use it to retrieve this page
Return type:

str

getCategoryRedirectTarget()[source]

If this is a category redirect, return the target category title.

Return type:Category
getCreator()[source]

Get the first revision of the page.

DEPRECATED: Use Page.oldest_revision.

Return type:tuple(username, Timestamp)
getDeletedRevision(timestamp, content=False, retrieveText='[deprecated name of content]')[source]

Return a particular deleted revision by timestamp.

Returns:a list of [date, editor, comment, text, restoration marker]. text will be None, unless content is True (or has been retrieved earlier). If timestamp is not found, returns None.
Return type:list
getLatestEditors(total=1, limit='[deprecated name of total]')[source]

Get a list of revision information of the last total edits.

DEPRECATED: Use Page.revisions.

Parameters:total – iterate no more than this number of revisions in total
Returns:list of dict, each dict containing the username and Timestamp
Return type:list
getMovedTarget()[source]

Return a Page object for the target this Page was moved to.

DEPRECATED: Use Page.moved_target().

If this page was not moved, it will raise a NoPage exception. This method also works if the source was already deleted.

Return type:pywikibot.Page
Raises:NoPage – this page was not moved
getOldVersion(oldid, force=False, get_redirect=False, sysop=False, throttle=NotImplemented, change_edit_time=NotImplemented)[source]

Return text of an old revision of this page; same options as get().

Parameters:oldid – The revid of the revision desired.
Return type:str
getRedirectTarget()[source]

Return a Page object for the target this Page redirects to.

If this page is not a redirect page, will raise an IsNotRedirectPage exception. This method also can raise a NoPage exception.

Return type:pywikibot.Page
getReferences(follow_redirects=True, with_template_inclusion=True, only_template_inclusion=False, filter_redirects=False, namespaces=None, total=None, content=False, step=NotImplemented, onlyTemplateInclusion='[deprecated name of only_template_inclusion]', redirectsOnly='[deprecated name of filter_redirects]', withTemplateInclusion='[deprecated name of with_template_inclusion]')[source]

Return an iterator all pages that refer to or embed the page.

If you need a full list of referring pages, use pages = list(s.getReferences())

Parameters:
  • follow_redirects – if True, also iterate pages that link to a redirect pointing to the page.
  • with_template_inclusion – if True, also iterate pages where self is used as a template.
  • only_template_inclusion – if True, only iterate pages where self is used as a template.
  • filter_redirects – if True, only iterate redirects to self.
  • namespaces – only iterate pages in these namespaces
  • total – iterate no more than this number of pages in total
  • content – if True, retrieve the content of the current version of each referring page (default False)
Return type:

typing.Iterable[pywikibot.Page]

getVersionHistoryTable(reverse=False, total=None, step=NotImplemented, forceReload=NotImplemented, reverseOrder='[deprecated name of reverse]')[source]

Return the version history as a wiki table.

image_repository

Return the Site object for the image repository.

Iterate FilePage objects for images displayed on this Page.

Parameters:
  • total – iterate no more than this number of pages in total
  • content – if True, retrieve the content of the current version of each image description page (default False)
Returns:

a generator that yields FilePage objects.

interwiki(expand=True)[source]

Iterate interwiki links in the page text, excluding language links.

Parameters:expand (bool) – if True (default), include interwiki links found in templates transcluded onto this page; if False, only iterate interwiki links found in this page’s own wikitext
Returns:a generator that yields Link objects
Return type:generator
isAutoTitle()[source]

Return True if title of this Page is in the autoFormat dict.

isCategoryRedirect()[source]

Return True if this is a category redirect page, False otherwise.

Return type:bool
isDisambig()[source]

Return True if this is a disambiguation page, False otherwise.

By default, it uses the the Disambiguator extension’s result. The identification relies on the presence of the __DISAMBIG__ magic word which may also be transcluded.

If the Disambiguator extension isn’t activated for the given site, the identification relies on the presence of specific templates. First load a list of template names from the Family file; if the value in the Family file is None or no entry was made, look for the list on [[MediaWiki:Disambiguationspage]]. If this page does not exist, take the MediaWiki message. ‘Template:Disambig’ is always assumed to be default, and will be appended regardless of its existence.

Return type:bool
isIpEdit()[source]

Return True if last editor was unregistered.

Return type:bool
isRedirectPage()[source]

Return True if this is a redirect, False if not or not existing.

isStaticRedirect(force=False)[source]

Determine whether the page is a static redirect.

A static redirect must be a valid redirect, and contain the magic word __STATICREDIRECT__.

Parameters:force (bool) – Bypass local caching
Return type:bool
isTalkPage()[source]

Return True if this page is in any talk namespace.

is_categorypage()[source]

Return True if the page is a Category, False otherwise.

is_filepage()[source]

Return True if this is an file description page, False otherwise.

is_flow_page()[source]

Whether a page is a Flow page.

Return type:bool

Iterate all inter-language links on this page.

Parameters:
  • total – iterate no more than this number of pages in total
  • include_obsolete (bool) – if true, yield even Link object whose site is obsolete
Returns:

a generator that yields Link objects.

Return type:

generator

itertemplates(total=None, content=False, step=NotImplemented)[source]

Iterate Page objects for templates used on this Page.

Template parameters are ignored. This method only returns embedded templates, not template pages that happen to be referenced through a normal link.

Parameters:
  • total – iterate no more than this number of pages in total
  • content – if True, retrieve the content of the current version of each template (default False)
  • content – bool

Return a list of all inter-language Links on this page.

Parameters:include_obsolete (bool) – if true, return even Link objects whose site is obsolete
Returns:list of Link objects.
Return type:list
lastNonBotUser()[source]

Return name or IP address of last human/non-bot user to edit page.

Determine the most recent human editor out of the last revisions. If it was not able to retrieve a human user, returns None.

If the edit was done by a bot which is no longer flagged as ‘bot’, i.e. which is not returned by Site.botusers(), it will be returned as a non-bot edit.

Return type:str
latest_revision

Return the current revision for this page.

latest_revision_id

Return the current revision id for this page.

linkedPages(namespaces=None, total=None, content=False, step=NotImplemented)[source]

Iterate Pages that this Page links to.

Only returns pages from “normal” internal links. Image and category links are omitted unless prefixed with “:”. Embedded templates are omitted (but links within them are returned). All interwiki and external links are omitted.

Parameters:
  • namespaces – only iterate links in these namespaces
  • namespaces – int, or list of ints
  • total (int) – iterate no more than this number of pages in total
  • content (bool) – if True, retrieve the content of the current version of each linked page (default False)
Returns:

a generator that yields Page objects.

Return type:

generator

loadDeletedRevisions(total=None, step=NotImplemented)[source]

Retrieve deleted revisions for this Page.

Stores all revisions’ timestamps, dates, editors and comments in self._deletedRevs attribute.

Returns:iterator of timestamps (which can be used to retrieve revisions later on).
Return type:generator
markDeletedRevision(timestamp, undelete=True)[source]

Mark the revision identified by timestamp for undeletion.

Parameters:undelete (bool) – if False, mark the revision to remain deleted.
merge_history(dest, timestamp=None, reason=None)[source]

Merge revisions from this page into another page.

See APISite.merge_history for details.

Parameters:
  • dest (pywikibot.Page) – Destination page to which revisions will be merged
  • timestamp (pywikibot.Timestamp) – Revisions from this page dating up to this timestamp will be merged into the destination page (if not given or False, all revisions will be merged)
  • reason (str) – Optional reason for the history merge
move(newtitle, reason=None, movetalk=True, sysop=False, noredirect=False, movetalkpage='[deprecated name of movetalk]', throttle=NotImplemented, deleteAndMove='[deprecated name of noredirect]')[source]

Move this page to a new title.

Parameters:
  • newtitle – The new page title.
  • reason – The edit summary for the move.
  • movetalk – If true, move this page’s talk page (if it exists)
  • sysop – Try to move using sysop account, if available
  • noredirect – if move succeeds, delete the old page (usually requires sysop privileges, depending on wiki settings)
moved_target()[source]

Return a Page object for the target this Page was moved to.

If this page was not moved, it will raise a NoMoveTarget exception. This method also works if the source was already deleted.

Return type:pywikibot.Page
Raises:NoMoveTarget – this page was not moved
namespace()[source]

Return the namespace of the page.

Returns:namespace of the page
Return type:pywikibot.Namespace
oldest_revision

Return the first revision of this page.

Return type:Revision
page_image()[source]

Return the most appropriate image on the page.

Uses the MediaWiki extension PageImages.

Returns:A FilePage object
Return type:FilePage
pageid

Return pageid of the page.

Returns:pageid or 0 if page does not exist
Return type:int

Return the permalink URL of an old revision of this page.

Parameters:
  • oldid – The revid of the revision desired.
  • percent_encoded – if false, the link will be provided without title uncoded.
  • with_protocol – if true, http or https prefixes will be included before the double slash.
Return type:

str

preloadText()[source]

The text returned by EditFormPreloadText.

See API module “info”.

Application: on Wikisource wikis, text can be preloaded even if a page does not exist, if an Index page is present.

Return type:str
previousRevision()[source]

Return the revision id for the previous revision.

DEPRECATED: Use latest_revision.parent_id instead.

Return type:int
Raises:AssertionError – Use on MediaWiki prior to v1.16.
properties(force=False)[source]

Return the properties of the page.

Parameters:force – force updating from the live site
Return type:dict
protect(edit=False, move=False, create=None, upload=None, unprotect=False, reason=None, prompt=None, protections=None, **kwargs, throttle=NotImplemented)[source]

Protect or unprotect a wiki page. Requires administrator status.

Valid protection levels (in MediaWiki 1.12) are ‘’ (equivalent to ‘none’), ‘autoconfirmed’, and ‘sysop’. If None is given, however, that protection will be skipped.

Parameters:
  • protections (dict) – A dict mapping type of protection to protection level of that type.
  • reason (basestring) – Reason for the action
  • prompt (bool) – Whether to ask user for confirmation (deprecated). Defaults to protections is None
protection()[source]

Return a dictionary reflecting page protections.

Return type:dict
purge(**kwargs)[source]

Purge the server’s cache for this page.

Keyword Arguments:
 
  • redirects – Automatically resolve redirects.
  • converttitles – Convert titles to other variants if necessary. Only works if the wiki’s content language supports variant conversion.
  • forcelinkupdate – Update the links tables.
  • forcerecursivelinkupdate – Update the links table, and update the links tables for any page that uses this page as a template.
Return type:

bool

put(newtext, summary=None, watch=None, minor=True, botflag=None, force=False, asynchronous=False, callback=None, **kwargs, watchArticle='[deprecated name of watch]', comment='[deprecated name of summary]', minorEdit='[deprecated name of minor]', async='[deprecated name of asynchronous]')[source]

Save the page with the contents of the first argument as the text.

This method is maintained primarily for backwards-compatibility. For new code, using Page.save() is preferred. See save() method docs for all parameters not listed here.

Parameters:newtext (str) – The complete text of the revised page.
revision_count(contributors=None)[source]

Determine number of edits from a set of contributors.

Parameters:contributors (iterable of str) – contributor usernames
Returns:number of edits for all provided usernames
Return type:int
revisions(reverse=False, total=None, content=False, rollback=False, starttime=None, endtime=None, step=NotImplemented, reverseOrder='[deprecated name of reverse]', getText='[deprecated name of content]')[source]

Generator which loads the version history as Revision instances.

save(summary=None, watch=None, minor=True, botflag=None, force=False, asynchronous=False, callback=None, apply_cosmetic_changes=None, quiet=False, **kwargs, sysop=NotImplemented, comment='[deprecated name of summary]', async='[deprecated name of asynchronous]')[source]

Save the current contents of page’s text to the wiki.

Parameters:
  • summary (str) – The edit summary for the modification (optional, but most wikis strongly encourage its use)
  • watch (str, bool (deprecated) or None) –

    Specify how the watchlist is affected by this edit, set to one of “watch”, “unwatch”, “preferences”, “nochange”: * watch: add the page to the watchlist * unwatch: remove the page from the watchlist * preferences: use the preference settings (Default) * nochange: don’t change the watchlist If None (default), follow bot account’s default settings

    For backward compatibility watch parameter may also be boolean: if True, add or if False, remove this Page to/from bot user’s watchlist.

  • minor (bool) – if True, mark this edit as minor
  • botflag – if True, mark this edit as made by a bot (default: True if user has bot status, False if not)
  • force (bool) – if True, ignore botMayEdit() setting
  • asynchronous – if True, launch a separate thread to save asynchronously
  • callback – a callable object that will be called after the page put operation. This object must take two arguments: (1) a Page object, and (2) an exception instance, which will be None if the page was saved successfully. The callback is intended for use by bots that need to keep track of which saves were successful.
  • apply_cosmetic_changes (bool or None) – Overwrites the cosmetic_changes configuration value to this value unless it’s None.
  • quiet (bool) – enable/disable successful save operation message; defaults to False. In asynchronous mode, if True, it is up to the calling bot to manage the output e.g. via callback.
section()[source]

Return the name of the section this Page refers to.

The section is the part of the title following a ‘#’ character, if any. If no section is present, return None.

Return type:str or None
site

Return the Site object for the wiki on which this Page resides.

Return type:pywikibot.Site
templates(content=False, get_redirect=NotImplemented)[source]

Return a list of Page objects for templates used on this Page.

Template parameters are ignored. This method only returns embedded templates, not template pages that happen to be referenced through a normal link.

Parameters:
  • content – if True, retrieve the content of the current version of each template (default False)
  • content – bool
text

Return the current (edited) wikitext, loading it if necessary.

Returns:text of the page
Return type:str
title(underscore=False, with_ns=True, with_section=True, as_url=False, as_link=False, allow_interwiki=True, force_interwiki=False, textlink=False, as_filename=False, insite=None, without_brackets=False, forceInterwiki='[deprecated name of force_interwiki]', withNamespace='[deprecated name of with_ns]', asLink='[deprecated name of as_link]', decode=NotImplemented, allowInterwiki='[deprecated name of allow_interwiki]', asUrl='[deprecated name of as_url]', withSection='[deprecated name of with_section]', savetitle='[deprecated name of as_url]')[source]

Return the title of this Page, as a Unicode string.

Parameters:
  • underscore – (not used with as_link) if true, replace all ‘ ‘ characters with ‘_’
  • with_ns – if false, omit the namespace prefix. If this option is false and used together with as_link return a labeled link like [[link|label]]
  • with_section – if false, omit the section
  • as_url – (not used with as_link) if true, quote title as if in an URL
  • as_link – if true, return the title in the form of a wikilink
  • allow_interwiki – (only used if as_link is true) if true, format the link as an interwiki link if necessary
  • force_interwiki – (only used if as_link is true) if true, always format the link as an interwiki link
  • textlink – (only used if as_link is true) if true, place a ‘:’ before Category: and Image: links
  • as_filename – (not used with as_link) if true, replace any characters that are unsafe in filenames
  • insite – (only used if as_link is true) a site object where the title is to be shown. default is the current family/lang given by -family and -lang option i.e. config.family and config.mylang
  • without_brackets – (cannot be used with as_link) if true, remove the last pair of brackets(usually removes disambiguation brackets).
Return type:

str

toggleTalkPage()[source]

Return other member of the article-talk page pair for this Page.

If self is a talk page, returns the associated content page; otherwise, returns the associated talk page. The returned page need not actually exist on the wiki.

Returns:Page or None if self is a special page.
Return type:typing.Optional[pywikibot.Page]
touch(callback=None, botflag=False, **kwargs)[source]

Make a touch edit for this page.

See save() method docs for all parameters. The following parameters will be overridden by this method: - summary, watch, minor, force, asynchronous

Parameter botflag is False by default.

minor and botflag parameters are set to False which prevents hiding the edit when it becomes a real edit due to a bug.

undelete(reason=None, comment='[deprecated name of reason]', throttle=NotImplemented)[source]

Undelete revisions based on the markers set by previous calls.

If no calls have been made since loadDeletedRevisions(), everything will be restored.

Simplest case:

Page(...).undelete('This will restore all revisions')

More complex:

pg = Page(...)
revs = pg.loadDeletedRevisions()
for rev in revs:
    if ... #decide whether to undelete a revision
        pg.markDeletedRevision(rev) #mark for undeletion
pg.undelete('This will restore only selected revisions.')
Parameters:reason (basestring) – Reason for the action.
urlname()[source]

Return the Page title encoded for use in an URL.

DEPRECATED: use self.title(as_url=True) instead.

userName()[source]

Return name or IP address of last user to edit page.

Return type:str
version()[source]

Return MediaWiki version number of the page site.

This is needed to use @need_version() decorator for methods of Page objects.

watch(unwatch=False)[source]

Add or remove this page to/from bot account’s watchlist.

Parameters:unwatch (bool) – True to unwatch, False (default) to watch.
Returns:True if successful, False otherwise.
Return type:bool
class pywikibot.page.Page(source, title='', ns=0, defaultNamespace='[deprecated name of ns]', insite=NotImplemented)[source]

Bases: pywikibot.page.BasePage

Page: A MediaWiki page.

__init__(source, title='', ns=0, defaultNamespace='[deprecated name of ns]', insite=NotImplemented)[source]

Instantiate a Page object.

__module__ = 'pywikibot.page'
raw_extracted_templates

Extract templates using textlib.extract_templates_and_params.

Disabled parts and whitespace are stripped, except for whitespace in anonymous positional arguments.

This value is cached.

Return type:list of (str, OrderedDict)
set_redirect_target(target_page, create=False, force=False, keep_section=False, save=True, **kwargs)[source]

Change the page’s text to point to the redirect page.

Parameters:
  • target_page (pywikibot.Page or string) – target of the redirect, this argument is required.
  • create (bool) – if true, it creates the redirect even if the page doesn’t exist.
  • force (bool) – if true, it set the redirect target even the page doesn’t exist or it’s not redirect.
  • keep_section (bool) – if the old redirect links to a section and the new one doesn’t it uses the old redirect’s section.
  • save (bool) – if true, it saves the page immediately.
  • kwargs – Arguments which are used for saving the page directly afterwards, like ‘summary’ for edit summary.
templatesWithParams(get_redirect=NotImplemented)[source]

Return templates used on this Page.

The templates are extracted by textlib.extract_templates_and_params, with positional arguments placed first in order, and each named argument appearing as ‘name=value’.

All parameter keys and values for each template are stripped of whitespace.

Returns:a list of tuples with one tuple for each template invocation in the page, with the template Page as the first entry and a list of parameters as the second entry.
Return type:list of (Page, list)
class pywikibot.page.FilePage(source, title='', insite=NotImplemented)[source]

Bases: pywikibot.page.Page

A subclass of Page representing a file description page.

Supports the same interface as Page, with some added methods.

__init__(source, title='', insite=NotImplemented)[source]

Initializer.

__module__ = 'pywikibot.page'
download(filename=None, chunk_size=102400, revision=None)[source]

Download to filename file of FilePage.

Parameters:
  • filename (None or str) – filename where to save file: None: self.title(as_filename=True, with_ns=False) will be used str: provided filename will be used.
  • chunk_size (int) – the size of each chunk to be received and written to file.
  • revision (None or FileInfo) – file revision to download: None: self.latest_file_info will be used FileInfo: provided revision will be used.
Returns:

True if download is successful, False otherwise.

Raise:

IOError if filename cannot be written for any reason.

fileIsOnCommons()[source]

DEPRECATED. Check if the image is stored on Wikimedia Commons.

Return type:bool
fileIsShared()[source]

Check if the file is stored on any known shared repository.

Return type:bool
getFileVersionHistoryTable()[source]

Return the version history in the form of a wiki table.

getImagePageHtml()[source]

Download the file page, and return the HTML, as a unicode string.

Caches the HTML code, so that if you run this method twice on the same FilePage object, the page will only be downloaded once.

get_file_history()[source]

Return the file’s version history.

Returns:dictionary with: key: timestamp of the entry value: instance of FileInfo()
Return type:dict
get_file_url(url_width=None, url_height=None, url_param=None)[source]

Return the url or the thumburl of the file described on this page.

Fetch the information if not available.

Once retrieved, thumburl information will also be accessible as latest_file_info attributes, named as in [1]: - url, thumburl, thumbwidth and thumbheight

Parameters correspond to iiprops in: [1] https://www.mediawiki.org/wiki/API:Imageinfo

Parameters validation and error handling left to the API call.

Parameters:
  • url_width – see iiurlwidth in [1]
  • url_height – see iiurlheigth in [1]
  • url_param – see iiurlparam in [1]
Returns:

latest file url or thumburl

Return type:

str

globalusage(total=None)[source]

Iterate all global usage for this page.

Parameters:total – iterate no more than this number of pages in total
Returns:a generator that yields Pages also on sites different from self.site.
Return type:generator
latest_file_info

Retrieve and store information of latest Image rev. of FilePage.

At the same time, the whole history of Image is fetched and cached in self._file_revisions

Returns:instance of FileInfo()
oldest_file_info

Retrieve and store information of oldest Image rev. of FilePage.

At the same time, the whole history of Image is fetched and cached in self._file_revisions

Returns:instance of FileInfo()
upload(source, **kwargs)[source]

Upload this file to the wiki.

keyword arguments are from site.upload() method.

Parameters:

source (str) – Path or URL to the file to be uploaded.

Keyword Arguments:
 
  • comment – Edit summary; if this is not provided, then filepage.text will be used. An empty summary is not permitted. This may also serve as the initial page text (see below).
  • text – Initial page text; if this is not set, then filepage.text will be used, or comment.
  • watch – If true, add filepage to the bot user’s watchlist
  • ignore_warnings – It may be a static boolean, a callable returning a boolean or an iterable. The callable gets a list of UploadWarning instances and the iterable should contain the warning codes for which an equivalent callable would return True if all UploadWarning codes are in thet list. If the result is False it’ll not continue uploading the file and otherwise disable any warning and reattempt to upload the file. NOTE: If report_success is True or None it’ll raise an UploadWarning exception if the static boolean is False.
  • chunk_size – The chunk size in bytesfor chunked uploading (see https://www.mediawiki.org/wiki/API:Upload#Chunked_uploading). It will only upload in chunks, if the version number is 1.20 or higher and the chunk size is positive but lower than the file size.
  • _file_key – Reuses an already uploaded file using the filekey. If None (default) it will upload the file.
  • _offset – When file_key is not None this can be an integer to continue a previously canceled chunked upload. If False it treats that as a finished upload. If True it requests the stash info from the server to determine the offset. By default starts at 0.
  • _verify_stash – Requests the SHA1 and file size uploaded and compares it to the local file. Also verifies that _offset is matching the file size if the _offset is an int. If _offset is False if verifies that the file size match with the local file. If None it’ll verifies the stash when a file key and offset is given.
  • report_success – If the upload was successful it’ll print a success message and if ignore_warnings is set to False it’ll raise an UploadWarning if a warning occurred. If it’s None (default) it’ll be True if ignore_warnings is a bool and False otherwise. If it’s True or None ignore_warnings must be a bool.
Returns:

It returns True if the upload was successful and False otherwise.

Return type:

bool

usingPages(total=None, content=False, step=NotImplemented)[source]

Yield Pages on which the file is displayed.

Parameters:
  • total – iterate no more than this number of pages in total
  • content – if True, load the current content of each iterated page (default False)
class pywikibot.page.Category(source, title='', sort_key=None, insite=NotImplemented, sortKey='[deprecated name of sort_key]')[source]

Bases: pywikibot.page.Page

A page in the Category: namespace.

__init__(source, title='', sort_key=None, insite=NotImplemented, sortKey='[deprecated name of sort_key]')[source]

Initializer.

All parameters are the same as for Page() Initializer.

__module__ = 'pywikibot.page'
articles(recurse=False, total=None, content=False, namespaces=None, sortby=None, reverse=False, starttime=None, endtime=None, startsort=None, endsort=None, startprefix=None, endprefix=None, startFrom='[deprecated name of startprefix]', step=NotImplemented)[source]

Yield all articles in the current category.

By default, yields all pages in the category that are not subcategories!

Parameters:
  • recurse (int or bool) – if not False or 0, also iterate articles in subcategories. If an int, limit recursion to this number of levels. (Example: recurse=1 will iterate articles in first-level subcats, but no deeper.)
  • total – iterate no more than this number of pages in total (at all levels)
  • namespaces (int or list of ints) – only yield pages in the specified namespaces
  • content – if True, retrieve the content of the current version of each page (default False)
  • sortby (str) – determines the order in which results are generated, valid values are “sortkey” (default, results ordered by category sort key) or “timestamp” (results ordered by time page was added to the category). This applies recursively.
  • reverse – if True, generate results in reverse order (default False)
  • starttime (pywikibot.Timestamp) – if provided, only generate pages added after this time; not valid unless sortby=”timestamp”
  • endtime (pywikibot.Timestamp) – if provided, only generate pages added before this time; not valid unless sortby=”timestamp”
  • startsort (str) – if provided, only generate pages that have a sortkey >= startsort; not valid if sortby=”timestamp” (Deprecated in MW 1.24)
  • endsort (str) – if provided, only generate pages that have a sortkey <= endsort; not valid if sortby=”timestamp” (Deprecated in MW 1.24)
  • startprefix (str) – if provided, only generate pages >= this title lexically; not valid if sortby=”timestamp”; overrides “startsort” (requires MW 1.18+)
  • endprefix (str) – if provided, only generate pages < this title lexically; not valid if sortby=”timestamp”; overrides “endsort” (requires MW 1.18+)
Return type:

typing.Iterable[pywikibot.Page]

Return a link to place a page in this Category.

Use this only to generate a “true” category link, not for interwikis or text links to category pages.

Parameters:sort_key ((optional) unicode) – The sort key for the article to be placed in this Category; if omitted, default sort key is used.
categoryinfo

Return a dict containing information about the category.

The dict contains values for:

Numbers of pages, subcategories, files, and total contents.

Return type:dict
copyAndKeep(catname, cfd_templates, message, cfdTemplates='[deprecated name of cfd_templates]')[source]

Copy partial category page text (not contents) to a new title.

Like copyTo above, except this removes a list of templates (like deletion templates) that appear in the old category text. It also removes all text between the two HTML comments BEGIN CFD TEMPLATE and END CFD TEMPLATE. (This is to deal with CFD templates that are substituted.)

Returns true if copying was successful, false if target page already existed.

Parameters:
  • catname – New category title (without namespace)
  • cfd_templates – A list (or iterator) of templates to be removed from the page text
Returns:

True if copying was successful, False if target page already existed.

Return type:

bool

copyTo(cat, message)[source]

Copy text of category page to a new page. Does not move contents.

Parameters:
  • cat (str or Category) – New category title (without namespace) or Category object
  • message (str) – message to use for category creation message If two %s are provided in message, will be replaced by (self.title, authorsList)
Returns:

True if copying was successful, False if target page already existed.

Return type:

bool

isEmptyCategory()[source]

Return True if category has no members (including subcategories).

Return type:bool
isHiddenCategory()[source]

Return True if the category is hidden.

Return type:bool
members(recurse=False, namespaces=None, total=None, content=False, step=NotImplemented)[source]

Yield all category contents (subcats, pages, and files).

Return type:typing.Iterable[pywikibot.Page]
newest_pages(total=None)[source]

Return pages in a category ordered by the creation date.

If two or more pages are created at the same time, the pages are returned in the order they were added to the category. The most recently added page is returned first.

It only allows to return the pages ordered from newest to oldest, as it is impossible to determine the oldest page in a category without checking all pages. But it is possible to check the category in order with the newly added first and it yields all pages which were created after the currently checked page was added (and thus there is no page created after any of the cached but added before the currently checked).

Parameters:total (int) – The total number of pages queried.
Returns:A page generator of all pages in a category ordered by the creation date. From newest to oldest. Note: It currently only returns Page instances and not a subclass of it if possible. This might change so don’t expect to only get Page instances.
Return type:generator
subcategories(recurse=False, total=None, content=False, startFrom=NotImplemented, step=NotImplemented, cacheResults=NotImplemented)[source]

Iterate all subcategories of the current category.

Parameters:
  • recurse (int or bool) – if not False or 0, also iterate subcategories of subcategories. If an int, limit recursion to this number of levels. (Example: recurse=1 will iterate direct subcats and first-level sub-sub-cats, but no deeper.)
  • total – iterate no more than this number of subcategories in total (at all levels)
  • content – if True, retrieve the content of the current version of each category description page (default False)
class pywikibot.page.User(source, title='', name='[deprecated name of title]', site='[deprecated name of source]')[source]

Bases: pywikibot.page.Page

A class that represents a Wiki user.

This class also represents the Wiki page User:<username>

__init__(source, title='', name='[deprecated name of title]', site='[deprecated name of source]')[source]

Initializer for a User object.

All parameters are the same as for Page() Initializer.

__module__ = 'pywikibot.page'
block(*args, **kwargs)[source]

Block user.

Refer APISite.blockuser method for parameters.

Returns:None
contributions(total=500, **kwargs, namespace='[deprecated name of namespaces]', limit='[deprecated name of total]')[source]

Yield tuples describing this user edits.

Each tuple is composed of a pywikibot.Page object, the revision id (int), the edit timestamp (as a pywikibot.Timestamp object), and the comment (unicode). Pages returned are not guaranteed to be unique.

Parameters:

total (int) – limit result to this number of pages

Keyword Arguments:
 
  • start – Iterate contributions starting at this Timestamp
  • end – Iterate contributions ending at this Timestamp
  • reverse – Iterate oldest contributions first (default: newest)
  • namespaces – only iterate pages in these namespaces
  • showMinor – if True, iterate only minor edits; if False and not None, iterate only non-minor edits (default: iterate both)
  • top_only – if True, iterate only edits which are the latest revision (default: False)
Returns:

tuple of pywikibot.Page, revid, pywikibot.Timestamp, comment

Return type:

tuple

editCount(force=False)[source]

Return edit count for a registered user.

Always returns 0 for ‘anonymous’ users.

Parameters:force (bool) – if True, forces reloading the data from API
Return type:int
editedPages(total=500, limit='[deprecated name of total]')[source]

DEPRECATED. Use contributions().

Yields pywikibot.Page objects that this user has edited, with an upper bound of ‘total’. Pages returned are not guaranteed to be unique.

Parameters:total (int.) – limit result to this number of pages.
first_edit

Return first user contribution.

Returns:first user contribution entry
Returns:tuple of pywikibot.Page, revid, pywikibot.Timestamp, comment
Return type:tuple or None
gender(force=False)[source]

Return the gender of the user.

Parameters:force (bool) – if True, forces reloading the data from API
Returns:return ‘male’, ‘female’, or ‘unknown’
Return type:str
getUserPage(subpage='')[source]

Return a Page object relative to this user’s main page.

Parameters:subpage (str) – subpage part to be appended to the main page title (optional)
Returns:Page object of user page or user subpage
Return type:pywikibot.Page
getUserTalkPage(subpage='')[source]

Return a Page object relative to this user’s main talk page.

Parameters:subpage (str) – subpage part to be appended to the main talk page title (optional)
Returns:Page object of user talk page or user talk subpage
Return type:pywikibot.Page
getprops(force=False)[source]

Return a properties about the user.

Parameters:force (bool) – if True, forces reloading the data from API
Return type:dict
groups(force=False)[source]

Return a list of groups to which this user belongs.

The list of groups may be empty.

Parameters:force (bool) – if True, forces reloading the data from API
Returns:groups property
Return type:list
isAnonymous()[source]

Determine if the user is editing as an IP address.

Return type:bool
isBlocked(force=False)[source]

Determine whether the user is currently blocked.

Parameters:force (bool) – if True, forces reloading the data from API
Return type:bool
isEmailable(force=False)[source]

Determine whether emails may be send to this user through MediaWiki.

Parameters:force (bool) – if True, forces reloading the data from API
Return type:bool
isRegistered(force=False)[source]

Determine if the user is registered on the site.

It is possible to have a page named User:xyz and not have a corresponding user with username xyz.

The page does not need to exist for this method to return True.

Parameters:force (bool) – if True, forces reloading the data from API
Return type:bool
is_thankable

Determine if the user has thanks notifications enabled.

NOTE: This doesn’t accurately determine if thanks is enabled for user.
Privacy of thanks preferences is under discussion, please see https://phabricator.wikimedia.org/T57401#2216861, and https://phabricator.wikimedia.org/T120753#1863894
Return type:bool
last_edit

Return last user contribution.

Returns:last user contribution entry
Returns:tuple of pywikibot.Page, revid, pywikibot.Timestamp, comment
Return type:tuple or None
last_event

Return last user activity.

Returns:last user log entry
Return type:LogEntry or None
logevents(**kwargs)[source]

Yield user activities.

Keyword Arguments:
 
  • logtype – only iterate entries of this type (see mediawiki api documentation for available types)
  • page – only iterate entries affecting this page
  • namespace – namespace to retrieve logevents from
  • start – only iterate entries from and after this Timestamp
  • end – only iterate entries up to and through this Timestamp
  • reverse – if True, iterate oldest entries first (default: newest)
  • tag – only iterate entries tagged with this tag
  • total – maximum number of events to iterate
Return type:

iterable

name()[source]

The username.

DEPRECATED: use username instead.

Return type:str
registration(force=False)[source]

Fetch registration date for this user.

Parameters:force (bool) – if True, forces reloading the data from API
Return type:pywikibot.Timestamp or None
registrationTime(force=False)[source]

DEPRECATED. Fetch registration date for this user.

Parameters:force (bool) – if True, forces reloading the data from API
Returns:int (MediaWiki’s internal timestamp format) or 0
Return type:int
rights(force=False)[source]

Return user rights.

Parameters:force (bool) – if True, forces reloading the data from API
Returns:return user rights
Return type:list
send_email(subject, text, ccme=False)[source]

Send an email to this user via MediaWiki’s email interface.

Parameters:
  • subject (str) – the subject header of the mail
  • text (str) – mail body
  • ccme (bool) – if True, sends a copy of this email to the bot
Raises:
Returns:

operation successful indicator

Return type:

bool

unblock(reason=None)[source]

Remove the block for the user.

Parameters:reason (basestring) – Reason for the unblock.
uploadedImages(total=10, number='[deprecated name of total]')[source]

Yield tuples describing files uploaded by this user.

Each tuple is composed of a pywikibot.Page, the timestamp (str in ISO8601 format), comment (unicode) and a bool for pageid > 0. Pages returned are not guaranteed to be unique.

Parameters:total (int) – limit result to this number of pages
username

The username.

Convenience method that returns the title of the page with namespace prefix omitted, which is the username.

Return type:str
class pywikibot.page.WikibasePage(site, title='', **kwargs)[source]

Bases: pywikibot.page.BasePage, pywikibot.page.WikibaseEntity

The base page for the Wikibase extension.

There should be no need to instantiate this directly.

__delattr__(attr)[source]

Attribute deleter. Deprecates lastrevid.

__getattribute__(name)[source]

Low-level attribute getter. Deprecates lastrevid.

__init__(site, title='', **kwargs)[source]

Initializer.

If title is provided, either ns or entity_type must also be provided, and will be checked against the title parsed using the Page initialisation logic.

Parameters:
  • site (DataSite) – Wikibase data site
  • title (str) – normalized title of the page
Keyword Arguments:
 
  • ns – namespace
  • entity_type – Wikibase entity type
Raises:
  • TypeError – incorrect use of parameters
  • ValueError – incorrect namespace
  • pywikibot.Error – title parsing problems
  • NotImplementedError – the entity type is not supported
__module__ = 'pywikibot.page'
__setattr__(attr, value)[source]

Attribute setter. Deprecates lastrevid.

addClaim(claim, bot=True, **kwargs)[source]

Add a claim to the entity.

Parameters:
  • claim (Claim) – The claim to add
  • bot (bool) – Whether to flag as bot (if possible)
Keyword Arguments:
 
  • asynchronous – if True, launch a separate thread to add claim asynchronously
  • callback – a callable object that will be called after the claim has been added. It must take two arguments: (1) a WikibasePage object, and (2) an exception instance, which will be None if the entity was saved successfully. This is intended for use by bots that need to keep track of which saves were successful.
botMayEdit()[source]

Return whether bots may edit this page.

Because there is currently no system to mark a page that it shouldn’t be edited by bots on Wikibase pages it always returns True. The content of the page is not text but a dict, the original way (to search for a template) doesn’t apply.

Returns:True
Return type:bool
editAliases(aliases, **kwargs)[source]

Edit entity aliases.

Aliases should be a dict, with the key as a language or a site object. The value should be a list of strings.

editDescriptions(descriptions, **kwargs)[source]

Edit entity descriptions.

Descriptions should be a dict, with the key as a language or a site object. The value should be the string to set it to. You can set it to ‘’ to remove the description.

editEntity(data=None, **kwargs)[source]

Edit an entity using Wikibase wbeditentity API.

This function is wrapped around by:
  • editLabels
  • editDescriptions
  • editAliases
  • ItemPage.setSitelinks
Parameters:

data (dict, or None to save the current content of the entity.) – Data to be saved

Keyword Arguments:
 
  • asynchronous – if True, launch a separate thread to edit asynchronously
  • callback – a callable object that will be called after the entity has been updated. It must take two arguments: (1) a WikibasePage object, and (2) an exception instance, which will be None if the page was saved successfully. This is intended for use by bots that need to keep track of which saves were successful.
editLabels(labels, **kwargs)[source]

Edit entity labels.

Labels should be a dict, with the key as a language or a site object. The value should be the string to set it to. You can set it to ‘’ to remove the label.

exists()[source]

Determine if an entity exists in the data repository.

Return type:bool
get(force=False, *args, **kwargs)[source]

Fetch all page data, and cache it.

Parameters:force (bool) – override caching
Raises:NotImplementedError – a value in args or kwargs
Returns:actual data which entity holds
Return type:dict
Note:dicts returned by this method are references to content of this entity and their modifying may indirectly cause unwanted change to the live content
getdbName(site)[source]

Helper function to obtain a dbName for a Site.

Parameters:site (Site) – The site to look up.
latest_revision_id

Get the revision identifier for the most recent revision of the entity.

Return type:int
namespace()[source]