mwbot-ts - v1.2.7
    Preparing search index...

    Class Mwbot

    The core class of the mwbot-ts framework. This class provides a robust and extensible interface for interacting with the MediaWiki API.

    A Mwbot instance must be created using the static init method (not the protected constructor) to ensure that all lazy-loaded classes, properties, and methods are properly initialized.

    Example:

    import { Mwbot, MwbotInitOptions } from 'mwbot-ts';

    const initOptions: MwbotInitOptions = {
    apiUrl: 'https://en.wikipedia.org/w/api.php',
    userAgent: 'MyCoolBot/1.0.0 (https://github.com/Foo/MyCoolBot)',
    credentials: {
    oAuth2AccessToken: '...'
    }
    };

    Mwbot.init(initOptions).then((mwbot) => {
    // Interact with MediaWiki using the mwbot instance...
    });

    See also:

    Index

    Constructors

    • Creates a Mwbot instance.

      This constructor is protected. Use init instead to create a new instance.

      Parameters

      • mwbotInitOptions: MwbotInitOptions

        Configuration object containing initialization settings and user credentials.

      • requestOptions: MwbotRequestConfig

        Custom request options applied to all HTTP requests issued by the new instance.

      Returns Mwbot

      If:

      • No valid API endpoint is provided. (nourl)
      • The user credentials are malformed. (invalidcreds)

    Properties

    _FileWikilink: FileWikilinkStatic
    _ParserFunction: ParserFunctionStatic
    _RawWikilink: RawWikilinkStatic
    _Template: TemplateStatic
    _Title: TitleStatic
    _Wikilink: WikilinkStatic
    _Wikitext: WikitextStatic
    abortions: AbortController[]

    An array of AbortControllers used in abort.

    agents: { http: Agent; https: Agent }

    Custom agents that manage keep-alive connections for HTTP requests. These are injected into the request options when using OAuth.

    See [[mw:Manual:Creating a bot#Bot best practices]].

    axios: AxiosInstance

    Axios instance for this intance.

    configData: ConfigData = ...

    Stores configuration values for the site and user.

    configKeys: Set<keyof ConfigData> = ...

    The wg-keys of ConfigData, used in config to verify their existence.

    credentials: MwbotCredentials

    User credentials.

    jar: CookieJar

    A cookie jar that stores session and login cookies for this instance.

    lastRequestTime: null | number

    The timestamp (in milliseconds since the UNIX epoch) of the last successful request. This is updated only for API actions specified in MwbotOptions.intervalActions.

    Cashed MediaWiki tokens.

    userMwbotOptions: MwbotOptions

    The user options for this intance.

    userRequestOptions: MwbotRequestConfig

    The user-defined configurations for HTTP requests.

    Accessors

    • get apilimit(): 50 | 500

      Returns the user's API limit for multi-value requests.

      Returns 50 | 500

      500 for users with the apihighlimits permission; otherwise, 50.

    • get config(): MwConfig<ConfigData>

      Provides access to site and user configuration data.

      mwbot.config functions similarly to mw.config from MediaWiki core, except:

      • mwbot.config does not return a Map-like object like mw.config does. Instead, it returns an object with the methods get, set, and exists.
      • mwbot.config.set prevents built-in wg-variables from being overwritten. (See ConfigData for a list of such variables.)
      get(selection?: string | string[], fallback = null): Mixed;
      
      • If selection is a string, returns the corresponding value.
      • If selection is an array, returns an object mapping each key to its value.
      • If no selection is provided, returns a new object containing all key-value pairs.
      • If a key does not exist, fallback is returned. This also applies when selection is an array: missing keys will be mapped to fallback in the returned object.
      • An explicit undefined for fallback results in null (unlike the native mw.config).
      set(selection?: string | object, value?: any): boolean;
      
      • If selection is a string, value must be provided. The key-value pair will be set accordingly.
      • If selection is an object, each key-value pair will be set.
      • Built-in wg-variables cannot be modified ― attempting to do so always returns false.
      • Returns true if at least one property is successfully set.
      • If value is undefined, the key is not set.
      exists(selection: string): boolean;
      
      • Returns true if selection exists as a key with a defined value.

      Returns MwConfig<ConfigData>

    • get defaultRequestOptions(): {
          headers: {
              "Accept-Encoding": string;
              "Content-Type": string;
              "User-Agent": string;
          };
          method: string;
          params: {
              action: string;
              format: string;
              formatversion: string;
              maxlag: number;
          };
          responseEncoding: string;
          responseType: string;
          timeout: number;
      }

      The default configurations for HTTP requests.

      {
      method: 'GET',
      headers: {
      'User-Agent': `mwbot-ts/${MWBOT_VERSION} (https://github.com/Dr4goniez/mwbot-ts)`,
      'Content-Type': 'application/x-www-form-urlencoded',
      'Accept-Encoding': 'gzip'
      },
      params: {
      action: 'query',
      format: 'json',
      formatversion: '2',
      maxlag: 5
      },
      timeout: 60 * 1000, // 60 seconds
      responseType: 'json',
      responseEncoding: 'utf8'
      }

      Returns {
          headers: {
              "Accept-Encoding": string;
              "Content-Type": string;
              "User-Agent": string;
          };
          method: string;
          params: {
              action: string;
              format: string;
              formatversion: string;
              maxlag: number;
          };
          responseEncoding: string;
          responseType: string;
          timeout: number;
      }

    Methods

    • Internal handler for instance initialization.

      Parameters

      • attemptIndex: number

        The number of times we have attempted initialization, including the current attempt. On a certain type of failure, a retry is attempted once (i.e., when this index is less than or equal to 2).

      Returns Promise<Mwbot>

      A Promise resolving to the current instance, or rejecting with an error.

    • Performs a raw HTTP request to the MediaWiki API.

      This method assumes that the request body has been fully processed, meaning all necessary parameters have been formatted, validated, and encoded as required by the API.

      Parameters

      • requestOptions: MwbotRequestConfig

        The finalized HTTP request options, ready for transmission.

      • OptionalattemptCount: number

        The number of attemps that have been made so far.

      Returns Promise<ApiResponse>

      A Promise resolving to the API response, or rejecting with an error.

    • Aborts all unfinished HTTP requests issued by this instance.

      Returns this

    • Applies authentication to the request config.

      • Adds an Authorization header if OAuth is used.
      • Sets jar and withCredentials for cookie-based authentication otherwise.

      NOTE: url and method must be set beforehand.

      Parameters

      Returns void

    • Marks a cached token of the specified type as invalid.

      Parameters

      • tokenType: string

        The type of token to invalidate (e.g., csrf).

      Returns this

      The current instance for chaining.

    • Blocks a user.

      Enforced parameters:

      {
      action: 'block',
      format: 'json',
      formatversion: '2'
      }

      Default parameters:

      {
      user: target,
      anononly: true, // Soft-block
      nocreate: true,
      autoblock: true,
      allowusertalk: true
      }

      Parameters

      • target: string

        The user name, IP address, or user ID to block.

      • additionalParams: ApiParamsActionBlock = {}

        Additional parameters for action=block. If any of these parameters conflict with the enforced ones, the enforced values take precedence.

      • OptionalrequestOptions: MwbotRequestConfig

        Optional HTTP request options.

      Returns Promise<ApiResponseBlock>

      A Promise resolving to the response.block object, or rejecting with an error.

      If:

      • The client is anonymous. (anonymous)
      • The client lacks the block user right. (nopermission)
      • target is not a string. (typemismatch)
    • Performs API requests that automatically continue until the limit is reached.

      This method is designed for API modules that support continuation using a continue property in the response.

      Usage Note: If applicable, ensure the API parameters include a **limit value set to 'max' to retrieve the maximum number of results per request.

      Parameters

      • parameters: ApiParams

        Parameters to send to the API.

      • Optionaloptions: { limit?: number; multiValues?: string | string[]; rejectProof?: false }

        Optional continuation and batching settings.

        • Optionallimit?: number

          The maximum number of continuation cycles (default: 10). Must be a positive integer or Infinity.

        • OptionalmultiValues?: string | string[]

          The key or keys of multi-value fields that must be split into batches of up to apilimit. Specifying this option incorporates the function of massRequest. See the throw conditions of createBatchArray for the validation of these fields.

        • OptionalrejectProof?: false
          • If false (default), rejects the Promise if any internal API request fails, discarding all previously retrieved responses.
          • If true, failed requests are caught and appended as MwbotError into the result array.
      • OptionalrequestOptions: MwbotRequestConfig

        Optional HTTP request options.

      Returns Promise<ApiResponse[]>

      • If rejectProof is false, resolves to an array of API responses.
      • If rejectProof is true, resolves to the same, but can include error objects.

      NOTE: If multiValues is set and the relevant fields are empty arrays, returns an empty array.

      If:

      • limit is specified but is neither a positive integer nor Infinity. (invalidlimit)
      • multiValues is specified but fails validation via createBatchArray.
    • Performs API requests that automatically continue until the limit is reached.

      This method is designed for API modules that support continuation using a continue property in the response.

      Usage Note: If applicable, ensure the API parameters include a **limit value set to 'max' to retrieve the maximum number of results per request.

      Parameters

      • parameters: ApiParams

        Parameters to send to the API.

      • options: { limit?: number; multiValues?: string | string[]; rejectProof: true }

        Optional continuation and batching settings.

        • Optionallimit?: number

          The maximum number of continuation cycles (default: 10). Must be a positive integer or Infinity.

        • OptionalmultiValues?: string | string[]

          The key or keys of multi-value fields that must be split into batches of up to apilimit. Specifying this option incorporates the function of massRequest. See the throw conditions of createBatchArray for the validation of these fields.

        • rejectProof: true
          • If false (default), rejects the Promise if any internal API request fails, discarding all previously retrieved responses.
          • If true, failed requests are caught and appended as MwbotError into the result array.
      • OptionalrequestOptions: MwbotRequestConfig

        Optional HTTP request options.

      Returns Promise<(ApiResponse | MwbotError<keyof MwbotErrorCodes>)[]>

      • If rejectProof is false, resolves to an array of API responses.
      • If rejectProof is true, resolves to the same, but can include error objects.

      NOTE: If multiValues is set and the relevant fields are empty arrays, returns an empty array.

      If:

      • limit is specified but is neither a positive integer nor Infinity. (invalidlimit)
      • multiValues is specified but fails validation via createBatchArray.
    • Creates a new page with the given content.

      • To save a content to an (existing) page, use save instead.
      • To edit an existing page using a transformation predicate, use edit instead.

      Enforced parameters:

      {
      action: 'edit',
      format: 'json',
      formatversion: '2',
      // `token` is automatically appended
      }

      Default parameters (can be overridden):

      {
      title: title,
      text: content,
      summary: summary,
      bot: true,
      createonly: true
      }

      Parameters

      • title: string | Title

        The new page title, either as a string or a Title instance.

      • content: string

        The text content of the new page.

      • Optionalsummary: string

        An optional edit summary.

      • additionalParams: ApiParamsActionEdit = {}

        Additional parameters for action=edit. If any of these parameters conflict with the enforced ones, the enforced values take precedence.

      • OptionalrequestOptions: MwbotRequestConfig

        Optional HTTP request options.

      Returns Promise<ApiResponseEditSuccess>

      A Promise resolving to the response.edit object (where the result property is guaranteed to be 'Success'), or rejecting with an error.

    • Creates a batch array for an API request involving multi-value fields.

      Each batch will contain up to batchSize values (or apilimit if not provided), and all specified keys must refer to identical arrays of strings. This ensures consistent batching across all multi-value fields.

      Parameters

      • parameters: ApiParams

        The API parameters object.

      • keys: string[]

        An array of parameter names that are expected to hold multiple values.

      • OptionalbatchSize: number

        Optional maximum number of items per batch. Must be a positive integer less than or equal to apilimit (defaults to apilimit).

      Returns string[][]

      An array of string arrays, each representing a single API batch.

      If:

      • keys is an empty array. (emptyinput)
      • Any element in keys is not a string. (typemismatch)
      • The corresponding parameters[key] is not an array. (typemismatch)
      • The arrays for multiple fields are not identical. (fieldmismatch)
      • No valid multi-value fields are found. (nofields)
      • batchSize is invalid. (invalidsize)
    • Deletes a page.

      Enforced parameters:

      {
      action: 'delete',
      title: titleOrId, // If a string or a Title instance
      pageid: titleOrId, // If a number
      format: 'json',
      formatversion: '2'
      }

      Parameters

      • titleOrId: string | number | Title

        The title or ID of the page to delete.

      • additionalParams: Partial<ApiParamsActionDelete> = {}

        Additional parameters for action=delete. If any of these parameters conflict with the enforced ones, the enforced values take precedence.

      • OptionalrequestOptions: MwbotRequestConfig

        Optional HTTP request options.

      Returns Promise<ApiResponseDelete>

      A Promise resolving to the response.delete object, or rejecting with an error.

      If:

      • The client is anonymous. (anonymous)
      • The client lacks the delete user right. (nopermission)
      • titleOrId, if not a number, fails validation via validateTitle.
    • Throws an api_mwbot: anonymous error if the client is authenticated as anonymous.

      Parameters

      • condition: boolean = true

        Optional additional condition (default: true). The error is thrown only if this is true and the client is anonymous.

      Returns void

      If the client is anonymous and the condition is true.

    • Throws an error if the page opts out of bot editing via {{bots}} or {{nobots}} templates.

      This method checks the parsed wikitext for templates named {{bots}} or {{nobots}} and enforces bot exclusion rules based on the parameters allow, deny, or optout. If the page explicitly opts out of bot actions for the current user or for any of the specified complianceTypes, a MwbotError is thrown.

      It also emits console warnings for any suspicious or conflicting use of these templates, such as:

      • both allow and deny present in one {{bots}}
      • parameters inside {{nobots}}
      • presence of both {{bots}} and {{nobots}} on the same page
      • multiple instances of either template

      Parameters

      • title: string

        The title of the page being processed.

      • wikitext: Wikitext

        A Wikitext instance for the page, used to extract templates.

      • complianceTypes: string | string[] = []

        A message type or list of message types to check against |optout=.

      Returns void

      If bot access is denied, either by a {{nobots}} template or a {{bots}} template that excludes the current user or any of the specified complianceTypes. (botdenied)

    • Throws an error if the client is anonymous or lacks the required rights.

      Parameters

      • rights: string | string[]

        A single right or list of rights required to perform the action.

      • actionDescription: string

        A brief description of the action requiring the rights. This will be included in the error message if permission is denied.

      • allowAnonymous: boolean = false

        Whether to allow anonymous users to proceed. Defaults to false.

      Returns void

      If:

      • allowAnonymous is false and the client is anonymous. (anonymous)
      • The client lacks the required rights. (nopermission)
    • Edits an existing page by first fetching its latest revision and applying a transformation function to modify its content.

      This method automatically handles edit conflicts up to 3 times.

      Enforced parameters:

      {
      action: 'edit',
      format: 'json',
      formatversion: '2',
      // `token` is automatically appended
      }

      Default parameters (can be overridden by the return value of transform):

      {
      title: revision.title, // Erased if "pageid" is provided
      bot: true,
      baserevid: revision.baserevid,
      basetimestamp: revision.basetimestamp,
      starttimestamp: revision.starttimestamp,
      nocreate: true
      }

      Parameters

      Returns Promise<ApiResponseEditSuccess>

      A Promise resolving to the response.edit object (where the result property is guaranteed to be 'Success'), or rejecting with an error.

    • Performs an HTTP request to fetch data, defaulting to the 'GET' method, but automatically switches to 'POST' if the request parameters are too long.

      This is a shorthand for calling request(params, { autoMethod: true }).

      Parameters

      Returns Promise<ApiResponse>

      A Promise resolving to the API response, or rejecting with an error.

    • Retrieves a list of pages that link to the given page(s).

      Enforced parameters:

      {
      action: 'query',
      titles: titles,
      prop: 'linkshere',
      lhlimit: 'max',
      format: 'json',
      formatversion: '2'
      }

      Parameters

      • titles: string | Title

        A single title or an array of titles to enumerate backlinks for.

      • OptionaladditionalParams: ApiParams

        Additional parameters for prop=linkshere. If any of these parameters conflict with the enforced ones, the enforced values take precedence.

      • OptionalrequestOptions: MwbotRequestConfig

        Optional HTTP request options.

      Returns Promise<ApiResponseQueryPagesPropLinkshere[]>

      A Promise that resolves to:

      • An array of linkshere objects if a single title is provided.
      • An object mapping each normalized title (as returned by TitleStatic.normalize in 'api' format) to an array of linkshere objects if multiple titles are provided.

      If

      • Any input title fails validation via validateTitle (with allowSpecial set to true).
      • titles is an empty array. (emptyinput)
    • Retrieves a list of pages that link to the given page(s).

      Enforced parameters:

      {
      action: 'query',
      titles: titles,
      prop: 'linkshere',
      lhlimit: 'max',
      format: 'json',
      formatversion: '2'
      }

      Parameters

      • titles: (string | Title)[]

        A single title or an array of titles to enumerate backlinks for.

      • OptionaladditionalParams: ApiParams

        Additional parameters for prop=linkshere. If any of these parameters conflict with the enforced ones, the enforced values take precedence.

      • OptionalrequestOptions: MwbotRequestConfig

        Optional HTTP request options.

      Returns Promise<Record<string, ApiResponseQueryPagesPropLinkshere[]>>

      A Promise that resolves to:

      • An array of linkshere objects if a single title is provided.
      • An object mapping each normalized title (as returned by TitleStatic.normalize in 'api' format) to an array of linkshere objects if multiple titles are provided.

      If

      • Any input title fails validation via validateTitle (with allowSpecial set to true).
      • titles is an empty array. (emptyinput)
    • Retrieves the categories that the given title(s) belong to.

      Parameters

      • titles: string | Title

        A single title or an array of titles to enumerate categories for.

      • Optionalhidden: boolean

        A specification to enumerate hidden categories. This manipulates the clshow parameter for prop=categories:

        • If not provided, enumerates both hidden and unhidden categories.
        • If true, only enumerates hidden categories (clshow=hidden).
        • If false, only enumerates unhidden categories (clshow=!hidden).
      • OptionalrequestOptions: MwbotRequestConfig

        Optional HTTP request options.

      Returns Promise<string[]>

      A Promise that resolves to:

      • An array of category titles (without the namespace prefix) if a single title is provided.
      • An object mapping each normalized title (as returned by TitleStatic.normalize in 'api' format) to an array of category titles (without the namespace prefix) if multiple titles are provided.

      If

      • Any input title fails validation via validateTitle.
      • titles is an empty array. (emptyinput)
    • Retrieves the categories that the given title(s) belong to.

      Parameters

      • titles: (string | Title)[]

        A single title or an array of titles to enumerate categories for.

      • Optionalhidden: boolean

        A specification to enumerate hidden categories. This manipulates the clshow parameter for prop=categories:

        • If not provided, enumerates both hidden and unhidden categories.
        • If true, only enumerates hidden categories (clshow=hidden).
        • If false, only enumerates unhidden categories (clshow=!hidden).
      • OptionalrequestOptions: MwbotRequestConfig

        Optional HTTP request options.

      Returns Promise<Record<string, string[]>>

      A Promise that resolves to:

      • An array of category titles (without the namespace prefix) if a single title is provided.
      • An object mapping each normalized title (as returned by TitleStatic.normalize in 'api' format) to an array of category titles (without the namespace prefix) if multiple titles are provided.

      If

      • Any input title fails validation via validateTitle.
      • titles is an empty array. (emptyinput)
    • Retrieves a list of categories whose titles match the specified prefix.

      Parameters

      • prefix: string

        The prefix to match.

      • limit: number = Infinity

        The maximum number of continuation cycles to perform (default: Infinity). Specify this if the prefix is very generic and may produce too many results.

      • OptionalrequestOptions: MwbotRequestConfig

        Optional HTTP request options.

      Returns Promise<string[]>

      A Promise that resolves to an array of matched category titles, excluding the namespace prefix.

      If limit is provided and is not a positive integer or Infinity. (invalidlimit)

    • Retrieves a list of pages that belong to the given category.

      Enforced parameters:

      {
      action: 'query',
      list: 'categorymembers',
      cmtitle: titleOrId, // If a string or a Title instance
      cmpageid: titleOrId, // If a number
      cmlimit: 'max',
      format: 'json',
      formatversion: '2'
      }

      Parameters

      • titleOrId: string | number | Title

        The prefixed title or the page ID of the category to enumerate.

      • additionalParams: ApiParams = {}

        Additional parameters for list=categorymembers. If any of these parameters conflict with the enforced ones, the enforced values take precedence.

      • OptionalrequestOptions: MwbotRequestConfig

        Optional HTTP request options.

      Returns Promise<ApiResponseQueryListCategorymembers[]>

      A Promise resolving to the result array in response.query.categorymembers, or rejecting with an error.

      If:

      • titleOrId, if not a number, fails title validation via validateTitle.
      • titleOrId, if not a number, is not a category title. (invalidtitle)
    • Retrieves a csrf token from the API.

      This is a shorthand method of getToken.

      Parameters

      Returns Promise<string>

      A Promise resolving to a CSRF token, or rejecting with an error.

    • Gets a function to check whether pages exist.

      Example:

      // Suppose 'Foo' exists but 'Bar' does not
      const exists = await mwbot.getExistencePredicate(['Foo', 'Bar']);
      exists('Foo'); // true
      exists('Bar'); // false
      exists('Baz'); // null

      See ExistencePredicate for details on the returned function.

      Parameters

      • titles: (string | Title)[]

        The titles to check for existence.

      • options: { loose?: boolean; rejectProof?: boolean } = {}
        • Optionalloose?: boolean

          Whether to apply loose validation to the titles input.

          • If false (default), the method throws if any input title fails validation via validateTitle.
          • If true, such titles are skipped (and exists() will return null for them).
        • OptionalrejectProof?: boolean

          Whether to suppress request errors (default: false). If set to true, the method always resolves to a function, though that function may return null frequently due to missing data.

      • OptionalrequestOptions: MwbotRequestConfig

        Optional HTTP request options.

      Returns Promise<ExistencePredicate>

      A Promise that resolves to an exists() function, or rejects with an error (unless rejectProof is true).

    • Retrieves a token of the specified type from the API.

      If a cached token is available, it is returned immediately. Otherwise, an API request is made to fetch a new token.

      Enforced parameters:

      {
      action: 'query',
      meta: 'tokens',
      type: '*',
      format: 'json',
      formatversion: '2'
      }

      Parameters

      • tokenType: string

        The type of token to retrieve (e.g., csrf).

      • OptionaladditionalParams: ApiParams | "user" | "bot" | "anon"

        Additional API parameters. If a string is provided, it is treated as the assert parameter. If any of these parameters conflict with the enforced ones, the enforced values take precedence.

      • OptionalrequestOptions: MwbotRequestConfig

        Optional HTTP request options.

      Returns Promise<string>

      A Promise resolving to the retrieved token, or rejecting with an error.

    • Gets type of token to be used with an API action.

      Parameters

      • action: string

        The API's action parameter value.

      Returns Promise<null | string>

      A Promise resolving to the token type as a string, or null on failure.

      This method never rejects.

    • Retrieves a list of pages that transclude the given page(s).

      Enforced parameters:

      {
      action: 'query',
      titles: titles,
      prop: 'transcludedin',
      tilimit: 'max',
      format: 'json',
      formatversion: '2'
      }

      Parameters

      • titles: string | Title

        A single title or an array of titles to enumerate transclusions for.

      • OptionaladditionalParams: ApiParams

        Additional parameters for prop=transcludedin. If any of these parameters conflict with the enforced ones, the enforced values take precedence.

      • OptionalrequestOptions: MwbotRequestConfig

        Optional HTTP request options.

      Returns Promise<ApiResponseQueryPagesPropTranscludedin[]>

      A Promise that resolves to:

      • An array of transcludedin objects if a single title is provided.
      • An object mapping each normalized title (as returned by TitleStatic.normalize in 'api' format) to an array of transcludedin objects if multiple titles are provided.

      If

      • Any input title fails validation via validateTitle (with allowSpecial set to true).
      • titles is an empty array. (emptyinput)
    • Retrieves a list of pages that transclude the given page(s).

      Enforced parameters:

      {
      action: 'query',
      titles: titles,
      prop: 'transcludedin',
      tilimit: 'max',
      format: 'json',
      formatversion: '2'
      }

      Parameters

      • titles: (string | Title)[]

        A single title or an array of titles to enumerate transclusions for.

      • OptionaladditionalParams: ApiParams

        Additional parameters for prop=transcludedin. If any of these parameters conflict with the enforced ones, the enforced values take precedence.

      • OptionalrequestOptions: MwbotRequestConfig

        Optional HTTP request options.

      Returns Promise<Record<string, ApiResponseQueryPagesPropTranscludedin[]>>

      A Promise that resolves to:

      • An array of transcludedin objects if a single title is provided.
      • An object mapping each normalized title (as returned by TitleStatic.normalize in 'api' format) to an array of transcludedin objects if multiple titles are provided.

      If

      • Any input title fails validation via validateTitle (with allowSpecial set to true).
      • titles is an empty array. (emptyinput)
    • Handles data encoding for POST requests (calls handlePostMultipartFormData for multipart/form-data).

      Parameters

      • requestOptions: MwbotRequestConfig

        The HTTP request options to modify.

      • hasLongFields: boolean

        A boolean indicating whether the parameters have a long field.

      Returns Promise<void>

    • Handles POST requests with multipart/form-data encoding.

      • Converts params into a FormData object.
      • Supports file uploads if params contain an object with a stream property.

      Parameters

      • requestOptions: MwbotRequestConfig

        The HTTP request options to modify.

      • Optionaltoken: string

        Optional token for authentication.

      Returns Promise<void>

    • Checks whether the authenticated user has the specified user right(s).

      Parameters

      • rights: string | string[]

        The user right or list of rights to check.

      • requireAll: boolean = true

        Whether to require all rights (true, default) or any one of them (false).

      Returns boolean

      true if the user has the specified right(s) according to the given condition; otherwise false.

    • Checks whether the instance has been initialized for an anonymous user.

      Returns boolean

      A boolean indicating whether the instance was initialized for an anonymous user.

    • Logs in to the wiki for which this instance has been initialized.

      Parameters

      • username: string
      • password: string

      Returns Promise<ApiResponse>

      A Promise resolving to the API response, or rejecting with an error.

    • Performs API requests with a multi-value field that is subject to the apilimit, processing multiple requests in parallel if necessary.

      For example:

      {
      action: 'query',
      titles: 'A|B|C|D|...', // This parameter is subject to the apilimit of 500 or 50
      formatversion: '2'
      }

      Pass the multi-value field as an array, and this method will automatically split it based on the user's apilimit (500 for bots, 50 otherwise). The key(s) of the multi-value field(s) must be passed as the second parameter.

      Request method:

      By default, this method assumes a read-only request and automatically chooses between GET and POST. To perform a database write action, requestOptions.method must be explicitly set to 'POST'.

      Parameters

      • parameters: ApiParams

        Parameters to the API, including multi-value fields.

      • keys: string | string[]

        The key(s) of the multi-value field(s) to split (e.g., titles).

      • OptionalbatchSize: number

        Optional batch size (defaults to the apilimit). Must be a positive integer less than or equal to the apilimit.

      • OptionalrequestOptions: MwbotRequestConfig

        Optional HTTP request options.

      Returns Promise<(ApiResponse | MwbotError<keyof MwbotErrorCodes>)[]>

      A Promise resolving to an array of API responses or MwbotError objects for failed requests. The array will be empty if no values are provided to batch.

      If multi-values fail validation via createBatchArray.

    • Moves a page.

      Enforced parameters:

      {
      action: 'move',
      from: from, // If a string or a Title instance
      fromid: from, // If a number
      to: to,
      format: 'json',
      formatversion: '2'
      }

      Parameters

      • from: string | number | Title

        The title or ID of the page to move.

      • to: string | Title

        The destination title.

      • additionalParams: Partial<ApiParamsActionMove> = {}

        Additional parameters for action=move. If any of these parameters conflict with the enforced ones, the enforced values take precedence.

      • OptionalrequestOptions: MwbotRequestConfig

        Optional HTTP request options.

      Returns Promise<ApiResponseMove>

      A Promise resolving to the response.move object, or rejecting with an error.

      If:

      • The client is anonymous. (anonymous)
      • The client lacks the move user right. (nopermission)
      • from is not a number and fails validation via validateTitle.
      • to fails validation via validateTitle.
    • Posts a new section to the given page.

      Enforced parameters:

      {
      action: 'edit',
      format: 'json',
      formatversion: '2',
      // `token` is automatically appended
      }

      Default parameters (can be overridden):

      {
      title: title,
      section: 'new',
      sectiontitle: sectiontitle,
      text: content,
      summary: summary,
      bot: true
      }

      Parameters

      • title: string | Title

        The title of the page to edit.

      • sectiontitle: string

        The section title.

      • content: string

        The content of the new section.

      • Optionalsummary: string

        An optional edit summary. If not provided, the API generates one automatically.

      • additionalParams: ApiParamsActionEdit = {}

        Additional parameters for action=edit. If any of these parameters conflict with the enforced ones, the enforced values take precedence.

      • OptionalrequestOptions: MwbotRequestConfig

        Optional HTTP request options.

      Returns Promise<ApiResponseEditSuccess>

      A Promise resolving to the response.edit object (where the result property is guaranteed to be 'Success'), or rejecting with an error.

    • Performs an HTTP POST request to the MediaWiki API to fetch data. This method should only be used to circumvent a 414 URI too long error; otherwise, use get.

      Per [[mw:API:Etiquette#Other notes]], Promise-Non-Write-API-Action: true will be set to the request headers automatically.

      Parameters

      Returns Promise<ApiResponse>

      A Promise resolving to the API response, or rejecting with an error.

    post

    • Performs a POST request to the MediaWiki API using a token of the specified type.

      This method retrieves a token automatically, before performing the request. If a cached token exists, it is used first; if the request fails due to an invalid token (badtoken), the token cache is cleared, and a retry is attempted.

      Example usage:

      mwbot.postWithToken('csrf', {
      action: 'options',
      optionname: 'gender',
      optionvalue: 'female'
      });

      Parameters

      • tokenType: string

        The type of token to use (e.g., csrf).

      • parameters: ApiParams

        Parameters to the API.

      • OptionalrequestOptions: MwbotRequestConfig

        Optional HTTP request options.

      Returns Promise<ApiResponse>

      A Promise resolving to the API response, or rejecting with an error.

    • Performs a prefix search for page titles.

      Enforced parameters:

      {
      action: 'query',
      list: 'prefixsearch',
      pssearch: target,
      pslimit: 'max',
      format: 'json',
      formatversion: '2'
      }

      Parameters

      • target: string

        The search string.

      • additionalParams: ApiParams = {}

        Additional parameters for list=prefixsearch. If any of these parameters conflict with the enforced ones, the enforced values take precedence.

      • limit: number = Infinity

        The maximum number of continuation cycles to perform (default: Infinity). Specify this if the target is very generic and may produce too many results.

      • OptionalrequestOptions: MwbotRequestConfig

        Optional HTTP request options.

      Returns Promise<ApiResponseQueryListPrefixsearch[]>

      A Promise resolving to the result array in response.query.prefixsearch, or rejecting with an error.

      If:

      • target is not a string. (typemismatch)
      • target is empty. (emptyinput)
      • limit is provided and is not a positive integer or Infinity. (invalidlimit)
    • Massages parameters from the nice format we accept into a format suitable for the API.

      Parameters

      Returns { hasLongFields: boolean; length: number }

      An object containing:

      • length: The UTF-8 byte length of the encoded query string.
      • hasLongFields: Whether any field value exceeds 8000 characters.
    • Protects a page.

      Enforced parameters:

      {
      action: 'protect',
      title: titleOrId, // If a string or a Title instance
      pageid: titleOrId, // If a number
      protections: levels,
      format: 'json',
      formatversion: '2'
      }

      Parameters

      • titleOrId: string | number | Title

        The title or ID of the page to protect.

      • levels: string | string[] | { [action: string]: string }

        The protection levels to apply, in one of the following forms:

        • A pipe-separated string (e.g., 'edit=sysop|move=sysop')
        • An array of action=level strings (e.g., ['edit=sysop', 'move=sysop'])
        • An object map of actions to levels (e.g., { edit: 'sysop', move: 'sysop' })
      • additionalParams: Partial<ApiParamsActionProtect> = {}

        Additional parameters for action=protect. If any of these parameters conflict with the enforced ones, the enforced values take precedence.

      • OptionalrequestOptions: MwbotRequestConfig

        Optional HTTP request options.

      Returns Promise<ApiResponseProtect>

      A Promise resolving to the response.protect object, or rejecting with an error.

      If:

      • The client is anonymous. (anonymous)
      • The client lacks the protect user right. (nopermission)
      • titleOrId is not a number and fails validation via validateTitle.
      • levels is of an invalid type. (typemismatch)
    • Purges the cache for the given titles.

      Enforced parameters:

      {
      action: 'purge',
      titles: titles,
      format: 'json',
      formatversion: '2'
      }

      Parameters

      • titles: (string | Title)[]

        The titles to purge the cache for.

        The maximum number of values is 50 or 500 (see also apilimit).

      • additionalParams: ApiParams = {}

        Additional parameters for action=purge. If any of these parameters conflict with the enforced ones, the enforced values take precedence.

      • OptionalrequestOptions: MwbotRequestConfig

        Optional HTTP request options.

      Returns Promise<PartiallyRequired<ApiResponse, "purge">>

      A Promise that resolves to an ApiResponse object. This is the full response, not just the response.purge array, allowing access to top-level properties like normalized and redirects.

      If:

      • The client lacks the purge user right. (nopermission)
      • titles contains non-strings or non-Titles. (typemismatch)
    • Performs a raw HTTP request.

      NOTE: This method does not inject most instance-specific settings into the request config — except for session/cookie handling and cancellation.

      Parameters

      Returns Promise<AxiosResponse<any, any>>

      A Promise that resolves to the raw Axios response.

    • Retrieves the latest revision content of a given title from the API.

      Parameters

      • title: string | Title

        The page title, either as a string or a Title instance.

      • OptionalrequestOptions: MwbotRequestConfig

        Optional HTTP request options.

      Returns Promise<Revision>

      A Promise resolving to the revision information.

      If:

      • title fails validation via validateTitle.
      • The requested title does not exist. (pagemissing)
    • Retrieves the latest revision contents of multiple titles from the API.

      This method returns a Promise resolving to an array of revision information, whose length is exactly the same as the input titles array. This ensures that each title at a specific index in titles will have its corresponding response at the same index in the returned array, preserving a strict mapping between inputs and outputs.

      Parameters

      • titles: (string | Title)[]

        An array of the page titles, either as strings or Title instances, or mixed.

      • OptionalrequestOptions: MwbotRequestConfig

        Optional HTTP request options.

      Returns Promise<(Revision | MwbotError<keyof MwbotErrorCodes>)[]>

      A Promise resolving to an array of revision information, with errors for invalid titles at their respective indexes.

    • Attempts to retry a failed request under the following conditions:

      Note: MwbotRequestConfig.disableRetryAPI must be evaluated in the then block of request, rather than here.

      Parameters

      • initialError: MwbotError

        The error that triggered the retry attempt.

      • attemptCount: number

        The number of attemps that have been made so far.

      • params: ApiParams

        Request parameters. Since _request might have deleted them, they are re-injected as needed.

      • requestOptions: MwbotRequestConfig

        The original request options, using which we make another request.

      • maxAttempts: number = 2

        The maximum number of attempts (including the first request). Default is 2 (one retry after failure).

      • sleepSeconds: number = 10

        The delay in seconds before retrying. Default is 10.

      • OptionalretryCallback: () => Promise<ApiResponse>

        A function to execute when attempting the retry. If not provided, _request is called on requestOptions.

      Returns Promise<ApiResponse>

      A Promise of the retry request, or rejecting with an error.

    • Rolls back the most recent edits to a page made by a specific user.

      Enforced parameters:

      {
      action: 'rollback',
      title: titleOrId, // If a string or a Title instance
      pageid: titleOrId, // If a number
      user: user,
      format: 'json',
      formatversion: '2'
      }

      Parameters

      • titleOrId: string | number | Title

        The title or ID of the page to rollback.

      • user: string

        The username whose consecutive edits to the page should be rolled back.

      • additionalParams: Partial<ApiParamsActionRollback> = {}

        Additional parameters for action=rollback. If any of these parameters conflict with the enforced ones, the enforced values take precedence.

      • OptionalrequestOptions: MwbotRequestConfig

        Optional HTTP request options.

      Returns Promise<ApiResponseRollback>

      A Promise resolving to the response.rollback object, or rejecting with an error.

      If:

      • The client is anonymous. (anonymous)
      • The client lacks the rollback user right. (nopermission)
      • titleOrId, if not a number, fails validation via validateTitle.
    • Saves the given content to a page.

      • To create a new page, use create instead.
      • To edit an existing page using a transformation predicate, use edit instead.

      Enforced parameters:

      {
      action: 'edit',
      format: 'json',
      formatversion: '2',
      // `token` is automatically appended
      }

      Default parameters (can be overridden):

      {
      title: title,
      text: content,
      summary: summary,
      bot: true,
      nocreate: true
      }

      Parameters

      • title: string | Title

        The page title, either as a string or a Title instance.

      • content: string

        The text content of the page.

      • Optionalsummary: string

        An optional edit summary.

      • additionalParams: ApiParamsActionEdit = {}

        Additional parameters for action=edit. If any of these parameters conflict with the enforced ones, the enforced values take precedence.

      • OptionalrequestOptions: MwbotRequestConfig

        Optional HTTP request options.

      Returns Promise<ApiResponseEditSuccess>

      A Promise resolving to the response.edit object (where the result property is guaranteed to be 'Success'), or rejecting with an error.

    • Performs a full text search.

      Enforced parameters:

      {
      action: 'query',
      list: 'search',
      srsearch: target,
      srlimit: 'max',
      format: 'json',
      formatversion: '2'
      }

      Parameters

      • target: string

        The search query string to look for in page titles or content.

      • additionalParams: ApiParams = {}

        Additional parameters for list=search. If any of these parameters conflict with the enforced ones, the enforced values take precedence.

      • OptionalrequestOptions: MwbotRequestConfig

        Optional HTTP request options.

      Returns Promise<PartiallyRequired<ApiResponseQuery, "search">>

      A Promise that resolves to the response.query object (not the response.query.search array, as list=search may return additional properties in the query object, such as searchinfo).

      If:

      • target is not a string. (typemismatch)
      • target is empty. (emptyinput)
    • Updates the bot options stored in the instance.

      Parameters

      • options: Partial<MwbotOptions>

        The new options to apply.

      • merge: boolean = true

        Whether to merge options with the existing ones (default: true).

        If false, all current settings are cleared before applying options, except for the required apiUrl property. While apiUrl can be updated if provided in options, doing so is discouraged since a Mwbot instance is initialized with site-specific data based on the URL. Instead, consider creating a new instance with a different URL.

      Returns this

      The current instance for chaining.

      If the resulting options lack an apiUrl property. (nourl)

    • Updates the default request options stored in the instance.

      Parameters

      • options: MwbotRequestConfig

        The options to apply.

      • merge: boolean = true

        Whether to merge options with the existing ones (default: true).

        If false, the current settings are cleared before applying options.

      Returns this

      The current instance for chaining.

    • Unblocks a user.

      Enforced parameters:

      {
      action: 'unblock',
      id: userOrId, // If a number
      user: userOrId, // If a string
      format: 'json',
      formatversion: '2'
      }

      Parameters

      • userOrId: string | number

        The user name, IP address, user ID, or block ID to unblock.

      • additionalParams: ApiParamsActionUnblock = {}

        Additional parameters for action=unblock. If any of these parameters conflict with the enforced ones, the enforced values take precedence.

      • OptionalrequestOptions: MwbotRequestConfig

        Optional HTTP request options.

      Returns Promise<ApiResponseUnblock>

      A Promise resolving to the response.unblock object, or rejecting with an error.

      If:

      • The client is anonymous. (anonymous)
      • The client lacks the block user right. (nopermission)
      • userOrId is neither a string nor a number. (typemismatch)
    • Undeletes revisions of a deleted page.

      Enforced parameters:

      {
      action: 'undelete',
      title: title,
      format: 'json',
      formatversion: '2'
      }

      This method does not automatically handle multi-value fields that exceed the apilimit. Such cases must be handled manually (e.g., via massRequest).

      Parameters

      • title: string | Title

        The title of the page to undelete.

      • additionalParams: Partial<ApiParamsActionUndelete> = {}

        Additional parameters for action=undelete. If any of these parameters conflict with the enforced ones, the enforced values take precedence.

      • OptionalrequestOptions: MwbotRequestConfig

        Optional HTTP request options.

      Returns Promise<ApiResponseUndelete>

      A Promise resolving to the response.undelete object, or rejecting with an error.

      If:

      • The client is anonymous. (anonymous)
      • The client lacks the undelete user right. (nopermission)
      • title fails title validation via validateTitle.
    • Unprotects a page.

      Enforced parameters:

      {
      action: 'protect',
      title: titleOrId, // If a string or a Title instance
      pageid: titleOrId, // If a number
      protections: '', // Remove all protections
      format: 'json',
      formatversion: '2'
      }

      Parameters

      • titleOrId: string | number | Title

        The title or ID of the page to protect.

      • additionalParams: Partial<ApiParamsActionProtect> = {}

        Additional parameters for action=protect. If any of these parameters conflict with the enforced ones, the enforced values take precedence.

      • OptionalrequestOptions: MwbotRequestConfig

        Optional HTTP request options.

      Returns Promise<ApiResponseProtect>

      A Promise resolving to the response.protect object, or rejecting with an error.

      If:

      • The client is anonymous. (anonymous)
      • The client lacks the protect user right. (nopermission)
      • titleOrId is not a number and fails title validation via validateTitle.
    • Checks whether the client is configured to use OAuth (v1 or v2).

      Returns boolean

      true if either oauth1 or oauth2 credentials are set; otherwise, false.

    • Validates and processes a title before use, and returns a Title instance. This method is used to normalize user input and ensure the title is valid for API access. If any validation fails, it throws an MwbotError.

      Parameters

      • title: string | Title

        The page title, either as a string or a Title instance.

      • options: { allowAnonymous?: boolean; allowSpecial?: boolean } = {}
        • OptionalallowAnonymous?: boolean

          Whether to allow anonymous users to proceed. Defaults to false.

        • OptionalallowSpecial?: boolean

          Whether to allow special page inputs. Defaults to false.

      Returns Title

      A validated Title instance.

      If:

      • The user is anonymous while allowAnonymous is false. (anonymous)
      • The title is neither a string nor a Title instance. (typemismatch)
      • The title is empty. (emptytitle)
      • The title is interwiki. (interwikititle)
      • The title is in the Special or Media namespace while allowSpecial is false. (specialtitle)
    • Throws or returns an api_mwbot: empty error.

      Parameters

      • Optionaldie: true

        Whether to throw the error (default: true). If false, the error object is returned instead of being thrown.

      • OptionaladditionalInfo: string

        Optional text to append after 'OK response but empty result'. A space is automatically prepended if provided; otherwise, a period is appended.

      • Optionaldata: MwbotErrorData

        Optional data object to set to the error.

      Returns never

    • Throws or returns an api_mwbot: empty error.

      Parameters

      • die: false

        Whether to throw the error (default: true). If false, the error object is returned instead of being thrown.

      • OptionaladditionalInfo: string

        Optional text to append after 'OK response but empty result'. A space is automatically prepended if provided; otherwise, a period is appended.

      • Optionaldata: MwbotErrorData

        Optional data object to set to the error.

      Returns MwbotError<"api_mwbot">

    • Throws a fatal internal error if the request method is not "POST".

      Parameters

      Returns void

      If the request method is missing or not "POST". (internal)

    • Constructs a standard API request parameter object for a given MediaWiki API action.

      The returned object includes:

      {
      action: action,
      format: 'json',
      formatversion: '2'
      }

      Parameters

      Returns { action: ApiParamsAction; format: "json"; formatversion: "2" }

      An object containing the action name along with fixed format and formatversion values.

    • Initializes a new Mwbot instance.

      This static factory method should always be used to create instances of Mwbot or its subclasses. It handles token fetching, site info, and class initialization in one convenient place.

      Note: The generic signature may look intimidating, but it’s designed to ensure subclasses are constructed correctly while preserving type safety. You usually don’t need to worry about it.

      Example:

      import { Mwbot, MwbotInitOptions, MwbotRequestConfig } from 'mwbot-ts';

      const initOptions: MwbotInitOptions = {
      apiUrl: 'https://en.wikipedia.org/w/api.php',
      userAgent: 'MyCoolBot/1.0.0 (https://github.com/Foo/MyCoolBot)',
      credentials: {
      oAuth2AccessToken: '...'
      }
      };
      const requestOptions: MwbotRequestConfig = { // This object is optional
      // ...
      };

      Mwbot.init(initOptions, requestOptions).then((mwbot) => {
      // Do something here and below...
      });

      Type Parameters

      Parameters

      • this: MwbotStatic
      • mwbotInitOptions: MwbotInitOptions

        Configuration object containing initialization settings and user credentials.

      • requestOptions: MwbotRequestConfig = {}

        Custom request options applied to all HTTP requests issued by the new instance.

      Returns Promise<InstanceOf<MwbotStatic>>

      A Promise resolving to a new Mwbot instance, or rejecting with an error.

    • Converts legacy token types to csrf.

      Parameters

      • action: string

      Returns string

    • Returns a deep-cloned version of the given request options, ensuring that the returned object is safe to mutate without affecting the original.

      If requestOptions is undefined or an empty object, a new object with _cloned: true is returned immediately to avoid unnecessary cloning.

      If the _cloned flag is already present and truthy, the original object is returned as-is. Otherwise, the object is deeply cloned via mergeDeep(), and _cloned is set to true on the resulting object to prevent redundant cloning on future calls.

      Parameters

      • OptionalrequestOptions: MwbotRequestConfig

        The request options to check and clone if needed.

      Returns MwbotRequestConfig

      A safely cloneable MwbotRequestConfig object with _cloned set to true.

    • Validates user credentials and determines the authentication type.

      Parameters

      • credentials: Credentials

        The credentials object provided by the user.

      Returns MwbotCredentials

      Validated credentials.

      If the credentials format is incorrect, or if unexpected keys are present. (invalidcreds)