Skip to content

TibiaWiki API

tibiawikisql.api

API to fetch information from TibiaWiki through MediaWiki's API.

Classes:

Name Description
WikiEntry

Represents a Wiki entry, such as an article or file.

Article

Represents a Wiki article.

Image

Represents an image info.

WikiClient

Contains methods to communicate with TibiaWiki's API.

WikiEntry pydantic-model

Bases: BaseModel

Represents a Wiki entry, such as an article or file.

Show JSON schema:
{
  "description": "Represents a Wiki entry, such as an article or file.",
  "properties": {
    "article_id": {
      "title": "Article Id",
      "type": "integer"
    },
    "title": {
      "title": "Title",
      "type": "string"
    },
    "timestamp": {
      "format": "date-time",
      "title": "Timestamp",
      "type": "string"
    }
  },
  "required": [
    "article_id",
    "title",
    "timestamp"
  ],
  "title": "WikiEntry",
  "type": "object"
}

Fields:

article_id pydantic-field
article_id: int

The entry's ID.

title pydantic-field
title: str

The entry's title.

timestamp pydantic-field
timestamp: datetime

The date of the entry's last edit.

url property
url: str

The URL to the article's display page.

__eq__
__eq__(other: object) -> bool

Check for equality.

Returns:

Type Description
bool

True if both objects are instances of this class and have the same article_id.

Source code in tibiawikisql/api.py
def __eq__(self, other: object) -> bool:
    """Check for equality.

    Returns:
        `True` if both objects are instances of this class and have the same `article_id`.

    """
    if isinstance(other, self.__class__):
        return self.article_id == other.article_id
    return False

Article pydantic-model

Bases: WikiEntry

Represents a Wiki article.

Show JSON schema:
{
  "description": "Represents a Wiki article.",
  "properties": {
    "article_id": {
      "title": "Article Id",
      "type": "integer"
    },
    "title": {
      "title": "Title",
      "type": "string"
    },
    "timestamp": {
      "format": "date-time",
      "title": "Timestamp",
      "type": "string"
    },
    "content": {
      "title": "Content",
      "type": "string"
    }
  },
  "required": [
    "article_id",
    "title",
    "timestamp",
    "content"
  ],
  "title": "Article",
  "type": "object"
}

Fields:

content pydantic-field
content: str

The article's source content.

infobox_attributes property
infobox_attributes: dict

Returns a mapping of the template attributes.

article_id pydantic-field
article_id: int

The entry's ID.

title pydantic-field
title: str

The entry's title.

timestamp pydantic-field
timestamp: datetime

The date of the entry's last edit.

url property
url: str

The URL to the article's display page.

__eq__
__eq__(other: object) -> bool

Check for equality.

Returns:

Type Description
bool

True if both objects are instances of this class and have the same article_id.

Source code in tibiawikisql/api.py
def __eq__(self, other: object) -> bool:
    """Check for equality.

    Returns:
        `True` if both objects are instances of this class and have the same `article_id`.

    """
    if isinstance(other, self.__class__):
        return self.article_id == other.article_id
    return False

Image pydantic-model

Bases: WikiEntry

Represents an image info.

Show JSON schema:
{
  "description": "Represents an image info.",
  "properties": {
    "article_id": {
      "title": "Article Id",
      "type": "integer"
    },
    "title": {
      "title": "Title",
      "type": "string"
    },
    "timestamp": {
      "format": "date-time",
      "title": "Timestamp",
      "type": "string"
    },
    "file_url": {
      "title": "File Url",
      "type": "string"
    }
  },
  "required": [
    "article_id",
    "title",
    "timestamp",
    "file_url"
  ],
  "title": "Image",
  "type": "object"
}

Fields:

file_url pydantic-field
file_url: str

The URL to the file.

extension property
extension: str | None

The image's file extension.

file_name property
file_name: str

The image's file name.

clean_name property
clean_name: str

The image's name without extension and prefix.

article_id pydantic-field
article_id: int

The entry's ID.

title pydantic-field
title: str

The entry's title.

timestamp pydantic-field
timestamp: datetime

The date of the entry's last edit.

url property
url: str

The URL to the article's display page.

__eq__
__eq__(other: object) -> bool

Check for equality.

Returns:

Type Description
bool

True if both objects are instances of this class and have the same article_id.

Source code in tibiawikisql/api.py
def __eq__(self, other: object) -> bool:
    """Check for equality.

    Returns:
        `True` if both objects are instances of this class and have the same `article_id`.

    """
    if isinstance(other, self.__class__):
        return self.article_id == other.article_id
    return False

WikiClient

WikiClient()

Contains methods to communicate with TibiaWiki's API.

Methods:

Name Description
get_category_members

Create a generator that obtains entries in a certain category.

get_category_members_titles

Create a generator that obtains a list of article titles in a category.

get_image_info

Get an image's info.

get_images_info

Get the information of a list of image names.

get_articles

Create a generator that obtains a list of articles given their titles.

get_article

Get an article's info.

Source code in tibiawikisql/api.py
def __init__(self) -> None:
    """Creates a new instance of the client."""
    self.session = requests.Session()
get_category_members
get_category_members(
    name: str, skip_index: bool = True
) -> Generator[WikiEntry]

Create a generator that obtains entries in a certain category.

Parameters:

Name Type Description Default
name str

The category's name. Category: prefix is not necessary.

required
skip_index bool

Whether to skip index articles or not.

True

Yields:

Type Description
Generator[WikiEntry]

Articles in this category.

Source code in tibiawikisql/api.py
def get_category_members(self, name: str, skip_index: bool = True) -> Generator[WikiEntry]:
    """Create a generator that obtains entries in a certain category.

    Args:
        name: The category's name. ``Category:`` prefix is not necessary.
        skip_index: Whether to skip index articles or not.

    Yields:
        Articles in this category.

    """
    cmcontinue = None
    params = {
        "action": "query",
        "list": "categorymembers",
        "cmtitle": f"Category:{name}",
        "cmlimit": 500,
        "cmtype": "page",
        "cmprop": "ids|title|sortkeyprefix|timestamp",
        "format": "json",
    }
    while True:
        params["cmcontinue"] = cmcontinue
        r = self.session.get(self.ENDPOINT, params=params)
        data = json.loads(r.text)
        for member in data["query"]["categorymembers"]:
            if member["sortkeyprefix"] == "*" and skip_index:
                continue
            yield WikiEntry(
                article_id=member["pageid"],
                title=member["title"],
                timestamp=member["timestamp"],
            )
        try:
            cmcontinue = data["continue"]["cmcontinue"]
        except KeyError:
            # If there's no "cmcontinue", means we reached the end of the list.
            break
get_category_members_titles
get_category_members_titles(
    name: str, skip_index: bool = True
) -> Generator[str]

Create a generator that obtains a list of article titles in a category.

Parameters:

Name Type Description Default
name str

The category's name. Category: prefix is not necessary.

required
skip_index bool

Whether to skip index articles or not.

True

Yields:

Type Description
Generator[str]

Titles of articles in this category.

Source code in tibiawikisql/api.py
def get_category_members_titles(self, name: str, skip_index: bool =True) -> Generator[str]:
    """Create a generator that obtains a list of article titles in a category.

    Args:
        name: The category's name. ``Category:`` prefix is not necessary.
        skip_index: Whether to skip index articles or not.

    Yields:
        Titles of articles in this category.

    """
    for member in self.get_category_members(name, skip_index):
        yield member.title
get_image_info
get_image_info(name: str) -> Image

Get an image's info.

It is not required to prefix the name with File:, but the extension is required.

Parameters:

Name Type Description Default
name str

The name of the image.

required

Returns:

Type Description
Image

The image's information.

Source code in tibiawikisql/api.py
def get_image_info(self, name: str) -> Image:
    """Get an image's info.

    It is not required to prefix the name with ``File:``, but the extension is required.

    Args:
        name: The name of the image.

    Returns:
        The image's information.

    """
    gen = self.get_images_info([name])
    return next(gen)
get_images_info
get_images_info(
    names: list[str],
) -> Generator[Image | None]

Get the information of a list of image names.

It is not required to prefix the name with File:, but the extension is required.

Warning

The order of the returned images might not match the order of the provided names due to an API limitation.

Parameters:

Name Type Description Default
names list[str]

A list of names of images to get the info of.

required

Yields:

Type Description
Generator[Image | None]

An image's information.

Source code in tibiawikisql/api.py
def get_images_info(self, names: list[str]) -> Generator[Image | None]:
    """Get the information of a list of image names.

    It is not required to prefix the name with ``File:``, but the extension is required.

    Warning:
        The order of the returned images might not match the order of the provided names due to an API limitation.

    Args:
        names: A list of names of images to get the info of.

    Yields:
        An image's information.

    """
    i = 0
    params = {
        "action": "query",
        "prop": "imageinfo",
        "iiprop": "url|timestamp",
        "format": "json",
    }
    while True:
        if i >= len(names):
            break
        params["titles"] = "|".join(f"File:{n}" for n in names[i:min(i + 50, len(names))])

        r = self.session.get(self.ENDPOINT, params=params)
        if r.status_code >= 400:
            continue
        data = json.loads(r.text)
        i += 50
        for image_data in data["query"]["pages"].values():
            if "missing" in image_data:
                yield None
                continue
            try:
                yield Image(
                    article_id=image_data["pageid"],
                    title=image_data["title"],
                    timestamp=image_data["imageinfo"][0]["timestamp"],
                    file_url=image_data["imageinfo"][0]["url"],
                )
            except KeyError:
                continue
get_articles
get_articles(names: list[str]) -> Generator[Article | None]

Create a generator that obtains a list of articles given their titles.

Warning

The order of the returned articles might not match the order of the provided names due to an API limitation.

Parameters:

Name Type Description Default
names list[str]

A list of names of articles to get the info of.

required

Yields:

Type Description
Generator[Article | None]

An article in the list of names.

Source code in tibiawikisql/api.py
def get_articles(self, names: list[str]) -> Generator[Article | None]:
    """Create a generator that obtains a list of articles given their titles.

    Warning:
        The order of the returned articles might not match the order of the provided names due to an API limitation.

    Args:
        names: A list of names of articles to get the info of.

    Yields:
        An article in the list of names.

    """
    i = 0
    params = {
        "action": "query",
        "prop": "revisions",
        "rvprop": "content|timestamp",
        "format": "json",
    }
    while True:
        if i >= len(names):
            break
        params["titles"] = "|".join(names[i:min(i + 50, len(names))])
        i += 50
        r = self.session.get(self.ENDPOINT, params=params)
        data = json.loads(r.text)
        for article in data["query"]["pages"].values():
            if "missing" in article:
                yield None
                continue
            yield Article(
                article_id=article["pageid"],
                timestamp=article["revisions"][0]["timestamp"],
                title=article["title"],
                content=article["revisions"][0]["*"],
            )
get_article
get_article(name: str) -> Article

Get an article's info.

Parameters:

Name Type Description Default
name str

The name of the Article.

required

Returns:

Type Description
Article

The article matching the title.

Source code in tibiawikisql/api.py
def get_article(self, name: str) -> Article:
    """Get an article's info.

    Args:
        name: The name of the Article.

    Returns:
        The article matching the title.

    """
    gen = self.get_articles([name])
    return next(gen)