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, startprefix: Optional[str] = None, endprefix: Optional[str] = None, endsort=NotImplemented, startFrom='[deprecated name of startprefix]', startsort=NotImplemented)[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”

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

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

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', isReference='[deprecated name of is_reference]', isQualifier='[deprecated name of is_qualifier]', **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', isReference='[deprecated name of is_reference]', isQualifier='[deprecated name of is_qualifier]', **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: float, lon: float, alt=None, precision: Optional[float] = None, globe: Optional[str] = None, typ: str = '', name: str = '', dim: Optional[int] = None, site: Optional[pywikibot.site._datasite.DataSite] = None, globe_item=None, primary: bool = False, entity='[deprecated name of globe_item]')[source]

Bases: pywikibot._wbtypes.WbRepresentation

Class for handling and storing Coordinates.

__abstractmethods__ = frozenset({})
__init__(lat: float, lon: float, alt=None, precision: Optional[float] = None, globe: Optional[str] = None, typ: str = '', name: str = '', dim: Optional[int] = None, site: Optional[pywikibot.site._datasite.DataSite] = None, globe_item=None, primary: bool = False, entity='[deprecated name of globe_item]')[source]

Represent a geo coordinate.

Parameters
  • lat – Latitude

  • lon – Longitude

  • alt – Altitude? TODO FIXME

  • precision – precision

  • globe – Which globe the point is on

  • typ – The type of coordinate point

  • name – The name

  • dim – Dimension (in meters)

  • site – 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 – True for a primary set of coordinates

__module__ = 'pywikibot'
property entity

Return the entity uri of the globe.

classmethod fromWikibase(data: dict, site: pywikibot.site._datasite.DataSite)[source]

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

Parameters
  • data – Wikibase JSON

  • site – The Wikibase site

Return type

Coordinate

get_globe_item(repo: Optional[pywikibot.site._datasite.DataSite] = None, lazy_load: bool = 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 – the Wikibase site for the globe, if different from that provided with the Coordinate.

  • lazy_load – 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()dict[source]

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

FIXME: Should this be in the DataSite object?

Returns

Wikibase JSON

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: str, 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 – 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

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()str[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 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 (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._collections.AliasesDict'>, 'claims': <class 'pywikibot.page._collections.ClaimCollection'>, 'descriptions': <class 'pywikibot.page._collections.LanguageDict'>, 'labels': <class 'pywikibot.page._collections.LanguageDict'>, 'sitelinks': <class 'pywikibot.page._collections.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: str, lazy_load: bool = False)[source]

Get the ItemPage from its entity uri.

Parameters
  • site (pywikibot.site.DataSite) – The Wikibase site for the item.

  • uri – Entity uri for the Wikibase item.

  • lazy_load – 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: Union[str, Exception])[source]

Bases: pywikibot.exceptions.PageSaveRelatedError

Saving the page has failed due to uncatchable error.

__init__(page, reason: Union[str, Exception])[source]

Initializer.

Parameters

reason – 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'
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._collections.AliasesDict'>, 'claims': <class 'pywikibot.page._collections.ClaimCollection'>, 'descriptions': <class 'pywikibot.page._collections.LanguageDict'>, 'labels': <class 'pywikibot.page._collections.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.SectionError(arg: str)[source]

Bases: pywikibot.exceptions.Error

The section specified by # does not exist.

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

Bases: pywikibot.exceptions.ServerError

Server returned with HTTP 414 code.

__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: Optional[str] = None, fam=None, user: Optional[str] = None, sysop=NotImplemented, *, interface=None, url: Optional[str] = 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 – language code (override config.mylang) code may also be a sitename like ‘wikipedia:test’

  • fam (str or pywikibot.family.Family) – family name or object (override config.family)

  • user – 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 – Instead of code and fam, does try to get a Site based on the URL. Still requires that the family supporting that URL exists.

Raises
  • ValueError – URL and pair of code and family given

  • ValueError – Invalid interface name

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'
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: str = '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 – 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
  • file_key – The file_key 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: int = 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 – 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

deleted_contributions(*, total: int = 500, **kwargs)Iterable[Tuple[pywikibot.page.Page, pywikibot.page._revision.Revision]][source]

Yield tuples describing this user’s deleted edits.

Param

total: Limit results 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

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

Remove the block for the user.

Parameters

reason – 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: Optional[pywikibot.site._datasite.DataSite] = None)[source]

