Protected
constructorCreates a Mwbot
instance.
This constructor is protected. Use init instead to create a new instance.
Configuration object containing initialization settings and user credentials.
Custom request options applied to all HTTP requests issued by the new instance.
Protected
_Protected
_Protected
_Protected
_Protected
_Protected
_Protected
_Protected
_Protected
abortionsAn array of AbortController
s used in abort.
Protected
Readonly
agentsCustom agents that manage keep-alive connections for HTTP requests. These are injected into the request options when using OAuth.
Protected
Readonly
axiosAxios instance for this intance.
Protected
Readonly
configStores configuration values for the site and user.
Protected
Readonly
configThe wg
-keys of ConfigData, used in config to verify their existence.
Protected
Readonly
credentialsUser credentials.
Protected
Readonly
jarA cookie jar that stores session and login cookies for this instance.
Protected
lastThe timestamp (in milliseconds since the UNIX epoch) of the last successful request. This is updated only for API actions specified in MwbotOptions.intervalActions.
Protected
tokensCashed MediaWiki tokens.
The user options for this intance.
The user-defined configurations for HTTP requests.
Returns the user's API limit for multi-value requests.
500
for users with the apihighlimits
permission; otherwise, 50
.
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;
selection
is a string, returns the corresponding value.selection
is an array, returns an object mapping each key to its value.selection
is provided, returns a new object containing all key-value pairs.fallback
is returned. This also applies when selection
is an array: missing keys will be mapped to fallback
in the returned object.undefined
for fallback
results in null
(unlike the native mw.config
).set(selection?: string | object, value?: any): boolean;
selection
is a string, value
must be provided. The key-value pair will be set accordingly.selection
is an object, each key-value pair will be set.wg
-variables cannot be modified ― attempting to do so always returns false
.true
if at least one property is successfully set.value
is undefined
, the key is not set.exists(selection: string): boolean;
true
if selection
exists as a key with a defined value.FileWikilink class for this instance.
Returns (a deep copy of) the site and user information fetched by init.
ParserFunction class for this instance.
RawWikilink class for this instance.
Template class for this instance.
Title class for this instance.
Wikilink class for this instance.
Wikitext class for this instance.
Protected
Static
defaultStatic
defaultThe 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'
}
Static
StringString
library with functions to manipulate strings.
Static
UtilUtil
library with convenient functions.
Protected
_Internal handler for instance initialization.
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
).
A Promise resolving to the current instance, or rejecting with an error.
Protected
_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.
The finalized HTTP request options, ready for transmission.
Optional
attemptCount: numberThe number of attemps that have been made so far.
A Promise resolving to the API response, or rejecting with an error.
Protected
_Sends an action=edit
request.
Optional
summary: stringMethod-specific default parameters, which additionalParams
should be able to override.
User-provided additional parameters.
Optional
requestOptions: MwbotRequestConfigAborts all unfinished HTTP requests issued by this instance.
Protected
applyApplies authentication to the request config.
Authorization
header if OAuth is used.jar
and withCredentials
for cookie-based authentication otherwise.NOTE: url
and method
must be set beforehand.
Marks a cached token of the specified type as invalid.
The type of token to invalidate (e.g., csrf
).
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
}
The user name, IP address, or user ID to block.
Additional parameters for action=block
.
If any of these parameters conflict with the enforced ones, the enforced values take precedence.
Optional
requestOptions: MwbotRequestConfigOptional HTTP request options.
A Promise resolving to the response.block
object, or rejecting with an error.
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 to send to the API.
Optional
options: { limit?: number; multiValues?: string | string[]; rejectProof?: false }Optional continuation and batching settings.
Optional
limit?: numberThe maximum number of continuation cycles (default: 10
). Must be a positive integer or
Infinity
.
Optional
multiValues?: 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.
Optional
rejectProof?: falsefalse
(default), rejects the Promise if any internal API request fails, discarding
all previously retrieved responses.true
, failed requests are caught and appended as MwbotError into the result
array.Optional
requestOptions: MwbotRequestConfigOptional HTTP request options.
rejectProof
is false
, resolves to an array of API responses.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 to send to the API.
Optional continuation and batching settings.
Optional
limit?: numberThe maximum number of continuation cycles (default: 10
). Must be a positive integer or
Infinity
.
Optional
multiValues?: 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.
false
(default), rejects the Promise if any internal API request fails, discarding
all previously retrieved responses.true
, failed requests are caught and appended as MwbotError into the result
array.Optional
requestOptions: MwbotRequestConfigOptional HTTP request options.
rejectProof
is false
, resolves to an array of API responses.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.
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
}
The new page title, either as a string or a Title instance.
The text content of the new page.
Optional
summary: stringAn optional edit summary.
Additional parameters for action=edit
.
If any of these parameters conflict with the enforced ones, the enforced values take precedence.
Optional
requestOptions: MwbotRequestConfigOptional HTTP request options.
A Promise resolving to the response.edit
object (where the result
property is guaranteed
to be 'Success'
), or rejecting with an error.
Protected
createCreates 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.
The API parameters object.
An array of parameter names that are expected to hold multiple values.
Optional
batchSize: numberOptional maximum number of items per batch. Must be a positive integer less than or
equal to apilimit
(defaults to apilimit
).
An array of string arrays, each representing a single API batch.
If:
keys
is an empty array. (emptyinput
)keys
is not a string. (typemismatch
)parameters[key]
is not an array. (typemismatch
)fieldmismatch
)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'
}
The title or ID of the page to delete.
Additional parameters for action=delete
.
If any of these parameters conflict with the enforced ones, the enforced values take precedence.
Optional
requestOptions: MwbotRequestConfigOptional HTTP request options.
A Promise resolving to the response.delete
object, or rejecting with an error.
If:
anonymous
)delete
user right. (nopermission
)titleOrId
, if not a number, fails validation via validateTitle.Protected
dieThrows an api_mwbot: anonymous
error if the client is authenticated as anonymous.
Optional additional condition (default: true
). The error is thrown
only if this is true
and the client is anonymous.
Protected
dieThrows 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:
allow
and deny
present in one {{bots}}
{{nobots}}
{{bots}}
and {{nobots}}
on the same pageProtected
dieThrows an error if the client is anonymous or lacks the required rights.
A single right or list of rights required to perform the action.
A brief description of the action requiring the rights. This will be included in the error message if permission is denied.
Whether to allow anonymous users to proceed. Defaults to false
.
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
}
The page title, either as a string or a Title instance.
See TransformationPredicate for details.
Optional
editRequestOptions: MwbotRequestConfig & ExclusionComplianceConfigOptional HTTP request options and exclusion compliance options.
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 to the API.
Optional
requestOptions: MwbotRequestConfigOptional HTTP request options.
A Promise resolving to the API response, or rejecting with an error.
Performs an HTTP GET request to the MediaWiki API.
Parameters to the API.
Optional
requestOptions: MwbotRequestConfigOptional HTTP request options.
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'
}
A single title or an array of titles to enumerate backlinks for.
Optional
additionalParams: ApiParamsAdditional parameters for prop=linkshere
.
If any of these parameters conflict with the enforced ones, the enforced values take precedence.
Optional
requestOptions: MwbotRequestConfigOptional HTTP request options.
A Promise that resolves to:
linkshere
objects if a single title is provided.'api'
format)
to an array of linkshere
objects if multiple titles are provided.If
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'
}
A single title or an array of titles to enumerate backlinks for.
Optional
additionalParams: ApiParamsAdditional parameters for prop=linkshere
.
If any of these parameters conflict with the enforced ones, the enforced values take precedence.
Optional
requestOptions: MwbotRequestConfigOptional HTTP request options.
A Promise that resolves to:
linkshere
objects if a single title is provided.'api'
format)
to an array of linkshere
objects if multiple titles are provided.If
allowSpecial
set to true
).titles
is an empty array. (emptyinput
)Retrieves the categories that the given title(s) belong to.
A single title or an array of titles to enumerate categories for.
Optional
hidden: booleanA specification to enumerate hidden categories. This manipulates the clshow
parameter
for prop=categories
:
true
, only enumerates hidden categories (clshow=hidden
).false
, only enumerates unhidden categories (clshow=!hidden
).Optional
requestOptions: MwbotRequestConfigOptional HTTP request options.
A Promise that resolves to:
'api'
format)
to an array of category titles (without the namespace prefix) if multiple titles are provided.Retrieves the categories that the given title(s) belong to.
A single title or an array of titles to enumerate categories for.
Optional
hidden: booleanA specification to enumerate hidden categories. This manipulates the clshow
parameter
for prop=categories
:
true
, only enumerates hidden categories (clshow=hidden
).false
, only enumerates unhidden categories (clshow=!hidden
).Optional
requestOptions: MwbotRequestConfigOptional HTTP request options.
A Promise that resolves to:
'api'
format)
to an array of category titles (without the namespace prefix) if multiple titles are provided.Retrieves a list of categories whose titles match the specified prefix.
The prefix to match.
The maximum number of continuation cycles to perform (default: Infinity
).
Specify this if the prefix
is very generic and may produce too many results.
Optional
requestOptions: MwbotRequestConfigOptional HTTP request options.
A Promise that resolves to an array of matched category titles, excluding the namespace prefix.
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'
}
The prefixed title or the page ID of the category to enumerate.
Additional parameters for list=categorymembers
.
If any of these parameters conflict with the enforced ones, the enforced values take precedence.
Optional
requestOptions: MwbotRequestConfigOptional HTTP request options.
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.
Optional
requestOptions: MwbotRequestConfigOptional HTTP request options.
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.
The titles to check for existence.
Optional
loose?: booleanWhether to apply loose validation to the titles
input.
false
(default), the method throws if any input title fails validation
via validateTitle.true
, such titles are skipped (and exists()
will return null
for them).Optional
rejectProof?: booleanWhether 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.
Optional
requestOptions: MwbotRequestConfigOptional HTTP request options.
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'
}
The type of token to retrieve (e.g., csrf
).
Optional
additionalParams: 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.
Optional
requestOptions: MwbotRequestConfigOptional HTTP request options.
A Promise resolving to the retrieved token, or rejecting with an error.
Protected
getGets type of token to be used with an API action.
The API's action
parameter value.
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'
}
A single title or an array of titles to enumerate transclusions for.
Optional
additionalParams: ApiParamsAdditional parameters for prop=transcludedin
.
If any of these parameters conflict with the enforced ones, the enforced values take precedence.
Optional
requestOptions: MwbotRequestConfigOptional HTTP request options.
A Promise that resolves to:
transcludedin
objects if a single title is provided.'api'
format)
to an array of transcludedin
objects if multiple titles are provided.If
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'
}
A single title or an array of titles to enumerate transclusions for.
Optional
additionalParams: ApiParamsAdditional parameters for prop=transcludedin
.
If any of these parameters conflict with the enforced ones, the enforced values take precedence.
Optional
requestOptions: MwbotRequestConfigOptional HTTP request options.
A Promise that resolves to:
transcludedin
objects if a single title is provided.'api'
format)
to an array of transcludedin
objects if multiple titles are provided.If
allowSpecial
set to true
).titles
is an empty array. (emptyinput
)Protected
handleHandles data encoding for POST requests (calls handlePostMultipartFormData for multipart/form-data
).
The HTTP request options to modify.
A boolean indicating whether the parameters have a long field.
Protected
handleHandles POST requests with multipart/form-data
encoding.
params
into a FormData
object.params
contain an object with a stream
property.The HTTP request options to modify.
Optional
token: stringOptional token for authentication.
Checks whether the authenticated user has the specified user right(s).
The user right or list of rights to check.
Whether to require all rights (true
, default) or any one of them (false
).
true
if the user has the specified right(s) according to the given condition; otherwise false
.
Protected
initInitializes the configuration values with site and user data.
An array of wg
-keys that failed to be initialized.
Protected
isChecks whether the instance has been initialized for an anonymous user.
A boolean indicating whether the instance was initialized for an anonymous user.
Protected
loginLogs in to the wiki for which this instance has been initialized.
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 to the API, including multi-value fields.
The key(s) of the multi-value field(s) to split (e.g., titles
).
Optional
batchSize: numberOptional batch size (defaults to the apilimit
). Must be a positive integer less than
or equal to the apilimit
.
Optional
requestOptions: MwbotRequestConfigOptional HTTP request options.
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'
}
The title or ID of the page to move.
The destination title.
Additional parameters for action=move
.
If any of these parameters conflict with the enforced ones, the enforced values take precedence.
Optional
requestOptions: MwbotRequestConfigOptional HTTP request options.
A Promise resolving to the response.move
object, or rejecting with an error.
If:
anonymous
)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
}
The title of the page to edit.
The section title.
The content of the new section.
Optional
summary: stringAn optional edit summary. If not provided, the API generates one automatically.
Additional parameters for action=edit
.
If any of these parameters conflict with the enforced ones, the enforced values take precedence.
Optional
requestOptions: MwbotRequestConfigOptional HTTP request options.
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 to the API.
Optional
requestOptions: MwbotRequestConfigOptional HTTP request options.
A Promise resolving to the API response, or rejecting with an error.
Parses content via the API.
Enforced parameters:
{
action: 'parse',
format: 'json',
formatversion: '2'
}
Parameters to the API.
Optional
requestOptions: MwbotRequestConfigOptional HTTP request options.
A Promise resolving to the response.parse
object, or rejecting with an error.
Performs an HTTP POST request to the MediaWiki API.
Parameters to the API.
Optional
requestOptions: MwbotRequestConfigOptional HTTP request options.
A Promise resolving to the API response, or rejecting with an error.
Performs a POST request to the MediaWiki API using a CSRF token.
This is a shorthand method of postWithToken.
Parameters to the API.
Optional
requestOptions: MwbotRequestConfigOptional HTTP request options.
A Promise resolving to the API response, or rejecting with an error.
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'
});
The type of token to use (e.g., csrf
).
Parameters to the API.
Optional
requestOptions: MwbotRequestConfigOptional HTTP request options.
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'
}
The search string.
Additional parameters for list=prefixsearch
.
If any of these parameters conflict with the enforced ones, the enforced values take precedence.
The maximum number of continuation cycles to perform (default: Infinity
).
Specify this if the target
is very generic and may produce too many results.
Optional
requestOptions: MwbotRequestConfigOptional HTTP request options.
A Promise resolving to the result array in response.query.prefixsearch
, or rejecting with an error.
Protected
preprocessMassages parameters from the nice format we accept into a format suitable for the API.
(modified in-place)
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'
}
The title or ID of the page to protect.
The protection levels to apply, in one of the following forms:
'edit=sysop|move=sysop'
)action=level
strings (e.g., ['edit=sysop', 'move=sysop']
){ edit: 'sysop', move: 'sysop' }
)Additional parameters for action=protect
.
If any of these parameters conflict with the enforced ones, the enforced values take precedence.
Optional
requestOptions: MwbotRequestConfigOptional HTTP request options.
A Promise resolving to the response.protect
object, or rejecting with an error.
If:
anonymous
)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'
}
The titles to purge the cache for.
The maximum number of values is 50 or 500 (see also apilimit).
Additional parameters for action=purge
.
If any of these parameters conflict with the enforced ones, the enforced values take precedence.
Optional
requestOptions: MwbotRequestConfigOptional HTTP request options.
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
.
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.
The complete user-defined Axios request config.
A Promise that resolves to the raw Axios response.
Retrieves the latest revision content of a given title from the API.
The page title, either as a string or a Title instance.
Optional
requestOptions: MwbotRequestConfigOptional HTTP request options.
A Promise resolving to the revision information.
If:
title
fails validation via validateTitle.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.
An array of the page titles, either as strings or Title instances, or mixed.
Optional
requestOptions: MwbotRequestConfigOptional HTTP request options.
A Promise resolving to an array of revision information, with errors for invalid titles at their respective indexes.
Performs an HTTP request to the MediaWiki API.
Parameters to the API.
Optional
requestOptions: MwbotRequestConfig & ReadRequestConfigOptional HTTP request options.
A Promise resolving to the API response, or rejecting with an error.
Protected
retryAttempts to retry a failed request under the following conditions:
maxAttempts
).true
.initialError
.Note: MwbotRequestConfig.disableRetryAPI must be evaluated in the then
block of request, rather than here.
The error that triggered the retry attempt.
The number of attemps that have been made so far.
Request parameters. Since _request might have deleted them, they are re-injected as needed.
The original request options, using which we make another request.
The maximum number of attempts (including the first request). Default is 2 (one retry after failure).
The delay in seconds before retrying. Default is 10.
Optional
retryCallback: () => Promise<ApiResponse>A function to execute when attempting the retry. If not provided, _request is called on requestOptions
.
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'
}
The title or ID of the page to rollback.
The username whose consecutive edits to the page should be rolled back.
Additional parameters for action=rollback
.
If any of these parameters conflict with the enforced ones, the enforced values take precedence.
Optional
requestOptions: MwbotRequestConfigOptional HTTP request options.
A Promise resolving to the response.rollback
object, or rejecting with an error.
If:
anonymous
)rollback
user right. (nopermission
)titleOrId
, if not a number, fails validation via validateTitle.Saves the given content to a page.
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
}
The page title, either as a string or a Title instance.
The text content of the page.
Optional
summary: stringAn optional edit summary.
Additional parameters for action=edit
.
If any of these parameters conflict with the enforced ones, the enforced values take precedence.
Optional
requestOptions: MwbotRequestConfigOptional HTTP request options.
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'
}
The search query string to look for in page titles or content.
Additional parameters for list=search
.
If any of these parameters conflict with the enforced ones, the enforced values take precedence.
Optional
requestOptions: MwbotRequestConfigOptional HTTP request options.
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
).
Updates the bot options stored in the instance.
The new options to apply.
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.
The current instance for chaining.
Updates the default request options stored in the instance.
The options to apply.
Whether to merge options
with the existing ones (default: true
).
If false
, the current settings are cleared before applying options
.
The current instance for chaining.
Protected
showLogs warnings returned from the API to the console unless suppressed.
Warnings returned by the API, if any.
Unblocks a user.
Enforced parameters:
{
action: 'unblock',
id: userOrId, // If a number
user: userOrId, // If a string
format: 'json',
formatversion: '2'
}
The user name, IP address, user ID, or block ID to unblock.
Additional parameters for action=unblock
.
If any of these parameters conflict with the enforced ones, the enforced values take precedence.
Optional
requestOptions: MwbotRequestConfigOptional HTTP request options.
A Promise resolving to the response.unblock
object, or rejecting with an error.
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).
The title of the page to undelete.
Additional parameters for action=undelete
.
If any of these parameters conflict with the enforced ones, the enforced values take precedence.
Optional
requestOptions: MwbotRequestConfigOptional HTTP request options.
A Promise resolving to the response.undelete
object, or rejecting with an error.
If:
anonymous
)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'
}
The title or ID of the page to protect.
Additional parameters for action=protect
.
If any of these parameters conflict with the enforced ones, the enforced values take precedence.
Optional
requestOptions: MwbotRequestConfigOptional HTTP request options.
A Promise resolving to the response.protect
object, or rejecting with an error.
If:
anonymous
)protect
user right. (nopermission
)titleOrId
is not a number and fails title validation via validateTitle.Protected
usingChecks whether the client is configured to use OAuth (v1 or v2).
true
if either oauth1
or oauth2
credentials are set; otherwise, false
.
Protected
validateValidates 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.
The page title, either as a string or a Title instance.
Optional
allowAnonymous?: booleanWhether to allow anonymous users to proceed. Defaults to false
.
Optional
allowSpecial?: booleanWhether to allow special page inputs. Defaults to false
.
A validated Title instance.
If:
allowAnonymous
is false
. (anonymous
)typemismatch
)emptytitle
)interwikititle
)allowSpecial
is false
. (specialtitle
)Protected
Static
dieThrows or returns an api_mwbot: empty
error.
Optional
die: trueWhether to throw the error (default: true
). If false
, the error object
is returned instead of being thrown.
Optional
additionalInfo: stringOptional text to append after 'OK response but empty result'
.
A space is automatically prepended if provided; otherwise, a period is appended.
Optional
data: MwbotErrorDataOptional data object to set to the error.
Throws or returns an api_mwbot: empty
error.
Whether to throw the error (default: true
). If false
, the error object
is returned instead of being thrown.
Optional
additionalInfo: stringOptional text to append after 'OK response but empty result'
.
A space is automatically prepended if provided; otherwise, a period is appended.
Optional
data: MwbotErrorDataOptional data object to set to the error.
Protected
Static
dieThrows a fatal internal error if the request method is not "POST".
The request configuration object to check.
Static
getConstructs a standard API request parameter object for a given MediaWiki API action.
The returned object includes:
{
action: action,
format: 'json',
formatversion: '2'
}
The API action name (e.g., 'query', 'edit', etc.).
An object containing the action name along with fixed format
and formatversion
values.
Static
initInitializes 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...
});
Configuration object containing initialization settings and user credentials.
Custom request options applied to all HTTP requests issued by the new instance.
A Promise resolving to a new Mwbot
instance, or rejecting with an error.
Protected
Static
mapConverts legacy token types to csrf
.
Protected
Static
unrefReturns 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.
Optional
requestOptions: MwbotRequestConfigThe request options to check and clone if needed.
A safely cloneable MwbotRequestConfig
object with _cloned
set to true
.
Protected
Static
validateValidates user credentials and determines the authentication type.
The credentials object provided by the user.
Validated credentials.
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:
See also: