pywikibot package

The initialization file for the Pywikibot framework.

exception pywikibot.BadTitle(arg: str)[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.

property site

Get the current site.

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

Bases: pywikibot.exceptions.Error

Captcha is asked and config.solve_captcha == False.

__module__ = 'pywikibot.exceptions'
exception pywikibot.CascadeLockedPage(page, message: Optional[str] = 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: str = '', sort_key=None, sortKey='[deprecated name of sort_key]')[source]

Bases: pywikibot.page.Page

A page in the Category: namespace.

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

Initializer.

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

__module__ = 'pywikibot.page'
articles(recurse: int = False, total: Optional[int] = None, content: bool = False, namespaces: Union[int, List[int]] = None, sortby: Optional[str] = None, reverse: bool = False, starttime=None, endtime=None, startsort: Optional[str] = None, endsort: Optional[str] = None, startprefix: Optional[str] = None, endprefix: Optional[str] = None, startFrom='[deprecated name of startprefix]')[source]

Yield all articles in the current category.

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

Parameters
  • recurse – 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 – only yield pages in the specified namespaces

  • content – if True, retrieve the content of the current version of each page (default False)

  • sortby – 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 – if provided, only generate pages that have a sortkey >= startsort; not valid if sortby=”timestamp” (Deprecated in MW 1.24)

  • endsort – if provided, only generate pages that have a sortkey <= endsort; not valid if sortby=”timestamp” (Deprecated in MW 1.24)

  • startprefix – if provided, only generate pages >= this title lexically; not valid if sortby=”timestamp”; overrides “startsort”

  • endprefix – if provided, only generate pages < this title lexically; not valid if sortby=”timestamp”; overrides “endsort”

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 – The sort key for the article to be placed in this Category; if omitted, default sort key is used.

property categoryinfo

Return a dict containing information about the category.

The dict contains values for:

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

isEmptyCategory() → bool[source]

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

isHiddenCategory() → bool[source]

Return True if the category is hidden.

members(recurse: bool = False, namespaces=None, total: Optional[int] = None, content=False)[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: int = False, total: Optional[int] = None, content: bool = False)[source]

Iterate all subcategories of the current category.

Parameters
  • recurse – 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: Optional[str] = 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', isQualifier='[deprecated name of is_qualifier]', isReference='[deprecated name of is_reference]', **kwargs)[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 _WbDataPage.fromWikibase of <class 'pywikibot.WbGeoShape'>>, 'globe-coordinate': <bound method Coordinate.fromWikibase of <class 'pywikibot.Coordinate'>>, 'monolingualtext': <function Claim.<lambda>>, 'quantity': <bound method WbQuantity.fromWikibase of <class 'pywikibot.WbQuantity'>>, 'tabular-data': <bound method _WbDataPage.fromWikibase of <class 'pywikibot.WbTabularData'>>, 'time': <bound method WbTime.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', isQualifier='[deprecated name of is_qualifier]', isReference='[deprecated name of is_reference]', **kwargs)[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 (pywikibot.page.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

pywikibot.page.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

pywikibot.page.Claim

getRank()[source]

Return the rank of the Claim.

getSnakType() → str[source]

Return the type of snak.

Returns

str (‘value’, ‘somevalue’ or ‘novalue’)

getSources() → list[source]

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

getTarget()[source]

Return the target value of this Claim.

None is returned if no target is set

Returns

object

has_qualifier(qualifier_id: str, target) → bool[source]

Check whether Claim contains specified qualifier.

Parameters
  • qualifier_id – id of the qualifier

  • target – qualifier target to check presence of

Returns

true if the qualifier was found, false otherwise

property on_item

Return item this claim is attached to.

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

pywikibot.page.Claim

classmethod referenceFromJSON(site, data) → dict[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.

removeQualifier(qualifier, **kwargs)[source]

Remove the qualifier. Call removeQualifiers().

Parameters

qualifier (pywikibot.page.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

same_as(other, ignore_rank=True, ignore_quals=False, ignore_refs=True)[source]

Check if two claims are same.

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) → bool[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

toJSON() → dict[source]

Create dict suitable for the MediaWiki API.

class pywikibot.Coordinate(lat, lon, alt=None, precision=None, globe=None, typ='', name='', dim=None, site=None, globe_item=None, primary=False, entity='[deprecated name of globe_item]')[source]

Bases: pywikibot._wbtypes.WbRepresentation

Class for handling and storing Coordinates.

__abstractmethods__ = frozenset({})
__init__(lat, lon, alt=None, precision=None, globe=None, typ='', name='', dim=None, site=None, globe_item=None, primary=False, entity='[deprecated name of globe_item]')[source]

Represent a geo coordinate.

Parameters
  • lat (float) – Latitude

  • lon (float) – Longitude

  • alt – Altitude? TODO FIXME

  • precision (float) – precision

  • globe (str) – Which globe the point is on

  • typ (str) – The type of coordinate point

  • name (str) – The name

  • dim (int) – Dimension (in meters)

  • site (pywikibot.site.DataSite) – The Wikibase site

  • globe_item (pywikibot.ItemPage or str) – The Wikibase item for the globe, or the entity URI of this Wikibase item. Takes precedence over ‘globe’ if present.

  • primary (bool) – True for a primary set of coordinates

__module__ = 'pywikibot'
property entity

Return the entity uri of the globe.

classmethod fromWikibase(data, site)[source]

Constructor to create an object from Wikibase’s JSON output.

Parameters
Return type

pywikibot.Coordinate

get_globe_item(repo=None, lazy_load=False)[source]

Return the ItemPage corresponding to the globe.

Note that the globe need not be in the same data repository as the Coordinate itself.

A successful lookup is stored as an internal value to avoid the need for repeated lookups.

Parameters
  • repo (pywikibot.site.DataSite) – the Wikibase site for the globe, if different from that provided with the Coordinate.

  • lazy_load (bool) – Do not raise NoPage if ItemPage does not exist.

Returns

pywikibot.ItemPage

property precision

Return the precision of the geo coordinate.

The precision is calculated if the Coordinate does not have a precision, and self._dim is set.

When no precision and no self._dim exists, None is returned.

The biggest error (in degrees) will be given by the longitudinal error; the same error in meters becomes larger (in degrees) further up north. We can thus ignore the latitudinal error.

The longitudinal can be derived as follows:

In small angle approximation (and thus in radians):

M{Δλ ≈ Δpos / r_φ}, where r_φ is the radius of earth at the given latitude. Δλ is the error in longitude.

M{r_φ = r cos φ}, where r is the radius of earth, φ the latitude

Therefore:

precision = math.degrees(
    self._dim/(radius*math.cos(math.radians(self.lat))))
precisionToDim() → Optional[int][source]

Convert precision from Wikibase to GeoData’s dim and return the latter.

dim is calculated if the Coordinate doesn’t have a dimension, and precision is set. When neither dim nor precision are set, ValueError is thrown.

Carrying on from the earlier derivation of precision, since precision = math.degrees(dim/(radius*math.cos(math.radians(self.lat)))) we get:

dim = math.radians(
    precision)*radius*math.cos(math.radians(self.lat))

But this is not valid, since it returns a float value for dim which is an integer. We must round it off to the nearest integer.

Therefore:

dim = int(round(math.radians(
    precision)*radius*math.cos(math.radians(self.lat))))
toWikibase()[source]

Export the data to a JSON object for the Wikibase API.

FIXME: Should this be in the DataSite object?

Returns

Wikibase JSON

Return type

dict

exception pywikibot.CoordinateGlobeUnknownException(arg: str)[source]

Bases: pywikibot.exceptions.WikiBaseError, NotImplementedError

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

__module__ = 'pywikibot.exceptions'
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, comment='[deprecated name of summary]', **kwargs)[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).

exception pywikibot.EditConflict(page, message: Optional[str] = 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.Error(arg: str)[source]

Bases: Exception

Pywikibot error.

__init__(arg: str)[source]

Initializer.

__module__ = 'pywikibot.exceptions'
__str__() → str[source]

Return a string representation.

exception pywikibot.FatalServerError(arg: str)[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: str = '')[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: str = '')[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.

file_is_shared() → bool[source]

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

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 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() → dict[source]

Return the file’s version history.

Returns

dictionary with: key: timestamp of the entry value: instance of FileInfo()

get_file_url(url_width=None, url_height=None, url_param=None) → str[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

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

property 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()

property 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: str, **kwargs) → bool[source]

Upload this file to the wiki.

keyword arguments are from site.upload() method.

Parameters

source – 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.

usingPages(total: Optional[int] = None, content: bool = False)[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)

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: str)[source]

Bases: pywikibot.exceptions.Error

Invalid page title.

__module__ = 'pywikibot.exceptions'
exception pywikibot.IsNotRedirectPage(page, message: Optional[str] = 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: Optional[str] = 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.

DATA_ATTRIBUTES = {'aliases': <class 'pywikibot.page.AliasesDict'>, 'claims': <class 'pywikibot.page.ClaimCollection'>, 'descriptions': <class 'pywikibot.page.LanguageDict'>, 'labels': <class 'pywikibot.page.LanguageDict'>, 'sitelinks': <class 'pywikibot.page.SiteLinkCollection'>}
__init__(site, title=None, ns=None)[source]

Initializer.

Parameters
  • site (pywikibot.site.DataSite) – data repository

  • title (str) – identifier 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) – 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

pywikibot.page.ItemPage

Raises
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

pywikibot.page.ItemPage

Raises
  • TypeError – Site is not a valid DataSite.

  • ValueError – Site does not match the base of the provided uri.

  • pywikibot.exceptions.NoPage – Uri points to non-existent item.

get(force=False, get_redirect=False, *args, **kwargs) → dict[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

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

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 (pywikibot.page.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 be a Page object, a BaseLink 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, a BaseLink 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 (pywikibot.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*'

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 (str or None); this contains any text following a ‘#’ character in the title

  • anchor: The anchor text (str 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'
property anchor

Return the anchor of the link.

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
Return type

pywikibot.page.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

pywikibot.page.Link

property 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() → tuple[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.

property section

Return the section of the link.

property site

Return the site of the link.

Return type

pywikibot.Site

property title

Return the title of the link.

exception pywikibot.LockedNoPage(page, message: Optional[str] = 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: Optional[str] = None)[source]

Bases: pywikibot.exceptions.PageSaveRelatedError

Page is locked.

__module__ = 'pywikibot.exceptions'
message = 'Page %s is locked.'
exception pywikibot.NoCreateError(page, message: Optional[str] = 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: Optional[str] = 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: Optional[str] = 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: str)[source]

Bases: pywikibot.exceptions.Error

Username is not in user-config.py.

__module__ = 'pywikibot.exceptions'
exception pywikibot.NoWikibaseEntity(entity)[source]

Bases: pywikibot.exceptions.WikiBaseError

This entity doesn’t exist.

__init__(entity)[source]

Initializer.

Parameters

entity (WikibaseEntity) – Wikibase entity

__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'
property args

Expose args.

message = 'Edit to page %(title)s failed:\n%(reason)s'
class pywikibot.Page(source, title: str = '', ns=0, defaultNamespace='[deprecated name of ns]')[source]

Bases: pywikibot.page.BasePage

Page: A MediaWiki page.

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

Instantiate a Page object.

__module__ = 'pywikibot.page'
get_best_claim(prop: str)[source]

Return the first best Claim for this page.

Return the first ‘preferred’ ranked Claim specified by wikibase property or the first ‘normal’ one otherwise.

Parameters

prop – property id, “P###”

Returns

Claim object given by wikibase property number for this page object.

Return type

pywikibot.Claim or None

Raises

UnknownExtension – site has no wikibase extension

property 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()[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 (pywikibot.page.Page, list)

exception pywikibot.PageCreatedConflict(page, message: Optional[str] = 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: Optional[str] = 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: Optional[str] = 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: Optional[str] = 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 = ''
exception pywikibot.PageSaveRelatedError(page, message: Optional[str] = None)[source]

Bases: pywikibot.exceptions.PageRelatedError

Saving the page has failed.

__module__ = 'pywikibot.exceptions'
property 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')
DATA_ATTRIBUTES = {'aliases': <class 'pywikibot.page.AliasesDict'>, 'claims': <class 'pywikibot.page.ClaimCollection'>, 'descriptions': <class 'pywikibot.page.LanguageDict'>, 'labels': <class 'pywikibot.page.LanguageDict'>}
__init__(source, title=None, datatype=None)[source]

Initializer.

Parameters
  • source (pywikibot.site.DataSite) – data repository property is on

  • title (str) – identifier 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: bool = False, *args, **kwargs) → dict[source]

Fetch the property entity, and cache it.

Parameters

force – override caching

Raises

NotImplementedError – a value in args or kwargs

Returns

actual data which entity holds

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

pywikibot.page.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: str)[source]

Bases: pywikibot.exceptions.Error

The section specified by # does not exist.

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

Bases: pywikibot.exceptions.ServerError

Server timed out with HTTP 504 code.

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

Bases: pywikibot.exceptions.Error

Got unexpected server response.

__module__ = 'pywikibot.exceptions'
pywikibot.Site(code=None, fam=None, user=None, sysop=NotImplemented, 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 pywikibot.family.Family) – family name or object (override config.family)

  • user (str) – bot user name to use on this site (override config.usernames)

  • 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
exception pywikibot.SiteDefinitionError(arg: str)[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'
property badges

Return a list of all badges associated with the link.

Return type

[pywikibot.ItemPage]

classmethod fromJSON(data: dict, site=None)[source]

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

Parameters
Return type

pywikibot.page.SiteLink

toJSON() → dict[source]

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

Returns

Wikibase JSON

exception pywikibot.SpamblacklistError(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.TimeStripper(*a, **kw)
class pywikibot.Timestamp[source]

Bases: datetime.datetime

Class for handling MediaWiki timestamps.

This inherits from datetime.datetime, so it can use all of the methods and operations of a datetime object. To ensure that the results of any operation are also a Timestamp object, be sure to use only Timestamp objects (and datetime.timedeltas) in any operation.

Use Timestamp.fromISOformat() and Timestamp.fromtimestampformat() to create Timestamp objects from MediaWiki string formats. As these constructors are typically used to create objects using data passed provided by site and page methods, some of which return a Timestamp when previously they returned a MediaWiki string representation, these methods also accept a Timestamp object, in which case they return a clone.

Use Site.server_time() for the current time; this is more reliable than using Timestamp.utcnow().

ISO8601Format = '%Y-%m-%dT%H:%M:%SZ'
__add__(other)[source]

Perform addition, returning a Timestamp instead of datetime.

__module__ = 'pywikibot'
__str__()[source]

Return a string format recognized by the API.

__sub__(other)[source]

Perform subtraction, returning a Timestamp instead of datetime.

clone()[source]

Clone this instance.

classmethod fromISOformat(ts, sep='T')[source]

Convert an ISO 8601 timestamp to a Timestamp object.

Parameters
  • ts (str or Timestamp) – ISO 8601 timestamp or a Timestamp object already

  • sep (str) – one-character separator, placed between the date and time

Returns

Timestamp object

Return type

Timestamp

classmethod fromtimestampformat(ts)[source]

Convert a MediaWiki internal timestamp to a Timestamp object.

isoformat(sep='T')[source]

Convert object to an ISO 8601 timestamp accepted by MediaWiki.

datetime.datetime.isoformat does not postfix the ISO formatted date with a ‘Z’ unless a timezone is included, which causes MediaWiki ~1.19 and earlier to fail.

mediawikiTSFormat = '%Y%m%d%H%M%S'
totimestampformat()[source]

Convert object to a MediaWiki internal timestamp.

exception pywikibot.TitleblacklistError(page, message: Optional[str] = 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.UnknownExtension(arg: str)[source]

Bases: pywikibot.exceptions.Error, NotImplementedError

Extension is not defined.

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

Bases: pywikibot.exceptions.SiteDefinitionError

Family is not registered.

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

Bases: pywikibot.exceptions.SiteDefinitionError

Site does not exist in Family.

__module__ = 'pywikibot.exceptions'
exception pywikibot.UnsupportedPage(page, message: Optional[str] = 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: Optional[str] = None, offset: int = 0)[source]

Bases: pywikibot.data.api.APIError

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

__init__(code, message, file_key: Optional[str] = None, offset: int = 0)[source]

Create a new UploadWarning instance.

Parameters
  • filekey – 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 – The starting offset for a chunked upload. Is False when there is no offset.

__module__ = 'pywikibot.data.api'
property message

Return warning message.

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, namespace='[deprecated name of namespaces]', limit='[deprecated name of total]', **kwargs)[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 (str). 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

editCount(force: bool = False) → int[source]

Return edit count for a registered user.

Always returns 0 for ‘anonymous’ users.

Parameters

force – if True, forces reloading the data from API

property 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: bool = False) → str[source]

Return the gender of the user.

Parameters

force – if True, forces reloading the data from API

Returns

return ‘male’, ‘female’, or ‘unknown’

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: bool = False) → dict[source]

Return a properties about the user.

Parameters

force – if True, forces reloading the data from API

groups(force: bool = False) → list[source]

Return a list of groups to which this user belongs.

The list of groups may be empty.

Parameters

force – if True, forces reloading the data from API

Returns

groups property

isAnonymous() → bool[source]

Determine if the user is editing as an IP address.

isBlocked(force: bool = False) → bool[source]

Determine whether the user is currently blocked.

Parameters

force – if True, forces reloading the data from API

isEmailable(force: bool = False) → bool[source]

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

Parameters

force – if True, forces reloading the data from API

isRegistered(force: bool = False) → bool[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 – if True, forces reloading the data from API

property 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

property 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

property 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() → str[source]

The username.

DEPRECATED: use username instead.

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

rights(force: bool = False) → list[source]

Return user rights.

Parameters

force – if True, forces reloading the data from API

Returns

return user rights

send_email(subject: str, text: str, ccme: bool = False) → bool[source]

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

Parameters
  • subject – the subject header of the mail

  • text – mail body

  • ccme – if True, sends a copy of this email to the bot

Raises
Returns

operation successful indicator

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 (str) and a bool for pageid > 0. Pages returned are not guaranteed to be unique.

Parameters

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

property username

The username.

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

class pywikibot.WbGeoShape(page, site=None)[source]

Bases: pywikibot._WbDataPage

A Wikibase geo-shape representation.

__abstractmethods__ = frozenset({})
__module__ = 'pywikibot'
class pywikibot.WbMonolingualText(text, language)[source]

Bases: pywikibot._wbtypes.WbRepresentation

A Wikibase monolingual text representation.

__abstractmethods__ = frozenset({})
__init__(text, language)[source]

Create a new WbMonolingualText object.

Parameters
  • text (str) – text string

  • language (str) – language code of the string

__module__ = 'pywikibot'
classmethod fromWikibase(wb)[source]

Create a WbMonolingualText from the JSON data given by Wikibase API.

Parameters

wb (dict) – Wikibase JSON

Return type

pywikibot.WbMonolingualText

toWikibase()[source]

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

Returns

Wikibase JSON

Return type

dict

class pywikibot.WbQuantity(amount, unit=None, error=None, site=None)[source]

Bases: pywikibot._wbtypes.WbRepresentation

A Wikibase quantity representation.

__abstractmethods__ = frozenset({})
__init__(amount, unit=None, error=None, site=None)[source]

Create a new WbQuantity object.

Parameters
  • amount (str or Decimal. Other types are accepted, and converted via str to Decimal.) – number representing this quantity

  • unit (pywikibot.ItemPage, str or None) – the Wikibase item for the unit or the entity URI of this Wikibase item.

  • error (same as amount, or tuple of two values, where the first value is the upper error and the second is the lower error value.) – the uncertainty of the amount (e.g. ±1)

  • site (pywikibot.site.DataSite) – The Wikibase site

__module__ = 'pywikibot'
classmethod fromWikibase(wb, site=None)[source]

Create a WbQuantity from the JSON data given by the Wikibase API.

Parameters
Return type

pywikibot.WbQuantity

get_unit_item(repo=None, lazy_load=False)[source]

Return the ItemPage corresponding to the unit.

Note that the unit need not be in the same data repository as the WbQuantity itself.

A successful lookup is stored as an internal value to avoid the need for repeated lookups.

Parameters
  • repo (pywikibot.site.DataSite) – the Wikibase site for the unit, if different from that provided with the WbQuantity.

  • lazy_load (bool) – Do not raise NoPage if ItemPage does not exist.

Returns

pywikibot.ItemPage

toWikibase()[source]

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

Returns

Wikibase JSON

Return type

dict

property unit

Return _unit’s entity uri or ‘1’ if _unit is None.

class pywikibot.WbTabularData(page, site=None)[source]

Bases: pywikibot._WbDataPage

A Wikibase tabular-data representation.

__abstractmethods__ = frozenset({})
__module__ = 'pywikibot'
class pywikibot.WbTime(year: Optional[int] = None, month: Optional[int] = None, day: Optional[int] = None, hour: Optional[int] = None, minute: Optional[int] = None, second: Optional[int] = None, precision: Optional[Union[int, str]] = None, before: int = 0, after: int = 0, timezone: int = 0, calendarmodel: Optional[str] = None, site=None)[source]

Bases: pywikibot._wbtypes.WbRepresentation

A Wikibase time representation.

FORMATSTR = '{0:+012d}-{1:02d}-{2:02d}T{3:02d}:{4:02d}:{5:02d}Z'
PRECISION = {'10000': 5, '100000': 4, '1000000': 3, '10000000': 2, '100000000': 1, '1000000000': 0, 'century': 7, 'day': 11, 'decade': 8, 'hour': 12, 'millenia': 6, 'minute': 13, 'month': 10, 'second': 14, 'year': 9}
__abstractmethods__ = frozenset({})
__init__(year: Optional[int] = None, month: Optional[int] = None, day: Optional[int] = None, hour: Optional[int] = None, minute: Optional[int] = None, second: Optional[int] = None, precision: Optional[Union[int, str]] = None, before: int = 0, after: int = 0, timezone: int = 0, calendarmodel: Optional[str] = None, site=None)[source]

Create a new WbTime object.

The precision can be set by the Wikibase int value (0-14) or by a human readable string, e.g., ‘hour’. If no precision is given, it is set according to the given time units.

Timezone information is given in three different ways depending on the time:

  • Times after the implementation of UTC (1972): as an offset from UTC in minutes;

  • Times before the implementation of UTC: the offset of the time zone from universal time;

  • Before the implementation of time zones: The longitude of the place of the event, in the range −180° to 180°, multiplied by 4 to convert to minutes.

Parameters
  • year – The year as a signed integer of between 1 and 16 digits.

  • month – Month

  • day – Day

  • hour – Hour

  • minute – Minute

  • second – Second

  • precision – The unit of the precision of the time.

  • before – Number of units after the given time it could be, if uncertain. The unit is given by the precision.

  • after – Number of units before the given time it could be, if uncertain. The unit is given by the precision.

  • timezone – Timezone information in minutes.

  • calendarmodel – URI identifying the calendar model

  • site (pywikibot.site.DataSite) – The Wikibase site

__module__ = 'pywikibot'
classmethod fromTimestamp(timestamp, precision=14, before=0, after=0, timezone=0, calendarmodel=None, site=None)[source]

Create a new WbTime object from a pywikibot.Timestamp.

Parameters
  • timestamp (pywikibot.Timestamp) – Timestamp

  • precision (int or str) – The unit of the precision of the time.

  • before (int) – Number of units after the given time it could be, if uncertain. The unit is given by the precision.

  • after (int) – Number of units before the given time it could be, if uncertain. The unit is given by the precision.

  • timezone (int) – Timezone information in minutes.

  • calendarmodel (str) – URI identifying the calendar model

  • site (pywikibot.site.DataSite) – The Wikibase site

Return type

pywikibot.WbTime

classmethod fromTimestr(datetimestr: str, precision: Union[int, str] = 14, before: int = 0, after: int = 0, timezone: int = 0, calendarmodel: Optional[str] = None, site=None)[source]

Create a new WbTime object from a UTC date/time string.

The timestamp differs from ISO 8601 in that:

  • The year is always signed and having between 1 and 16 digits;

  • The month, day and time are zero if they are unknown;

  • The Z is discarded since time zone is determined from the timezone param.

Parameters
  • datetimestr – Timestamp in a format resembling ISO 8601, e.g. +2013-01-01T00:00:00Z

  • precision – The unit of the precision of the time.

  • before – Number of units after the given time it could be, if uncertain. The unit is given by the precision.

  • after – Number of units before the given time it could be, if uncertain. The unit is given by the precision.

  • timezone – Timezone information in minutes.

  • calendarmodel – URI identifying the calendar model

  • site (pywikibot.site.DataSite) – The Wikibase site

Return type

pywikibot.WbTime

classmethod fromWikibase(wb, site=None)[source]

Create a WbTime from the JSON data given by the Wikibase API.

Parameters
Return type

pywikibot.WbTime

toTimestamp()[source]

Convert the data to a pywikibot.Timestamp.

Returns

Timestamp

Return type

pywikibot.Timestamp

Raises

ValueError – instance value can not be represented using Timestamp

toTimestr(force_iso=False)[source]

Convert the data to a UTC date/time string.

See fromTimestr() for differences between output with and without force_iso.

Parameters

force_iso (bool) – whether the output should be forced to ISO 8601

Returns

Timestamp in a format resembling ISO 8601

Return type

str

toWikibase()[source]

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

Returns

Wikibase JSON

Return type

dict

class pywikibot.WbUnknown(json)[source]

Bases: pywikibot._wbtypes.WbRepresentation

A Wikibase representation for unknown data type.

This will prevent the bot from breaking completely when a new type is introduced.

This data type is just a json container

__abstractmethods__ = frozenset({})
__init__(json)[source]

Create a new WbUnknown object.

Parameters

json – Wikibase JSON

Type

dict

__module__ = 'pywikibot'
classmethod fromWikibase(json)[source]

Create a WbUnknown from the JSON data given by the Wikibase API.

Parameters

json (dict) – Wikibase JSON

Return type

pywikibot.WbUnknown

toWikibase()[source]

Return the JSON object for the Wikibase API.

Returns

Wikibase JSON

Return type

dict

exception pywikibot.WikiBaseError(arg: str)[source]

Bases: pywikibot.exceptions.Error

Wikibase related error.

__module__ = 'pywikibot.exceptions'
class pywikibot.WikidataBot(use_from_page=NotImplemented, **kwargs)[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__(use_from_page=NotImplemented, **kwargs)[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(entity, data=None, ignore_save_related_errors=None, ignore_server_errors=None, **kwargs)[source]

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

Parameters
  • entity (WikibasePage) – 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.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.categoryFormat(*a, **kw)
pywikibot.compileLinkR(*a, **kw)
pywikibot.critical(text, decoder=None, newline=True, **kwargs)[source]

Output a critical record to the user via the userinterface.

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.

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

Output an error message to the user via the userinterface.

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.

pywikibot.extract_templates_and_params(*a, **kw)
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 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 str

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

Replace HTML entities with equivalent unicode.

Parameters
  • ignore – HTML entities to ignore

  • ignore – list of int

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.interwikiFormat(*a, **kw)
pywikibot.interwikiSort(*a, **kw)
pywikibot.isDisabled(*a, **kw)
pywikibot.log(text, decoder=None, newline=True, **kwargs)[source]

Output a record to the log file.

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.

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.showDiff(oldtext, newtext, context=0)[source]

Output a string showing the differences between oldtext and newtext.

The differences are highlighted (only on compatible systems) to show which changes were made.

pywikibot.showHelp(module_name=None)[source]

Show help for the Bot.

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

Output script results to the user via the userinterface.

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.unescape(*a, **kw)
pywikibot.unicode2html(string: str, encoding: str) → str[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
  • string – String to update

  • encoding – Encoding to use

pywikibot.url2unicode(title: str, encodings='utf-8', 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 – URL-encoded character data to convert

  • encodings (str, list or Site) – Encodings to attempt to use during conversion.

Raises

UnicodeError – Could not convert using any encoding.

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.

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.

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

Bases: pywikibot.bot_choice.Choice

Add an option to always apply the default.

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

Initializer.

__module__ = 'pywikibot.bot_choice'
property answer

Get the actual default answer instructing the replacement.

handle()[source]

Handle the custom shortcut.

Directly return answer whether it’s applying it always.

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
property summary_parameters

A dictionary of all parameters for i18n.

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}
property 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

Return type

pywikibot.Page

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

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, comment='[deprecated name of summary]', async='[deprecated name of asynchronous]', **kwargs)[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.

property site

Get the current site.

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_choice'
handle()[source]

Handle this choice. Must be implemented.

The current link will be handled by this choice.

property replacer

The replacer.

exception pywikibot.bot.ChoiceException(option: str, 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.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.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.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.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, comment='[deprecated name of summary]', **kwargs)[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.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.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.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) → str[source]

Return a formatted string showing the range.

property maximum

Return the upper bound of the range of allowed values.

property minimum

Return the lower bound of the range of allowed values.

parse(value) → int[source]

Return integer from value with prefix removed.

result(value)[source]

Return the value converted into int.

test(value) → bool[source]

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

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 (pywikibot.page.Link or pywikibot.page.Page) – The old link which is searched. The label and section are ignored.

  • new_link (pywikibot.page.Link or pywikibot.page.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'
property choices

Return the tuple of choices.

property current_groups

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

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

property current_range

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

property 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.

class pywikibot.bot.LinkChoice(option, shortcut, replacer, replace_section, replace_label)[source]

Bases: pywikibot.bot_choice.Choice

A choice returning a mix of the link new and current link.

__init__(option, shortcut, replacer, replace_section, replace_label)[source]

Initializer.

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

Handle by either applying the new section or label.

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.

property maximum

Return the maximum value.

result(value)[source]

Return a tuple with the prefix and selected value.

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

Bases: logging.Formatter

Format LogRecords for output to file.

This formatter ignores the ‘newline’ key of the LogRecord, because every record written to a file must end with a newline, regardless of whether the output to the user’s console does.

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

Format and return the specified exception with newline.

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) → bool[source]

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

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.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.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.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) → None[source]

Initializer.

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

Return a formatted string for that option.

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

Create a text with the options formatted into it.

Parameters
  • text – Text into which options are to be formatted

  • options (Iterable) – Option instances to be formatted

Returns

Text with the options formatted into it

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.

property stop

Return whether this option stops asking.

test(value)[source]

Return True whether this option applies.

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

pywikibot.exceptions.Error – No valid option is given with option parameter

setOptions(**kwargs)[source]

Set the instance options.

Parameters

kwargs – options

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.

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.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.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.

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.

property stop

Return whether this option stops asking.

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.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.

property site

Site that the bot is using.

skip_page(page)[source]

Skip page if it is not on the defined site.

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

Bases: pywikibot.bot_choice.Option

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

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

Initializer.

Parameters
  • option – option string

  • shortcut (str) – Shortcut of the option

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

Return a formatted string for that option.

result(value)[source]

Return the lowercased shortcut.

test(value) → bool[source]

Return True whether this option applies.

class pywikibot.bot.StaticChoice(option, shortcut, result)[source]

Bases: pywikibot.bot_choice.Choice

A static choice which just returns the given value.

__init__(option, shortcut, result)[source]

Create instance with replacer set to None.

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

Return the predefined value.

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.WikidataBot(use_from_page=NotImplemented, **kwargs)[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__(use_from_page=NotImplemented, **kwargs)[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(entity, data=None, ignore_save_related_errors=None, ignore_server_errors=None, **kwargs)[source]

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

Parameters
  • entity (WikibasePage) – 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.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.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.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 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 str

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.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_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

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.log(text, decoder=None, newline=True, **kwargs)[source]

Output a record to the log file.

pywikibot.bot.open_webbrowser(page)[source]

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

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.showHelp(module_name=None)[source]

Show help for the Bot.

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

Output script results to the user via the userinterface.

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.

Returns

True if an error message was printed, False otherwise

Return type

bool

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.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.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_choice module

Choices for input_choice.

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

Bases: pywikibot.bot_choice.Choice

Add an option to always apply the default.

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

Initializer.

__module__ = 'pywikibot.bot_choice'
property answer

Get the actual default answer instructing the replacement.

handle()[source]

Handle the custom shortcut.

Directly return answer whether it’s applying it always.

class pywikibot.bot_choice.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_choice'
handle()[source]

Handle this choice. Must be implemented.

The current link will be handled by this choice.

property replacer

The replacer.

exception pywikibot.bot_choice.ChoiceException(option: str, 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) → str[source]

Return a formatted string showing the range.

property maximum

Return the upper bound of the range of allowed values.

property minimum

Return the lower bound of the range of allowed values.

parse(value) → int[source]

Return integer from value with prefix removed.

result(value)[source]

Return the value converted into int.

test(value) → bool[source]

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

class pywikibot.bot_choice.LinkChoice(option, shortcut, replacer, replace_section, replace_label)[source]

Bases: pywikibot.bot_choice.Choice

A choice returning a mix of the link new and current link.

__init__(option, shortcut, replacer, replace_section, replace_label)[source]

Initializer.

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

Handle by either applying the new section or label.

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.

property 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) → bool[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) → None[source]

Initializer.

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

Return a formatted string for that option.

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

Create a text with the options formatted into it.

Parameters
  • text – Text into which options are to be formatted

  • options (Iterable) – Option instances to be formatted

Returns

Text with the options formatted into it

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.

property 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.

property 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.

property 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: str, shortcut, **kwargs)[source]

Bases: pywikibot.bot_choice.Option

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

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

Initializer.

Parameters
  • option – option string

  • shortcut (str) – Shortcut of the option

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

Return a formatted string for that option.

result(value)[source]

Return the lowercased shortcut.

test(value) → bool[source]

Return True whether this option applies.

class pywikibot.bot_choice.StaticChoice(option, shortcut, result)[source]

Bases: pywikibot.bot_choice.Choice

A static choice which just returns the given value.

__init__(option, shortcut, result)[source]

Create instance with replacer set to None.

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

Return the predefined value.

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, show_diff=False, namespace=None, pageTitle=None, ignore=False, redirect=NotImplemented, diff='[deprecated name of show_diff]', debug='[deprecated name of show_diff]')[source]

Bases: object

Cosmetic changes toolkit.

__init__(site, show_diff=False, namespace=None, pageTitle=None, ignore=False, redirect=NotImplemented, diff='[deprecated name of show_diff]', debug='[deprecated name of show_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, show_diff=False, ignore=False, diff='[deprecated name of show_diff]')[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 string.

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.

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.format_date(month, day, lang=None, year=2000)[source]

Format a date localized to given lang.

Parameters
  • month (int) – month in range of 1..12

  • day (int) – day of month in range of 1..31

  • lang (BaseSite or string) – a site object or language key. Defaults to current site.

  • year (int) – year for which the date is to be formatted. always 29 will be given For February except the year is given. Default is leap year 2000.

Returns

localized date like “January 11”

Return type

str

Raises
  • ValueError – Wrong day value; must be 1-28/29/30/31

  • IllegalMonthError – bad month number; must be 1-12

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: str, 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_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: str, text_b: str, 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: str, text_b: str, context=0, by_letter=False, replace_invisible=False, n='[deprecated name of context]')[source]

Initializer.

Parameters
  • text_a – base text

  • text_b – 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

property 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: str, jumpIndex=None, highlight=None) → Optional[str][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 – 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

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).

  • SpamblacklistError: 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.

  • NoWikibaseEntity: entity doesn’t exist

  • CoordinateGlobeUnknownException: globe is not implemented yet.

  • EntityTypeUnknownException: entity type is not available on the site.

TimeoutError: request failed with a timeout

  • MaxlagTimeoutError: request failed with a maxlag 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, FutureWarning

Command line argument that is no longer supported.

__module__ = 'pywikibot.exceptions'
exception pywikibot.exceptions.ArticleExistsConflict(page, message: Optional[str] = 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: str)[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: str)[source]

Bases: pywikibot.exceptions.Error

Server responded with BadTitle.

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

Bases: pywikibot.exceptions.Error

Captcha is asked and config.solve_captcha == False.

__module__ = 'pywikibot.exceptions'
exception pywikibot.exceptions.CascadeLockedPage(page, message: Optional[str] = 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: Optional[str] = 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: str)[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: Optional[str] = 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: str)[source]

Bases: pywikibot.exceptions.WikiBaseError

The requested entity type is not recognised on this site.

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

Bases: Exception

Pywikibot error.

__init__(arg: str)[source]

Initializer.

__module__ = 'pywikibot.exceptions'
__str__() → str[source]

Return a string representation.

exception pywikibot.exceptions.FamilyMaintenanceWarning[source]

Bases: UserWarning

Family class is missing definitions.

__module__ = 'pywikibot.exceptions'
exception pywikibot.exceptions.FatalServerError(arg: str)[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: str)[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: str)[source]

Bases: pywikibot.exceptions.Error

Invalid page title.

__module__ = 'pywikibot.exceptions'
exception pywikibot.exceptions.IsNotRedirectPage(page, message: Optional[str] = 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: Optional[str] = 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: Optional[str] = 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: Optional[str] = None)[source]

Bases: pywikibot.exceptions.PageSaveRelatedError

Page is locked.

__module__ = 'pywikibot.exceptions'
message = 'Page %s is locked.'
exception pywikibot.exceptions.MaxlagTimeoutError(arg: str)[source]

Bases: pywikibot.exceptions.TimeoutError

Request failed with a maxlag timeout error.

__module__ = 'pywikibot.exceptions'
exception pywikibot.exceptions.NoCreateError(page, message: Optional[str] = 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: Optional[str] = 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: Optional[str] = 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: str)[source]

Bases: pywikibot.exceptions.Error

Username is not in user-config.py.

__module__ = 'pywikibot.exceptions'
exception pywikibot.exceptions.NoWikibaseEntity(entity)[source]

Bases: pywikibot.exceptions.WikiBaseError

This entity doesn’t exist.

__init__(entity)[source]

Initializer.

Parameters

entity (WikibaseEntity) – Wikibase entity

__module__ = 'pywikibot.exceptions'
exception pywikibot.exceptions.NotEmailableError(page, message: Optional[str] = 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'
property args

Expose args.

message = 'Edit to page %(title)s failed:\n%(reason)s'
exception pywikibot.exceptions.PageCreatedConflict(page, message: Optional[str] = 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: Optional[str] = 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: Optional[str] = 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: Optional[str] = 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: Optional[str] = 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 = ''
exception pywikibot.exceptions.PageSaveRelatedError(page, message: Optional[str] = None)[source]

Bases: pywikibot.exceptions.PageRelatedError

Saving the page has failed.

__module__ = 'pywikibot.exceptions'
property args

Expose args.

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

Bases: pywikibot.exceptions.Error

The section specified by # does not exist.

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

Bases: pywikibot.exceptions.ServerError

Server returned with HTTP 414 code.

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

Bases: pywikibot.exceptions.ServerError

Server timed out with HTTP 504 code.

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

Bases: pywikibot.exceptions.Error

Got unexpected server response.

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

Bases: pywikibot.exceptions.Error

Site does not exist.

__module__ = 'pywikibot.exceptions'
exception pywikibot.exceptions.SpamblacklistError(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: str)[source]

Bases: pywikibot.exceptions.Error

Request failed with a timeout error.

__module__ = 'pywikibot.exceptions'
exception pywikibot.exceptions.TitleblacklistError(page, message: Optional[str] = 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: str)[source]

Bases: pywikibot.exceptions.Error, NotImplementedError

Extension is not defined.

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

Bases: pywikibot.exceptions.SiteDefinitionError

Family is not registered.

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

Bases: pywikibot.exceptions.SiteDefinitionError

Site does not exist in Family.

__module__ = 'pywikibot.exceptions'
exception pywikibot.exceptions.UnsupportedPage(page, message: Optional[str] = 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.UserRightsError(arg: str)[source]

Bases: pywikibot.exceptions.Error

Insufficient user rights to perform an action.

__module__ = 'pywikibot.exceptions'
exception pywikibot.exceptions.WikiBaseError(arg: str)[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', 'nqo', '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', 'nqo', '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'
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', 'nqo', '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.

get_archived_page_templates(code)[source]

Return tuple of archived page templates.

get_edit_restricted_templates(code)[source]

Return tuple of edit restricted templates.

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', 'wikispore': 'wikispore', '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', 'ary', '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.

linktrails = {'_default': '[a-z]*', 'ab': '[a-zабвгҕдежзӡикқҟлмнопҧрстҭуфхҳцҵчҷҽҿшыҩџьә]*', 'als': '[äöüßa-z]*', 'an': '[a-záéíóúñ]*', 'ar': '[a-zء-ي]*', 'ary': '[a-zء-ي]*', 'arz': '[a-zء-ي]*', 'ast': '[a-záéíóúñ]*', 'atj': '[a-zàâçéèêîôûäëïöüùÇÉÂÊÎÔÛÄËÏÖÜÀÈÙ]*', 'av': '[a-zабвгдеёжзийклмнопрстуфхцчшщъыьэюя]*', 'avk': '[a-zàâçéèêîôûäëïöüùÇÉÂÊÎÔÛÄËÏÖÜÀÈÙ]*', 'awa': '[a-zऀ-ॣ०-꣠-\ua8ff]*', 'ay': '[a-záéíóúñ]*', 'az': '[a-zçəğıöşü]*', 'azb': '[ابپتثجچحخدذرزژسشصضطظعغفقکگلمنوهیآأئؤة\u200c]*', 'ba': '[a-zабвгдеёжзийклмнопрстуфхцчшщъыьэюяәөүғҡңҙҫһ“»]*', 'bar': '[äöüßa-z]*', 'bat-smg': '[a-ząčęėįšųūž]*', 'be': '[абвгґджзеёжзійклмнопрстуўфхцчшыьэюяćčłńśšŭźža-z]*', 'be-tarask': '[абвгґджзеёжзійклмнопрстуўфхцчшыьэюяćčłńśšŭźža-z]*', 'bg': '[a-zабвгдежзийклмнопрстуфхцчшщъыьэюя]*', 'bm': '[a-zàâçéèêîôûäëïöüùÇÉÂÊÎÔÛÄËÏÖÜÀÈÙ]*', 'bn': '[ঀ-\u09ff]*', 'bpy': '[ঀ-\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]*', '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ÇĞçğİıÖöŞşÜüÂâÎîÛû]*', 'gan': '', 'gcr': '[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աբգդեզէըթժիլխծկհձղճմյնշոչպջռսվտրցւփքօֆև«»]*', 'hyw': '[a-zաբգդեզէըթժիլխծկհձղճմյնշոչպջռսվտրցւփքօֆև«»]*', 'ii': '', 'inh': '[a-zабвгдеёжзийклмнопрстуфхцчшщъыьэюя]*', 'is': '[áðéíóúýþæöa-z-–]*', 'it': '[a-zàéèíîìóòúù]*', 'ka': '[a-zაბგდევზთიკლმნოპჟრსტუფქღყშჩცძწჭხჯჰ“»]*', 'kab': '[a-zàâçéèêîôûäëïöüùÇÉÂÊÎÔÛÄËÏÖÜÀÈÙ]*', 'kbp': '[a-zàâçéèêîôûäëïöüùÇÉÂÊÎÔÛÄËÏÖÜÀÈÙ]*', 'kk': '[a-zäçéğıïñöşüýʺʹа-яёәғіқңөұүһٴابپتجحدرزسشعفقكلمنڭەوۇۋۆىيچھ“»]*', 'kl': '[a-zæøå]*', 'koi': '[a-zабвгдеёжзийклмнопрстуфхцчшщъыьэюя]*', 'krc': '[a-zабвгдеёжзийклмнопрстуфхцчшщъыьэюя]*', 'ksh': '[äöüėëijßəğåůæœça-z]*', '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àéèíîìóòúù]*', 'lld': '[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]*', 'os': '[a-zаæбвгдеёжзийклмнопрстуфхцчшщъыьэюя“»]*', 'pa': '[ਁਂਃਅਆਇਈਉਊਏਐਓਔਕਖਗਘਙਚਛਜਝਞਟਠਡਢਣਤਥਦਧਨਪਫਬਭਮਯਰਲਲ਼ਵਸ਼ਸਹ਼ਾਿੀੁੂੇੈੋੌ੍ਖ਼ਗ਼ਜ਼ੜਫ਼ੰੱੲੳa-z]*', 'pcd': '[a-zàâçéèêîôûäëïöüùÇÉÂÊÎÔÛÄËÏÖÜÀÈÙ]*', 'pdc': '[äöüßa-z]*', 'pfl': '[äöüßa-z]*', 'pl': '[a-zęóąśłżźćńĘÓĄŚŁŻŹĆŃ]*', 'pms': '[a-zàéèíîìóòúù]*', 'pnt': '[a-zαβγδεζηθικλμνξοπρστυφχψωςΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩάέήίόύώϊϋΐΰΆΈΉΊΌΎΏΪΫ]*', 'pt': '[áâãàéêẽçíòóôõq̃úüűũa-z]*', '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àéèíîìóòúù]*', 'se': '[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ęóąśłżźćńĘÓĄŚŁŻŹĆŃ]*', 'szy': '', 'ta': '[\u0b80-\u0bff]*', 'te': '[ఁ-౯]*', 'tet': '[áâãàéêẽçíòóôõq̃úüűũa-z]*', '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àâçéèêîôûäëïöüùÇÉÂÊÎÔÛÄËÏÖÜÀÈÙ]*', 'wuu': '', 'xal': '[a-zабвгдеёжзийклмнопрстуфхцчшщъыьэюя]*', 'xmf': '[a-zაბგდევზთიკლმნოპჟრსტუფქღყშჩცძწჭხჯჰ“»]*', 'yi': '[a-zא-ת]*', 'za': '', 'zea': '[a-zäöüïëéèà]*', 'zh': ''}
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

pywikibot.exceptions.UnknownFamily – family not known

maximum_GET_length(code)[source]

Return the maximum URL length for GET instead of POST.

name = None
nocapitalize = []
property 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.

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 = {'be-x-old': 'be-tarask', 'dk': 'da', 'jp': 'ja', 'minnan': 'zh-min-nan', 'mo': 'ro', 'nan': 'zh-min-nan', 'nb': 'no', 'nds_nl': 'nds-nl', 'zh-cn': 'zh', 'zh-tw': 'zh'}
content_families = {'commons', 'incubator', 'mediawiki', 'species', 'wikibooks', 'wikidata', 'wikinews', 'wikipedia', 'wikiquote', 'wikisource', 'wikiversity', 'wikivoyage', 'wiktionary'}
cross_projects = {'commons', 'incubator', 'mediawiki', 'meta', 'outreach', 'species', 'strategy', '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', '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
Raises
  • TypeError – incorrect use of parameters

  • ValueError – use of non-Flow-enabled Site

__module__ = 'pywikibot.flow'
get(force=False, get_redirect=False)[source]

Get the page’s content.

property 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'
property 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)[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

  • format (str) – Content format to return contents in

Returns

The contents of the post in the given content format

Return type

str

hide(reason)[source]

Hide this post.

Parameters

reason (str) – The reason for hiding this post.

property is_moderated

Whether this post is moderated.

property 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.

property 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.

property 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.

property is_locked

Whether this topic is locked.

property 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.

property 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+, that package is not packaged with pywikibot, and pywikibot 3+ does not have a hard dependency on any i18n messages. However, there are three user input questions in pagegenerators which will use i18n 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: str)[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 (pywikibot.interwiki_graph.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 (pywikibot.page.Page) – the page on the ‘origin’ wiki

__module__ = 'pywikibot.interwiki_graph'
property foundIn

Mapping of pages to others pages interwiki linked to it.

DEPRECATED. Use found_in.

property 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 (pywikibot.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.

__abstractmethods__ = frozenset({})
__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.LogEntry(apidata, site)[source]

Bases: collections.UserDict

Generic log entry.

LogEntry parameters may be retrieved by the corresponding method or the LogEntry key. The following statements are equivalent:

action = logentry.action() action = logentry[‘action’] action = logentry.data[‘action’]

__abstractmethods__ = frozenset({})
__eq__(other)[source]

Compare if self is equal to other.

__getattr__(item)[source]

Return several items from dict used as methods.

__hash__()[source]

Combine site and logid as the hash.

__init__(apidata, site)[source]

Initialize object from a logevent dict returned by MW API.

__missing__(key)[source]

Debug when the 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.

__module__ = 'pywikibot.logentries'
__repr__()[source]

Return a string representation of LogEntry object.

page()[source]

Page on which action was performed.

Returns

page on action was performed

Return type

pywikibot.Page

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.

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 'abc.DeleteEntry'>, 'import': <class 'abc.ImportEntry'>, 'move': <class 'pywikibot.logentries.MoveEntry'>, 'newusers': <class 'abc.NewusersEntry'>, 'patrol': <class 'pywikibot.logentries.PatrolEntry'>, 'protect': <class 'abc.ProtectEntry'>, 'rights': <class 'pywikibot.logentries.RightsEntry'>, 'thanks': <class 'abc.ThanksEntry'>, 'upload': <class 'pywikibot.logentries.UploadEntry'>}
class pywikibot.logentries.MoveEntry(apidata, site)[source]

Bases: pywikibot.logentries.LogEntry

Move log entry.

__abstractmethods__ = frozenset({})
__module__ = 'pywikibot.logentries'
suppressedredirect()[source]

Return True if no redirect was created during the move.

Return type

bool

property target_ns

Return namespace object of target page.

property target_page

Return target page object.

Return type

pywikibot.Page

property target_title

Return the target title.

class pywikibot.logentries.OtherLogEntry(apidata, site)[source]

Bases: pywikibot.logentries.LogEntry

A log entry class for unspecified log events.

__abstractmethods__ = frozenset({})
__module__ = 'pywikibot.logentries'
class pywikibot.logentries.PatrolEntry(apidata, site)[source]

Bases: pywikibot.logentries.LogEntry

Patrol log entry.

__abstractmethods__ = frozenset({})
__module__ = 'pywikibot.logentries'
property auto

Return auto patrolled.

property current_id

Return the current id.

Return type

int

property previous_id

Return the previous id.

Return type

int

class pywikibot.logentries.RightsEntry(apidata, site)[source]

Bases: pywikibot.logentries.LogEntry

Rights log entry.

__abstractmethods__ = frozenset({})
__module__ = 'pywikibot.logentries'
property newgroups

Return new rights groups.

property oldgroups

Return old rights groups.

class pywikibot.logentries.UploadEntry(apidata, site)[source]

Bases: pywikibot.logentries.LogEntry

Upload log entry.

__abstractmethods__ = frozenset({})
__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.

__abstractmethods__ = frozenset({})
__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: str, password: str)[source]

Bases: object

BotPassword object for storage in password file.

__init__(suffix: str, password: str)[source]

Initializer.

BotPassword function by using a separate password paired with a suffixed username of the form <username>@<suffix>.

Parameters
  • suffix – Suffix of the login name

  • password – bot password

Raises

_PasswordFileWarning – suffix improperly specified

__module__ = 'pywikibot.login'
login_name(username: str) → str[source]

Construct the login name from the username and suffix.

Parameters

user – username (without suffix)

class pywikibot.login.LoginManager(password=None, site=None, user=None, username='[deprecated name of user]', sysop=NotImplemented, verbose=NotImplemented)[source]

Bases: object

Site login manager.

__init__(password=None, site=None, user=None, username='[deprecated name of user]', sysop=NotImplemented, verbose=NotImplemented)[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

pywikibot.exceptions.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

pywikibot.exceptions.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) → bool[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

pywikibot.exceptions.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

class pywikibot.login.LoginStatus(value)[source]

Bases: enum.IntEnum

Enum for Login statuses.

>>> LoginStatus.NOT_ATTEMPTED
LoginStatus(-3)
>>> LoginStatus.IN_PROGRESS.value
-2
>>> LoginStatus.NOT_LOGGED_IN.name
NOT_LOGGED_IN
>>> int(LoginStatus.AS_USER)
0
>>> LoginStatus(-3).name
'NOT_ATTEMPTED'
>>> LoginStatus(0).name
'AS_USER'
AS_USER = 0
IN_PROGRESS = -2
NOT_ATTEMPTED = -3
NOT_LOGGED_IN = -1
__module__ = 'pywikibot.login'
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 (str) – consumer key

  • password (str) – consumer secret

Raises
__module__ = 'pywikibot.login'
property access_token

Return OAuth access key token and secret token.

See

https://www.mediawiki.org/wiki/API:Tokens

Return type

tuple of two str

property consumer_token

Return OAuth consumer key token and secret token.

See

https://www.mediawiki.org/wiki/API:Tokens

Return type

tuple of two str

property 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.pagegenerators module

This module offers a wide variety of page generators.

A page generator is an object that is iterable (see http://legacy.python.org/dev/peps/pep-0255/ ) and that yields page objects on which other scripts can then work.

Pagegenerators.py cannot be run as script. For testing purposes listpages.py can be used instead, to print page titles to standard output.

These parameters are supported to specify which pages titles to print:

GENERATOR OPTIONS

-cat

Work on all pages which are in a specific category. Argument can also be given as “-cat:categoryname” or as “-cat:categoryname|fromtitle” (using # instead of | is also allowed in this one and the following)

-catr

Like -cat, but also recursively includes pages in subcategories, sub-subcategories etc. of the given category. Argument can also be given as “-catr:categoryname” or as “-catr:categoryname|fromtitle”.

-subcats

Work on all subcategories of a specific category. Argument can also be given as “-subcats:categoryname” or as “-subcats:categoryname|fromtitle”.

-subcatsr

Like -subcats, but also includes sub-subcategories etc. of the given category. Argument can also be given as “-subcatsr:categoryname” or as “-subcatsr:categoryname|fromtitle”.

-uncat

Work on all pages which are not categorised.

-uncatcat

Work on all categories which are not categorised.

-uncatfiles

Work on all files which are not categorised.

-file

Read a list of pages to treat from the named text file. Page titles in the file may be either enclosed with [[brackets]], or be separated by new lines. Argument can also be given as “-file:filename”.

-filelinks

Work on all pages that use a certain image/media file. Argument can also be given as “-filelinks:filename”.

-search

Work on all pages that are found in a MediaWiki search across all namespaces.

-logevents

Work on articles that were on a specified Special:Log. The value may be a comma separated list of these values:

logevent,username,start,end

or for backward compatibility:

logevent,username,total

To use the default value, use an empty string. You have options for every type of logs given by the log event parameter which could be one of the following:

spamblacklist, titleblacklist, gblblock, renameuser, globalauth, gblrights, gblrename, abusefilter, massmessage, thanks, usermerge, block, protect, rights, delete, upload, move, import, patrol, merge, suppress, tag, managetags, contentmodel, review, stable, timedmediahandler, newusers

It uses the default number of pages 10.

Examples:

-logevents:move gives pages from move log (usually redirects) -logevents:delete,,20 gives 20 pages from deletion log -logevents:protect,Usr gives pages from protect log by user Usr -logevents:patrol,Usr,20 gives 20 patrolled pages by Usr -logevents:upload,,20121231,20100101 gives upload pages in the 2010s, 2011s, and 2012s -logevents:review,,20121231 gives review pages since the beginning till the 31 Dec 2012 -logevents:review,Usr,20121231 gives review pages by user Usr since the beginning till the 31 Dec 2012

In some cases it must be given as -logevents:”move,Usr,20”

-interwiki

Work on the given page and all equivalent pages in other languages. This can, for example, be used to fight multi-site spamming. Attention: this will cause the bot to modify pages on several wiki sites, this is not well tested, so check your edits!

-links

Work on all pages that are linked from a certain page. Argument can also be given as “-links:linkingpagetitle”.

-liverecentchanges

Work on pages from the live recent changes feed. If used as -liverecentchanges:x, work on x recent changes.

-imagesused

Work on all images that contained on a certain page. Can also be given as “-imagesused:linkingpagetitle”.

-newimages

Work on the most recent new images. If given as -newimages:x, will work on x newest images.

-newpages

Work on the most recent new pages. If given as -newpages:x, will work on x newest pages.

-recentchanges

Work on the pages with the most recent changes. If given as -recentchanges:x, will work on the x most recently changed pages. If given as -recentchanges:offset,duration it will work on pages changed from ‘offset’ minutes with ‘duration’ minutes of timespan. rctags are supported too. The rctag must be the very first parameter part.

Examples:

-recentchanges:20 gives the 20 most recently changed pages -recentchanges:120,70 will give pages with 120 offset minutes and 70 minutes of timespan -recentchanges:visualeditor,10 gives the 10 most recently changed pages marked with ‘visualeditor’ -recentchanges:”mobile edit,60,35” will retrieve pages marked with ‘mobile edit’ for the given offset and timespan

-unconnectedpages

Work on the most recent unconnected pages to the Wikibase repository. Given as -unconnectedpages:x, will work on the x most recent unconnected pages.

-ref

Work on all pages that link to a certain page. Argument can also be given as “-ref:referredpagetitle”.

-start

Specifies that the robot should go alphabetically through all pages on the home wiki, starting at the named page. Argument can also be given as “-start:pagetitle”.

You can also include a namespace. For example, “-start:Template:!” will make the bot work on all pages in the template namespace.

default value is start:!

-prefixindex

Work on pages commencing with a common prefix.

-transcludes

Work on all pages that use a certain template. Argument can also be given as “-transcludes:Title”.

-unusedfiles

Work on all description pages of images/media files that are not used anywhere. Argument can be given as “-unusedfiles:n” where n is the maximum number of articles to work on.

-lonelypages

Work on all articles that are not linked from any other article. Argument can be given as “-lonelypages:n” where n is the maximum number of articles to work on.

-unwatched

Work on all articles that are not watched by anyone. Argument can be given as “-unwatched:n” where n is the maximum number of articles to work on.

-property:name Work on all pages with a given property name from

Special:PagesWithProp.

-usercontribs

Work on all articles that were edited by a certain user. (Example : -usercontribs:DumZiBoT)

-weblink

Work on all articles that contain an external link to a given URL; may be given as “-weblink:url”

-withoutinterwiki

Work on all pages that don’t have interlanguage links. Argument can be given as “-withoutinterwiki:n” where n is the total to fetch.

-mysqlquery

Takes a MySQL query string like “SELECT page_namespace, page_title FROM page WHERE page_namespace = 0” and treats the resulting pages. See https://www.mediawiki.org/wiki/Manual:Pywikibot/MySQL for more details.

-sparql

Takes a SPARQL SELECT query string including ?item and works on the resulting pages.

-sparqlendpoint

Specify SPARQL endpoint URL (optional). (Example : -sparqlendpoint:http://myserver.com/sparql)

-searchitem

Takes a search string and works on Wikibase pages that contain it. Argument can be given as “-searchitem:text”, where text is the string to look for, or “-searchitem:lang:text”, where lang is the language to search items in.

-wantedpages

Work on pages that are linked, but do not exist; may be given as “-wantedpages:n” where n is the maximum number of articles to work on.

-wantedcategories

Work on categories that are used, but do not exist; may be given as “-wantedcategories:n” where n is the maximum number of categories to work on.

-wantedfiles

Work on files that are used, but do not exist; may be given as “-wantedfiles:n” where n is the maximum number of files to work on.

-wantedtemplates

Work on templates that are used, but do not exist; may be given as “-wantedtemplates:n” where n is the maximum number of templates to work on.

-random

Work on random pages returned by [[Special:Random]]. Can also be given as “-random:n” where n is the number of pages to be returned.

-randomredirect

Work on random redirect pages returned by [[Special:RandomRedirect]]. Can also be given as “-randomredirect:n” where n is the number of pages to be returned.

-google

Work on all pages that are found in a Google search. You need a Google Web API license key. Note that Google doesn’t give out license keys anymore. See google_key in config.py for instructions. Argument can also be given as “-google:searchstring”.

-page

Work on a single page. Argument can also be given as “-page:pagetitle”, and supplied multiple times for multiple pages.

-pageid

Work on a single pageid. Argument can also be given as “-pageid:pageid1,pageid2,.” or “-pageid:’pageid1|pageid2|..’” and supplied multiple times for multiple pages.

-linter

Work on pages that contain lint errors. Extension Linter must be available on the site. -linter select all categories. -linter:high, -linter:medium or -linter:low select all categories for that prio. Single categories can be selected with commas as in -linter:cat1,cat2,cat3

Adding ‘/int’ identifies Lint ID to start querying from: e.g. -linter:high/10000

-linter:show just shows available categories.

-querypage:name Work on pages provided by a QueryPage-based special page,

see https://www.mediawiki.org/wiki/API:Querypage. (tip: use -limit:n to fetch only n pages).

-querypage shows special pages available.

FILTER OPTIONS

-catfilter

Filter the page generator to only yield pages in the specified category. See -cat generator for argument format.

-grep

A regular expression that needs to match the article otherwise the page won’t be returned. Multiple -grep:regexpr can be provided and the page will be returned if content is matched by any of the regexpr provided. Case insensitive regular expressions will be used and dot matches any character, including a newline.

-intersect

Work on the intersection of all the provided generators.

-limit

When used with any other argument -limit:n specifies a set of pages, work on no more than n pages in total.

-namespaces

Filter the page generator to only yield pages in the

-namespace

specified namespaces. Separate multiple namespace

-ns

numbers or names with commas.

Examples:

-ns:0,2,4 -ns:Help,MediaWiki

You may use a preleading “not” to exclude the namespace.

Examples:

-ns:not:2,3 -ns:not:Help,File

If used with -newpages/-random/-randomredirect/linter generators, -namespace/ns must be provided before -newpages/-random/-randomredirect/linter. If used with -recentchanges generator, efficiency is improved if -namespace is provided before -recentchanges.

If used with -start generator, -namespace/ns shall contain only one value.

-onlyif

A claim the page needs to contain, otherwise the item won’t be returned. The format is property=value,qualifier=value. Multiple (or none) qualifiers can be passed, separated by commas.

Examples:

P1=Q2 (property P1 must contain value Q2), P3=Q4,P5=Q6,P6=Q7 (property P3 with value Q4 and qualifiers: P5 with value Q6 and P6 with value Q7). Value can be page ID, coordinate in format: latitude,longitude[,precision] (all values are in decimal degrees), year, or plain string. The argument can be provided multiple times and the item page will be returned only if all claims are present. Argument can be also given as “-onlyif:expression”.

-onlyifnot

A claim the page must not contain, otherwise the item won’t be returned. For usage and examples, see -onlyif above.

-ql

Filter pages based on page quality. This is only applicable if contentmodel equals ‘proofread-page’, otherwise has no effects. Valid values are in range 0-4. Multiple values can be comma-separated.

-subpage

-subpage:n filters pages to only those that have depth n i.e. a depth of 0 filters out all pages that are subpages, and a depth of 1 filters out all pages that are subpages of subpages.

-titleregex

A regular expression that needs to match the article title otherwise the page won’t be returned. Multiple -titleregex:regexpr can be provided and the page will be returned if title is matched by any of the regexpr provided. Case insensitive regular expressions will be used and dot matches any character.

-titleregexnot

Like -titleregex, but return the page only if the regular expression does not match.

pywikibot.pagegenerators.AncientPagesPageGenerator(total=100, site=None, repeat=NotImplemented, number='[deprecated name of total]')[source]

Ancient page generator.

Parameters
  • total (int) – Maximum number of pages to retrieve in total

  • site (pywikibot.site.BaseSite) – Site for generator results.

pywikibot.pagegenerators.CategorizedPageGenerator(category, recurse=False, start=None, total=None, content=False, namespaces=None, step=NotImplemented)[source]

Yield all pages in a specific category.

If recurse is True, pages in subcategories are included as well; if recurse is an int, only subcategories to that depth will be included (e.g., recurse=2 will get pages in subcats and sub-subcats, but will not go any further).

If start is a string value, only pages whose sortkey comes after start alphabetically are included.

If content is True (default is False), the current page text of each retrieved page will be downloaded.

pywikibot.pagegenerators.CategoryFilterPageGenerator(generator, category_list, site=None)[source]

Wrap a generator to filter pages by categories specified.

Parameters
  • generator – A generator object

  • category_list (list of category objects) – categories used to filter generated pages

pywikibot.pagegenerators.DayPageGenerator(start_month=1, end_month=12, site=None, year=2000, startMonth='[deprecated name of start_month]', endMonth='[deprecated name of end_month]')[source]

Day page generator.

Parameters
  • site (pywikibot.site.BaseSite) – Site for generator results.

  • year (int) – considering leap year.

pywikibot.pagegenerators.DeadendPagesPageGenerator(total=100, site=None, repeat=NotImplemented, number='[deprecated name of total]')[source]

DEPRECATED. Dead-end page generator.

Parameters
  • total (int) – Maximum number of pages to retrieve in total

  • site (pywikibot.site.BaseSite) – Site for generator results.

pywikibot.pagegenerators.DequePreloadingGenerator(generator, groupsize=50, step='[deprecated name of groupsize]')[source]

Preload generator of type DequeGenerator.

pywikibot.pagegenerators.EdittimeFilterPageGenerator(generator, last_edit_start=None, last_edit_end=None, first_edit_start=None, first_edit_end=None, show_filtered=False, begintime='[deprecated name of last_edit_start]', endtime='[deprecated name of last_edit_end]')[source]

Wrap a generator to filter pages outside last or first edit range.

Parameters
  • generator – A generator object

  • last_edit_start (datetime) – Only yield pages last edited after this time

  • last_edit_end (datetime) – Only yield pages last edited before this time

  • first_edit_start (datetime) – Only yield pages first edited after this time

  • first_edit_end (datetime) – Only yield pages first edited before this time

  • show_filtered (bool) – Output a message for each page not yielded

class pywikibot.pagegenerators.GeneratorFactory(site=None, positional_arg_name=None)[source]

Bases: object

Process command line arguments and return appropriate page generator.

This factory is responsible for processing command line arguments that are used by many scripts and that determine which pages to work on.

__init__(site=None, positional_arg_name=None)[source]

Initializer.

Parameters
  • site (pywikibot.site.BaseSite) – Site for generator results.

  • positional_arg_name (basestring) – generator to use for positional args, which do not begin with a hyphen

__module__ = 'pywikibot.pagegenerators'
getCategory(category: str, arg='[deprecated name of category]')[source]

Return Category and start as defined by category.

Parameters

category – category name with start parameter

getCategoryGen(category, recurse=False, content=False, gen_func=None, arg='[deprecated name of category]')[source]

Return generator based on Category defined by category and gen_func.

Parameters

category (str) – category name with start parameter

Return type

generator

getCombinedGenerator(gen=None, preload=False)[source]

Return the combination of all accumulated generators.

Only call this after all arguments have been parsed.

Parameters
  • gen (iterator) – Another generator to be combined with

  • preload (bool) – preload pages using PreloadingGenerator unless self.nopreload is True

handleArg(arg)[source]

Parse one argument at a time.

If it is recognized as an argument that specifies a generator, a generator is created and added to the accumulation list, and the function returns true. Otherwise, it returns false, so that caller can try parsing the argument. Call getCombinedGenerator() after all arguments have been parsed to get the final output generator.

Parameters

arg (basestring) – Pywikibot argument consisting of -name:value

Returns

True if the argument supplied was recognised by the factory

Return type

bool

property namespaces

List of Namespace parameters.

Converts int or string namespaces to Namespace objects and change the storage to immutable once it has been accessed.

The resolving and validation of namespace command line arguments is performed in this method, as it depends on the site property which is lazy loaded to avoid being cached before the global arguments are handled.

Returns

namespaces selected using arguments

Return type

list of Namespace

Raises
  • KeyError – a namespace identifier was not resolved

  • TypeError – a namespace identifier has an inappropriate type such as NoneType or bool

property site

Generator site.

The generator site should not be accessed until after the global arguments have been handled, otherwise the default Site may be changed by global arguments, which will cause this cached value to be stale.

Returns

Site given to initializer, otherwise the default Site at the time this property is first accessed.

Return type

pywikibot.site.BaseSite

class pywikibot.pagegenerators.GoogleSearchPageGenerator(query=None, site=None)[source]

Bases: object

Page generator using Google search results.

To use this generator, you need to install the package ‘google’:

https://pypi.org/project/google

This package has been available since 2010, hosted on github since 2012, and provided by pypi since 2013.

As there are concerns about Google’s Terms of Service, this generator prints a warning for each query.

__init__(query=None, site=None)[source]

Initializer.

Parameters

site (pywikibot.site.BaseSite) – Site for generator results.

__iter__()[source]

Iterate results.

__module__ = 'pywikibot.pagegenerators'
queryGoogle(query)[source]

Perform a query using python package ‘google’.

The terms of service as at June 2014 give two conditions that may apply to use of search:

  1. Don’t access [Google Services] using a method other than the interface and the instructions that [they] provide.

  2. Don’t remove, obscure, or alter any legal notices displayed in or along with [Google] Services.

Both of those issues should be managed by the package ‘google’, however Pywikibot will at least ensure the user sees the TOS in order to comply with the second condition.

pywikibot.pagegenerators.InterwikiPageGenerator(page)[source]

Iterate over all interwiki (non-language) links on a page.

class pywikibot.pagegenerators.ItemClaimFilter[source]

Bases: object

Item claim filter.

__module__ = 'pywikibot.pagegenerators'
classmethod filter(generator, prop, claim, qualifiers=None, negate=False)[source]

Yield all ItemPages which contain certain claim in a property.

Parameters
  • prop (str) – property id to check

  • claim – value of the property to check. Can be exact value (for instance, ItemPage instance) or a string (e.g. ‘Q37470’).

  • qualifiers (dict or None) – dict of qualifiers that must be present, or None if qualifiers are irrelevant

  • negate (bool) – true if pages that do not contain specified claim should be yielded, false otherwise

pywikibot.pagegenerators.ItemClaimFilterPageGenerator(generator, prop, claim, qualifiers=None, negate=False)

Yield all ItemPages which contain certain claim in a property.

Parameters
  • prop (str) – property id to check

  • claim – value of the property to check. Can be exact value (for instance, ItemPage instance) or a string (e.g. ‘Q37470’).

  • qualifiers (dict or None) – dict of qualifiers that must be present, or None if qualifiers are irrelevant

  • negate (bool) – true if pages that do not contain specified claim should be yielded, false otherwise

pywikibot.pagegenerators.LanguageLinksPageGenerator(page, total=None, step=NotImplemented)[source]

Iterate over all interwiki language links on a page.

pywikibot.pagegenerators.LiveRCPageGenerator(site=None, total=None)[source]

Yield pages from a socket.io RC stream.

Generates pages based on the EventStreams Server-Sent-Event (SSE) recent changes stream. The Page objects will have an extra property ._rcinfo containing the literal rc data. This can be used to e.g. filter only new pages. See pywikibot.comms.eventstreams.rc_listener for details on the .rcinfo format.

Parameters
  • site (pywikibot.BaseSite) – site to return recent changes for

  • total (int) – the maximum number of changes to return

pywikibot.pagegenerators.LogeventsPageGenerator(logtype=None, user=None, site=None, namespace=None, total=None, start=None, end=None, reverse=False, repeat=NotImplemented, number='[deprecated name of total]', mode='[deprecated name of logtype]')[source]

Generate Pages for specified modes of logevents.

Parameters
  • logtype (basestring) – Mode of logs to