Bases: pywikibot._WbDataPage

A Wikibase geo-shape representation.

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

Bases: pywikibot._wbtypes.WbRepresentation

A Wikibase monolingual text representation.

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

Create a new WbMonolingualText object.

Parameters
  • text – text string

  • language – language code of the string

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

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

Parameters

wb – Wikibase JSON

Return type

pywikibot.WbMonolingualText

toWikibase()dict[source]

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

Returns

Wikibase JSON

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

Bases: pywikibot._wbtypes.WbRepresentation

A Wikibase quantity representation.

__abstractmethods__ = frozenset({})
__init__(amount, unit=None, error=None, site: Optional[pywikibot.site._datasite.DataSite] = 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 – The Wikibase site

__module__ = 'pywikibot'
classmethod fromWikibase(wb: dict, site: Optional[pywikibot.site._datasite.DataSite] = None)[source]

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

Parameters
  • wb – Wikibase JSON

  • site – The Wikibase site

Return type

pywikibot.WbQuantity

get_unit_item(repo: Optional[pywikibot.site._datasite.DataSite] = None, lazy_load: bool = 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 – the Wikibase site for the unit, if different from that provided with the WbQuantity.

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

Returns

pywikibot.ItemPage

toWikibase()dict[source]

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

Returns

Wikibase JSON

property unit

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

class pywikibot.WbTabularData(page, site: Optional[pywikibot.site._datasite.DataSite] = 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: Optional[pywikibot.site._datasite.DataSite] = 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: Optional[pywikibot.site._datasite.DataSite] = 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 – The Wikibase site

__module__ = 'pywikibot'
classmethod fromTimestamp(timestamp, precision: Union[int, str] = 14, before: int = 0, after: int = 0, timezone: int = 0, calendarmodel: Optional[str] = None, site: Optional[pywikibot.site._datasite.DataSite] = None)[source]

Create a new WbTime object from a pywikibot.Timestamp.

Parameters
  • timestamp (pywikibot.Timestamp) – Timestamp

  • 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 – 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: Optional[pywikibot.site._datasite.DataSite] = 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 – The Wikibase site

Return type

pywikibot.WbTime

classmethod fromWikibase(wb: dict, site: Optional[pywikibot.site._datasite.DataSite] = None)[source]

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

Parameters
  • wb – Wikibase JSON

  • site – The Wikibase site

Return type

pywikibot.WbTime

toTimestamp()pywikibot.Timestamp[source]

Convert the data to a pywikibot.Timestamp.

Raises

ValueError – instance value cannot be represented using Timestamp

toTimestr(force_iso: bool = False)str[source]

Convert the data to a UTC date/time string.

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

Parameters

force_iso – whether the output should be forced to ISO 8601

Returns

Timestamp in a format resembling ISO 8601

toWikibase()dict[source]

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

Returns

Wikibase JSON

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

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

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

Parameters

json – Wikibase JSON

Return type

pywikibot.WbUnknown

toWikibase()dict[source]

Return the JSON object for the Wikibase API.

Returns

Wikibase JSON

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

__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()str[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.

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

Output a critical record to the user via the userinterface.

Parameters
  • text – the critical message which is to be displayed to the user.

  • decoder – If None, text should be a unicode string else it should be encoded in the given encoding.

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

Output a debug record to the log file.

Parameters
  • text – the message of the debug record to be logged to the log file.

  • decoder – If None, text should be a unicode string else it should be encoded in the given encoding.

  • newline – 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.

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

Parameters
  • text – the message containing the error which occurred.

  • decoder – If None, text should be a unicode string else it should be encoded in the given encoding.

  • newline – 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.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)
...

This function should only be called from an Exception handler.

Parameters
  • msg – If not None,contains the description of the exception occurred.

  • decoder – If None, text should be a unicode string else it should be encoded in the given encoding.

  • newline – 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.

  • tb – Set to True in order to output traceback also.

pywikibot.handle_args(args: Optional[Iterable[str]] = None, do_help: bool = True)List[str][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 – Command line arguments

  • do_help – Handle parameter ‘-help’ to show help and invoke sys.exit

Returns

list of arguments not recognised globally

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: str, password: bool = False, default: str = '', force: bool = False)str[source]

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

Parameters
  • question – 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 – if True, hides the user’s input (for password entry).

  • default – The default answer if none was entered. None to require an answer.

  • force – Automatically use the default

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

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

Parameters
  • question – 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 – 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 – Whether the shortcut or the index of the answer is returned.

  • automatic_quit – Adds the option ‘Quit’ (‘q’) and throw a QuitKeyboardInterrupt if selected.

  • force – 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), str (otherwise)

pywikibot.input_yn(question: str, default: Optional[Union[str, bool]] = None, automatic_quit: bool = True, force: bool = False)bool[source]

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

Parameters
  • question – The question asked without trailing spaces.

  • default – 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 – Adds the option ‘Quit’ (‘q’) and throw a QuitKeyboardInterrupt if selected.

  • force – 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’.

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

Output a record to the log file.

Parameters
  • text – the message which is to be logged to the log file.

  • decoder – If None, text should be a unicode string else it should be encoded in the given encoding.

  • newline – 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.output(text, decoder=None, newline=True, **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.

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.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.show_help(module_name=None, show_global=False)[source]

Show help for the Bot.

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

Output script results to the user via the userinterface.

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

Parameters
  • text – the message printed via stdout logger to the user.

  • decoder – If None, text should be a unicode string else it should be encoded in the given encoding.

  • newline – 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.translate(code, xdict: Union[dict, str], parameters: Optional[Union[dict, str, int]] = None, fallback=False)str[source]

Return the most appropriate localization from a localization dict.

Given a site 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 code that is most applicable to use on the wiki in language ‘code’ except fallback is False.

The code itself is always checked first, then these codes that have been defined to be alternatives, and finally English.

If fallback is False and the code is not found in the

For PLURAL support have a look at the twtranslate method.

Parameters
  • code (str or Site object) – The site code as string or Site object. If xdict is an extended dictionary the Site object should be used in favour of the code string. Otherwise localizations from a wrong family might be used.

  • xdict – dictionary with language codes as keys or extended dictionary with family names as keys containing code dictionaries or a single string. May contain PLURAL tags as described in twtranslate

  • parameters – 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.

Returns

the localized string

Raises
  • IndexError – If the language supports and requires more plurals than defined for the given PLURAL pattern.

  • KeyError – No fallback key found if fallback is not False

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: str, decoder: Optional[str] = None, newline: bool = True, **kwargs)[source]

Output a warning message to the user via the userinterface.

Parameters
  • text – the message the user wants to display.

  • decoder – If None, text should be a unicode string else it should be encoded in the given encoding.

  • newline – 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.backports module

This module contains backports to support older Python versions.

pywikibot.backports.removeprefix(string: str, prefix: str)str[source]

Remove prefix from a string or return a copy otherwise.

pywikibot.backports.removesuffix(string: str, suffix: str)str[source]

Remove prefix from a string or return a copy otherwise.

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

For bot options handling refer OptionHandler class above.

__init__(**kwargs)[source]

Only accept options defined in available_options.

Parameters

kwargs – bot options

__module__ = 'pywikibot.bot'
available_options = {'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.

__annotations__ = {}
__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 an 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: str, **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 available_options 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:

- available_options default setting
- script.ini options settings
- command line arguments
INI = 'scripts.ini'
__module__ = 'pywikibot.bot'
set_options(**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.

__annotations__ = {}
__module__ = 'pywikibot.bot'
ignore_server_errors = False
put_current(new_text: str, 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 – 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

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: Optional[str] = None, automatic_quit: bool = 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: Optional[str] = None, automatic_quit: bool = 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 – The default answer as the shortcut

  • automatic_quit – 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.

How to use options of OptionHandler and its BaseBot subclasses: First define an available_options class attribute for your own option handler to define all available options:

>>> default_options = {'foo': 'bar', 'bar': 42, 'baz': False}
>>> class MyHandler(OptionHandler): available_options = default_options

Or you may update the predefined setting in the class initializer. BaseBot predefines a ‘always’ options and sets it to False:

self.available_options.update(always=True, another_option=’Yes’)

Now you can instantiate an OptionHandler or BaseBot class passing options other than default values:

>>> bot = MyHandler(baz=True)

You can access bot options either as keyword item or attribute:

>>> bot.opt.foo
'bar'
>>> bot.opt['bar']
42
>>> bot.opt.baz  # default was overridden
True

You can set the options in the same way:

>>> bot.opt.bar = 4711
>>> bot.opt['baz'] = None
>>>

Or you can use the option as a dict:

>>> 'Option opt.{foo} is {bar}'.format_map(bot.opt)
'Option opt.bar is 4711'
__getattribute__(name)[source]

Update options for backward compatibility of options property.

__init__(**kwargs)[source]

Only accept options defined in available_options.

Parameters

kwargs – bot options

__module__ = 'pywikibot.bot'
available_options = {}
set_options(**options)[source]

Set the instance 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: Optional[str] = None, post: Optional[str] = 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: Optional[str] = None, post: Optional[str] = None, **kwargs)[source]

Initializer.

Parameters
  • pre – Additional comment printed before the list.

  • post – 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: Optional[str] = None, post: Optional[str] = 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: str, **kwargs)[source]

Bases: pywikibot.bot_choice.Option

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

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

Initializer.

Parameters
  • option – option string

  • shortcut – 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.opt attribute.

__annotations__ = {}
__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()str[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.

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

Output a critical record to the user via the userinterface.

Parameters
  • text – the critical message which is to be displayed to the user.

  • decoder – If None, text should be a unicode string else it should be encoded in the given encoding.

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

Output a debug record to the log file.

Parameters
  • text – the message of the debug record to be logged to the log file.

  • decoder – If None, text should be a unicode string else it should be encoded in the given encoding.

  • newline – 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.

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

Parameters
  • text – the message containing the error which occurred.

  • decoder – If None, text should be a unicode string else it should be encoded in the given encoding.

  • newline – 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.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)
...

This function should only be called from an Exception handler.

Parameters
  • msg – If not None,contains the description of the exception occurred.

  • decoder – If None, text should be a unicode string else it should be encoded in the given encoding.

  • newline – 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.

  • tb – Set to True in order to output traceback also.

pywikibot.bot.handle_args(args: Optional[Iterable[str]] = None, do_help: bool = True)List[str][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 – Command line arguments

  • do_help – Handle parameter ‘-help’ to show help and invoke sys.exit

Returns

list of arguments not recognised globally

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: str, password: bool = False, default: str = '', force: bool = False)str[source]

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

Parameters
  • question – 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 – if True, hides the user’s input (for password entry).

  • default – The default answer if none was entered. None to require an answer.

  • force – Automatically use the default

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

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

Parameters
  • question – 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 – 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 – Whether the shortcut or the index of the answer is returned.

  • automatic_quit – Adds the option ‘Quit’ (‘q’) and throw a QuitKeyboardInterrupt if selected.

  • force – 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), str (otherwise)

pywikibot.bot.input_list_choice(question: str, answers: Sequence[Any], default: Optional[Union[int, str]] = None, force: bool = False)str[source]

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

Parameters
  • question – The question asked without trailing spaces.

  • answers – The valid answers each containing a full length answer.

  • default – 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 – Automatically use the default

Returns

The selected answer.

pywikibot.bot.input_yn(question: str, default: Optional[Union[str, bool]] = None, automatic_quit: bool = True, force: bool = False)bool[source]

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

Parameters
  • question – The question asked without trailing spaces.

  • default – 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 – Adds the option ‘Quit’ (‘q’) and throw a QuitKeyboardInterrupt if selected.

  • force – 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’.

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

Output a record to the log file.

Parameters
  • text – the message which is to be logged to the log file.

  • decoder – If None, text should be a unicode string else it should be encoded in the given encoding.

  • newline – 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.open_webbrowser(page)[source]

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

pywikibot.bot.output(text, decoder=None, newline=True, **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.

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.show_help(module_name=None, show_global=False)[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.

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

Parameters
  • text – the message printed via stdout logger to the user.

  • decoder – If None, text should be a unicode string else it should be encoded in the given encoding.

  • newline – 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.suggest_help(missing_parameters: Optional[List[str]] = None, missing_generator: bool = False, unknown_parameters: Optional[List[str]] = None, exception=None, missing_action: bool = False, additional_text: str = '', missing_dependencies: Optional[List[str]] = None)bool[source]

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

Parameters
  • missing_parameters – A list of parameters which are missing.

  • missing_generator – Whether a generator is missing.

  • unknown_parameters – 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 – Additional text added to the end.

  • missing_dependencies (list of str) – A list of dependencies which cannot be imported.

Returns

True if an error message was printed, False otherwise

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

Output a warning message to the user via the userinterface.

Parameters
  • text – the message the user wants to display.

  • decoder – If None, text should be a unicode string else it should be encoded in the given encoding.

  • newline – 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.

__annotations__ = {}
__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 an option, shortcut and handler.

__annotations__ = {}
__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: str, **kwargs)[source]

Bases: pywikibot.bot_choice.StandardOption, Exception

A choice for input_choice which result in this exception.

__annotations__ = {}
__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.

__annotations__ = {}
__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.

__annotations__ = {}
__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.

__annotations__ = {}
__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.

__annotations__ = {}
__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.

__annotations__ = {}
__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.

__annotations__ = {}
__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.

__annotations__ = {}
__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.

__annotations__ = {}
__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.

__annotations__ = {}
__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.

__annotations__ = {}
__init__()[source]

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

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

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

An option to show a list and select an item.

__annotations__ = {}
__init__(sequence, prefix='', pre: Optional[str] = None, post: Optional[str] = None, **kwargs)[source]

Initializer.

Parameters
  • pre – Additional comment printed before the list.

  • post – 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: Optional[str] = None, post: Optional[str] = None, **kwargs)[source]

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

An option to show a list and select multiple items.

__annotations__ = {}
__module__ = 'pywikibot.bot_choice'
class pywikibot.bot_choice.StandardOption(option: str, shortcut: str, **kwargs)[source]

Bases: pywikibot.bot_choice.Option

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

__annotations__ = {}
__init__(option: str, shortcut: str, **kwargs)[source]

Initializer.

Parameters
  • option – option string

  • shortcut – 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.

__annotations__ = {}
__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 cannot 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. If pywikibot is installed as a site-package the behaviour is like PYWIKIBOT_NO_USER_CONFIG=2 is set.

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: Optional[str] = None)str[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 or install pywikibot as a site-package.

Parameters

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

pywikibot.config2.makepath(path: str, create: bool = 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 – path in the filesystem

  • create – 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(page, diff='[deprecated name of show_diff]', redirect=NotImplemented, site='[deprecated name of page]', *, show_diff: bool = False, namespace: Optional[int] = None, pageTitle: Optional[str] = None, ignore: int = False)[source]

Bases: object

Cosmetic changes toolkit.

__init__(page, diff='[deprecated name of show_diff]', redirect=NotImplemented, site='[deprecated name of page]', *, show_diff: bool = False, namespace: Optional[int] = None, pageTitle: Optional[str] = None, ignore: int = False)[source]

Initializer.

Parameters
  • page (pywikibot.Page) – the Page object containing the text to be modified

  • show_diff – show difference after replacements (default: False)

  • namespace – DEPRECATED namespace parameter

  • pageTitle – DEPRECATED page title parameter

  • ignore – ignores if an error occurred and either skips the page or only that method. It can be set one of the CANCEL constants

__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 – string to perform the clean-up on

Returns

text with tidied wikilinks

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.

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.

class pywikibot.date.MonthFormat(index, format_key)[source]

Bases: collections.abc.MutableMapping

A Mapping which creates months formats.

__abstractmethods__ = frozenset({})
__delitem__(key)[source]
__getitem__(key)[source]
__init__(index, format_key)[source]

Initializer of MonthFormat mapping.

Parameters
  • index (int) – month number

  • format_key (str) – formats key like Day_January or Year_December

__iter__()[source]
__len__()[source]
__module__ = 'pywikibot.date'
__setitem__(key, value)[source]
day_formats = {'af': ('%d {}', True), 'ang': ('%d {}', True), 'bg': ('%d {}', False), 'bn': ('{} %%B', None), 'ceb': ('{} %d', True), 'csb': ('%d {}a', False), 'cv': ('{}, %d', True), 'cy': ('%d {}', True), 'de': ('%d. {}', True), 'en': ('{} %d', True), 'eo': ('%d-a de {}', False), 'es': ('%d de {}', False), 'eu': ('{}aren %d', True), 'fi': ('%d. {}ta', False), 'fur': ('%d di {}', True), 'fy': ('%d {}', False), 'gl': ('%d de {}', False), 'gsw': ('%d. {}', True), 'he': ('%d ב{}', None), 'hu': ('{} %d.', True), 'ia': ('%d de {}', False), 'id': ('%d {}', True), 'ie': ('%d {}', False), 'io': ('%d di {}', False), 'it': ('%d {}', False), 'jv': ('%d {}', True), 'ka': ('%d {}', None), 'lb': ('%d. {}', True), 'mhr': ('%d {}', False), 'ml': ('{} %d', None), 'ms': ('%d {}', True), 'nap': ("%d 'e {}", False), 'nds': ('%d. {}', True), 'pt': ('%d de {}', True), 'ro': ('%d {}', False), 'scn': ('%d di {}', False), 'sco': ('%d {}', True), 'su': ('%d {}', True), 'sv': ('%d {}', False), 'ta': ('{} %d', None), 'te': ('{} %d', None), 'th': ('%d {}', None), 'tl': ('{} %d', None), 'tr': ('%d {}', True), 'tt': ('%d. {}', True), 'vec': ('%d de {}', False), 'vo': ('{} %d', False)}
year_formats = {'ar': ('{} %d', None), 'cs': ('{} %d', None), 'eo': ('{} de %d', None), 'es': ('{} de %d', True), 'it': ('Attualità/Anno %d - {}', True), 'ka': ('{}, %d', None), 'sk': ('{} %d', None), 'th': ('{} พ.ศ. %%T', None), 'tl': ('{} %d', None)}
class pywikibot.date.MonthNames[source]

Bases: collections.abc.Mapping

A Mapping with reads month names from mediawiki messages.

__abstractmethods__ = frozenset({})
__getitem__(lang)[source]
__iter__()[source]
__len__()[source]

Length of preloaded languages with all month names.

__module__ = 'pywikibot.date'
months = {'br': <function MonthNames.<lambda>>, 'en': <function MonthNames.<lambda>>, 'ja': <function MonthNames.<lambda>>, 'ko': <function MonthNames.<lambda>>, 'wa': <function MonthNames.<lambda>>, 'zh': <function MonthNames.<lambda>>}
pywikibot.date.addFmt1(lang: str, 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 – language code

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: int, pattern, encf, decf, filter=None)[source]
pywikibot.date.dh(value: str, pattern, encf, decf, filter=None)

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 – 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: int, tuplst)[source]
pywikibot.date.multi(value: str, tuplst)

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: str)dict[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 :return: deleted and added list of contexts

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: Optional[int] = None, highlight: Optional[str] = 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 – position at which to put the caret

  • highlight – 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.

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

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

Bases: pywikibot.exceptions.Error

Captcha is asked and config.solve_captcha == False.

__annotations__ = {}
__module__ = 'pywikibot.exceptions'
exception pywikibot.exceptions.CascadeLockedPage(page, message: Optional[str] = None)[source]

Bases: pywikibot.exceptions.LockedPage

Page is locked due to cascading protection.

__annotations__ = {}
__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)

__annotations__ = {}
__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.

__annotations__ = {}
__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.

__annotations__ = {}
__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.

__annotations__ = {}
__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.

__annotations__ = {}
__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: str)[source]

Bases: pywikibot.exceptions.PageLoadRelatedError

Page receives a title inconsistent with query.

__init__(page, actual: str)[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.

__annotations__ = {}
__init__(page, target_page)[source]

Initializer.

Parameters

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

__annotations__ = {}
__module__ = 'pywikibot.exceptions'
exception pywikibot.exceptions.IsNotRedirectPage(page, message: Optional[str] = None)[source]

Bases: pywikibot.exceptions.PageRelatedError

Page is not a redirect page.

__annotations__ = {}
__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.

__annotations__ = {}
__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.

__annotations__ = {}
__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.

__annotations__ = {}
__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.

__annotations__ = {}
__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.

__annotations__ = {}
__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.

__annotations__ = {}
__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.

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

Bases: pywikibot.exceptions.WikiBaseError

This entity doesn’t exist.

__annotations__ = {}
__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: Union[str, Exception])[source]

Bases: pywikibot.exceptions.PageSaveRelatedError

Saving the page has failed due to uncatchable error.

__annotations__ = {}
__init__(page, reason: Union[str, Exception])[source]

Initializer.

Parameters

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

__annotations__ = {}
__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.

__annotations__ = {}
__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.

__annotations__ = {}
__init__(page, message: Optional[str] = None)[source]

Initializer.

Parameters

page (Page object) – Page that caused the exception

__module__ = 'pywikibot.exceptions'
message = ''
exception pywikibot.exceptions.PageSaveRelatedError(page, message: Optional[str] = None)[source]

Bases: pywikibot.exceptions.PageRelatedError

Saving the page has failed.

__annotations__ = {}
__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.

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

Bases: pywikibot.exceptions.ServerError

Server returned with HTTP 414 code.

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

Bases: pywikibot.exceptions.ServerError

Server timed out with HTTP 504 code.

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

Bases: pywikibot.exceptions.Error

Got unexpected server response.

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

Bases: pywikibot.exceptions.Error

Site does not exist.

__annotations__ = {}
__module__ = 'pywikibot.exceptions'
exception pywikibot.exceptions.SpamblacklistError(page, url)[source]

Bases: pywikibot.exceptions.PageSaveRelatedError

Page save failed because MediaWiki detected a blacklisted spam URL.

__annotations__ = {}
__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.

__annotations__ = {}
__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.

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

Bases: pywikibot.exceptions.SiteDefinitionError

Family is not registered.

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

Bases: pywikibot.exceptions.SiteDefinitionError

Site does not exist in Family.

__annotations__ = {}
__module__ = 'pywikibot.exceptions'
exception pywikibot.exceptions.UnsupportedPage(page, message: Optional[str] = None)[source]

Bases: pywikibot.exceptions.PageRelatedError

Unsupported page due to namespace restriction.

__annotations__ = {}
__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.

__annotations__ = {}
__module__ = 'pywikibot.exceptions'

pywikibot.family module

Objects representing MediaWiki families.

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

Family that automatically loads the site configuration.

Parameters
  • name – Name for the family

  • url – 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.

__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', 'alt', 'am', 'smn', 'ang', 'ab', 'ar', 'an', 'arc', 'roa-rup', 'frp', 'as', 'ast', 'atj', 'awa', 'gn', 'av', 'ay', 'az', 'ban', 'bm', 'bn', 'bjn', 'zh-min-nan', 'nan', 'map-bms', 'ba', 'be', 'be-tarask', 'mnw', 'bh', 'bcl', 'bi', 'bg', 'bar', 'bo', 'bs', 'br', 'bxr', 'ca', 'cv', 'ceb', 'cs', 'ch', 'cbk-zam', 'ny', 'sn', 'tum', 'cho', 'co', 'cy', 'da', 'dk', 'ary', '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', 'avk', 'ht', 'gcr', 'ku', 'kj', 'ky', 'mrj', 'lld', 'lad', 'lbe', 'lo', 'ltg', 'la', 'lv', 'lb', 'lez', 'lfn', 'lt', 'lij', 'li', 'ln', 'olo', 'jbo', 'lg', 'lmo', 'lrc', 'mad', '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', 'nia', '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', 'szy', 'se', 'sm', 'sa', 'sg', 'sat', 'skr', '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', 'alt', 'am', 'smn', 'ang', 'ab', 'ar', 'an', 'arc', 'roa-rup', 'frp', 'as', 'ast', 'atj', 'awa', 'gn', 'av', 'ay', 'az', 'bjn', 'id', 'ms', 'ban', 'bm', 'bn', 'zh-min-nan', 'nan', 'map-bms', 'jv', 'su', 'ba', 'min', 'be', 'be-tarask', 'mnw', 'mad', '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', 'ary', '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', 'avk', 'gor', 'ht', 'gcr', 'ku', 'shn', 'kj', 'lld', 'lad', 'lbe', 'lez', 'lfn', 'lo', 'la', 'ltg', 'lv', 'to', 'lb', 'lt', 'lij', 'li', 'ln', 'nia', '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', 'szy', 'se', 'sa', 'sg', 'sat', 'skr', '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: str, uri: str, protocol=None)str[source]

Prefix uri with port and hostname.

Parameters
  • code – The site code

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

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

set 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

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

from_url(url: str)Optional[str][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 – 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.

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', 'alt', 'am', 'an', 'ang', 'ar', 'arc', 'ary', 'arz', 'as', 'ast', 'atj', 'av', 'avk', 'awa', 'az', 'azb', 'ba', 'ban', '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', 'gcr', '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', 'lld', 'lmo', 'ln', 'lo', 'lrc', 'lt', 'ltg', 'lv', 'mad', 'mai', 'map-bms', 'mdf', 'mg', 'mh', 'mhr', 'mi', 'my', 'min', 'myv', 'mk', 'ml', 'mn', 'mnw', 'mo', 'mr', 'mrj', 'ms', 'mt', 'mus', 'mwl', 'mzn', 'na', 'nah', 'nan', 'nap', 'nds', 'nds-nl', 'ne', 'new', 'ng', 'ny', 'nia', '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', 'skr', 'sl', 'sm', 'smn', 'sn', 'so', 'sq', 'sr', 'srn', 'ss', 'st', 'stq', 'su', 'sv', 'sw', 'szy', '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.

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

langs = {}
language_groups = {'arab': ['ar', 'ary', 'arz', 'azb', 'ckb', 'fa', 'glk', 'ks', 'lrc', 'mzn', 'ps', 'sd', 'ur', 'ha', 'kk', 'ku', 'pnb', 'ug'], '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',