Options
All
  • Public
  • Public/Protected
  • All
Menu

Class mwn

Hierarchy

  • mwn

Index

Constructors

constructor

  • Constructs a new bot instance It is advised to create one bot instance for every API to use A bot instance has its own state (e.g. tokens) that is necessary for some operations

    Parameters

    Returns mwn

Properties

category

category: MwnCategoryStatic = MwnCategoryFactory(this)

Category class associated with the bot instance

cookieJar

cookieJar: CookieJar = new tough.CookieJar()

Cookie jar for the bot instance - holds session and login cookies

csrfToken

csrfToken: string = "%notoken%"

Bot instance's edit token. Initially set as an invalid token string so that the badtoken handling logic is invoked if the token is not set before a query is sent.

date

date: MwnDateStatic = MwnDateFactory(this)

Date class associated with the bot instance

file

file: MwnFileStatic = MwnFileFactory(this)

File class associated with the bot instance

hasApiHighLimit

hasApiHighLimit: boolean = false

loggedIn

loggedIn: boolean = false

Bot instance is logged in or not

oauth

oauth: OAuth

options

options: MwnOptions

Actual, current options of the bot instance Mix of the default options, the custom options and later changes

page

page: MwnPageStatic = MwnPageFactory(this)

Page class associated with the bot instance

requestOptions

requestOptions: RawRequestParams = mergeDeep1({responseType: 'json'}, mwn.requestDefaults)

Request options for the axios library. Change the defaults using setRequestOptions()

sleep

sleep: sleep = sleep

Promisified version of setTimeout

param

of sleep in milliseconds

state

state: any

Bot instance Login State Is received from the MW Login API and contains token, userid, etc.

stream

stream: MwnStreamStatic = MwnStreamFactory(this)

Stream class associated with the bot instance

title

title: MwnTitleStatic = MwnTitleFactory()

Title class associated with the bot instance

user

user: MwnUserStatic = MwnUserFactory(this)

User class associated with the bot instance

usingOAuth

usingOAuth: boolean

wikitext

wikitext: MwnWikitextStatic = MwnWikitextFactory(this)

Wikitext class associated with the bot instance

Static Error

Error: MwnError = MwnError

Static link

link: link = link

Static log

log: log = log

Static setLoggingConfig

setLoggingConfig: updateLoggingConfig = updateLoggingConfig

Static table

table: table = table

Static template

template: template = template

Static util

util: { escapeHtml: escapeHtml; escapeRegExp: escapeRegExp; isIPAddress: isIPAddress; isIPv4Address: isIPv4Address; isIPv6Address: isIPv6Address; rawurlencode: rawurlencode; wikiUrlencode: wikiUrlencode } = util

Type declaration

Methods

Private _usingOAuth

  • _usingOAuth(): boolean

askQuery

  • askQuery(query: string, apiUrl: string, customRequestOptions?: RawRequestParams): Promise<any>
  • Execute an ASK Query On a wiki that supports them, like semantic-mediawiki

    Parameters

    Returns Promise<any>

batchOperation

  • batchOperation<T>(list: T[], worker: (item: T, index: number) => Promise<any>, concurrency?: number, retries?: number): Promise<{ failures: {} }>
  • Execute an asynchronous function on a large number of pages (or other arbitrary items). Designed for working with promises.

    Type parameters

    • T

    Parameters

    • list: T[]

      list of items to execute actions upon. The array would usually be of page names (strings).

    • worker: (item: T, index: number) => Promise<any>

      function to execute upon each item in the list. Must return a promise.

        • (item: T, index: number): Promise<any>
        • Parameters

          • item: T
          • index: number

          Returns Promise<any>

    • Default value concurrency: number = 5
    • Default value retries: number = 0

    Returns Promise<{ failures: {} }>

    • resolved when all API calls have finished, with object { failures: [ ...list of failed items... ] }

continuedQuery

  • Send an API query that automatically continues till the limit is reached.

    Parameters

    • Optional query: ApiParams

      The API query

    • Default value limit: number = 10

    Returns Promise<ApiResponse[]>

    • resolved with an array of responses of individual calls.

continuedQueryGen

  • Generator to iterate through API response continuations.

    generator
    yields

    {Object} a single page of the response

    Parameters

    • Optional query: ApiParams
    • Default value limit: number = Infinity

    Returns AsyncGenerator<ApiResponse>

create

  • create(title: string, content: string, summary?: string, options?: ApiEditPageParams): Promise<ApiEditResponse>
  • Creates a new pages. Does not edit existing ones

    Parameters

    • title: string
    • content: string
    • Optional summary: string
    • Optional options: ApiEditPageParams

    Returns Promise<ApiEditResponse>

createAccount

  • createAccount(username: string, password: string): Promise<any>
  • Create an account. Only works on wikis without extensions like ConfirmEdit enabled (hence doesn't work on WMF wikis).

    Parameters

    • username: string
    • password: string

    Returns Promise<any>

delete

  • delete(title: string | number, summary: string, options?: ApiDeleteParams): Promise<ApiResponse>
  • Deletes a page

    Parameters

    • title: string | number

      title or pageid (as number)

    • summary: string
    • Optional options: ApiDeleteParams

    Returns Promise<ApiResponse>

disableEmergencyShutoff

  • disableEmergencyShutoff(): void
  • Disable emergency shutoff detection. Use this only if it was ever enabled.

    Returns void

download

  • download(file: string | number, localname: string): Promise<void>
  • Download an image from the wiki. If you're downloading multiple images, then for better efficiency, you may want to query the API for the urls of all images in one request, and follow that with running downloadFromUrl for each one.

    Parameters

    • file: string | number

      title or page ID

    • localname: string

    Returns Promise<void>

downloadFromUrl

  • downloadFromUrl(url: string, localname: string): Promise<void>
  • Download an image from a URL.

    Parameters

    • url: string
    • localname: string

    Returns Promise<void>

edit

  • edit(title: string | number, transform: (rev: { content: string; timestamp: string }) => string | ApiEditPageParams, editConfig?: editConfigType): Promise<ApiEditResponse>
  • config

    conflictRetries - maximum number of times to retry edit after encountering edit conflicts.

    config

    suppressNochangeWarning - don't show the warning when no change is actually made to the page on an successful edit

    config

    exclusionRegex - don't edit if the page text matches this regex. Used for bot per-page exclusion compliance.

    Parameters

    • title: string | number

      Page title or page ID or MwnTitle object

    • transform: (rev: { content: string; timestamp: string }) => string | ApiEditPageParams

      Callback that prepares the edit. It takes one argument that is an { content: 'string: page content', timestamp: 'string: time of last edit' } object. This function should return an object with edit API parameters or just the updated text, or a promise providing one of those.

        • (rev: { content: string; timestamp: string }): string | ApiEditPageParams
        • Parameters

          • rev: { content: string; timestamp: string }
            • content: string
            • timestamp: string

          Returns string | ApiEditPageParams

    • Optional editConfig: editConfigType

    Returns Promise<ApiEditResponse>

    Edit API response

enableEmergencyShutoff

  • enableEmergencyShutoff(shutoffOptions?: { condition?: RegExp | ((text: string) => boolean); intervalDuration?: number; onShutoff?: (text: string) => void; page?: string }): void
  • Enable bot emergency shutoff

    Parameters

    • Optional shutoffOptions: { condition?: RegExp | ((text: string) => boolean); intervalDuration?: number; onShutoff?: (text: string) => void; page?: string }
      • Optional condition?: RegExp | ((text: string) => boolean)
      • Optional intervalDuration?: number
      • Optional onShutoff?: (text: string) => void
          • (text: string): void
          • Parameters

            • text: string

            Returns void

      • Optional page?: string

    Returns void

getCsrfToken

  • getCsrfToken(): Promise<string>
  • Gets an edit token (also used for most other actions such as moving and deleting) This is only compatible with MW >= 1.24

    Returns Promise<string>

getMessages

  • getMessages(messages: string | string[], options?: ApiQueryAllMessagesParams): Promise<Record<string, string>>
  • Fetch MediaWiki messages

    Parameters

    • messages: string | string[]
    • Default value options: ApiQueryAllMessagesParams = {}

    Returns Promise<Record<string, string>>

getPagesByPrefix

  • getPagesByPrefix(prefix: string, otherParams?: ApiQueryAllPagesParams): Promise<string[]>
  • Get pages with names beginning with a given prefix

    Parameters

    • prefix: string
    • Optional otherParams: ApiQueryAllPagesParams

    Returns Promise<string[]>

    • array of page titles (upto 5000 or 500)

getPagesInCategory

  • getPagesInCategory(category: string, otherParams?: ApiQueryCategoryMembersParams): Promise<string[]>
  • Get pages in a category

    Parameters

    • category: string

      name of category, with or without namespace prefix

    • Optional otherParams: ApiQueryCategoryMembersParams

    Returns Promise<string[]>

getServerTime

  • getServerTime(): Promise<string>
  • Get the wiki's server time

    Returns Promise<string>

getSiteInfo

  • getSiteInfo(): Promise<void>
  • Gets namespace-related information for use in title nested class. This need not be used if login() is being used. This is for cases where mwn needs to be used without logging in.

    Returns Promise<void>

getTokenType

  • getTokenType(action: string): Promise<string>
  • Get type of token to be used with an API action

    Parameters

    • action: string

      API action parameter

    Returns Promise<string>

getTokens

  • getTokens(): Promise<void>
  • Get tokens and saves them in this.state

    Returns Promise<void>

getTokensAndSiteInfo

  • getTokensAndSiteInfo(): Promise<void>
  • Get the tokens and siteinfo in one request

    Returns Promise<void>

initOAuth

  • initOAuth(): void

login

  • login(loginOptions?: { apiUrl?: string; password?: string; username?: string }): Promise<ApiResponse>

loginGetToken

  • loginGetToken(loginOptions?: MwnOptions): Promise<void>
  • Login and fetch edit tokens. Deprecated in favour of login(), which also fetches tokens from mwn v0.10

    deprecated

    Parameters

    Returns Promise<void>

logout

  • logout(): Promise<void>
  • Log out of the account. Flushes the cookie jar and clears the saved tokens. Should not be used if authenticating via OAuth.

    Returns Promise<void>

massQuery

  • Function for using API action=query with more than 50/500 items in multi- input fields.

    Multi-value fields in the query API take multiple inputs as an array (internally converted to a pipe-delimted string) but with a limit of 500 (or 50 for users without apihighlimits). Example: the fields titles, pageids and revids in any query, ususers in list=users.

    This function allows you to send a query as if this limit didn't exist. The array given to the multi-input field is split into batches and individual queries are sent sequentially for each batch. A promise is returned finally resolved with the array of responses of each API call.

    The API calls are made via POST instead of GET to avoid potential 414 (URI too long) errors.

    Parameters

    • Optional query: ApiParams

      the query object, the multi-input field should be an array

    • Default value batchFieldName: string = "titles"

    Returns Promise<ApiResponse[]>

    • promise resolved when all the API queries have settled, with the array of responses.

massQueryGen

  • massQueryGen(query: ApiParams, batchFieldName?: string, batchSize?: number): AsyncGenerator<ApiResponse>
  • Generator version of massQuery(). Iterate through pages of API results.

    Parameters

    • query: ApiParams
    • Default value batchFieldName: string = "titles"
    • Optional batchSize: number

    Returns AsyncGenerator<ApiResponse>

move

  • move(fromtitle: string, totitle: string, summary: string, options?: ApiMoveParams): Promise<ApiResponse>
  • Moves a new page

    Parameters

    • fromtitle: string
    • totitle: string
    • summary: string
    • Optional options: ApiMoveParams

    Returns Promise<ApiResponse>

newSection

  • newSection(title: string | number, header: string, message: string, additionalParams?: ApiEditPageParams): Promise<ApiEditResponse>
  • Post a new section to the page.

    Parameters

    • title: string | number

      title or pageid (as number)

    • header: string
    • message: string

      wikitext message

    • Optional additionalParams: ApiEditPageParams

    Returns Promise<ApiEditResponse>

oresQueryRevisions

  • oresQueryRevisions(endpointUrl: string, models: string[], revisions: string[] | number[] | string | number): Promise<any>
  • Gets ORES predictions from revision IDs

    Parameters

    • endpointUrl: string
    • models: string[]
    • revisions: string[] | number[] | string | number

      ID(s)

    Returns Promise<any>

parseJsonPage

  • parseJsonPage(title: string): Promise<any>
  • Fetch and parse a JSON wikipage

    Parameters

    • title: string

      page title

    Returns Promise<any>

    parsed JSON object

parseTitle

  • parseTitle(title: string, additionalParams?: ApiParseParams): Promise<string>
  • Parse a given page. Convenience method for 'action=parse'.

    Parameters

    • title: string

      Title of the page to parse

    • Optional additionalParams: ApiParseParams

      Parameters object to set custom settings, e.g. redirects, sectionpreview. prop should not be overridden.

    Returns Promise<string>

parseWikitext

  • parseWikitext(content: string, additionalParams?: ApiParseParams): Promise<string>
  • Parse wikitext. Convenience method for 'action=parse'.

    Parameters

    • content: string

      Content to parse.

    • Optional additionalParams: ApiParseParams

      Parameters object to set custom settings, e.g. redirects, sectionpreview. prop should not be overridden.

    Returns Promise<string>

purge

  • purge(titles: string[] | string | number[] | number, options?: ApiPurgeParams): Promise<ApiResponse>
  • Purge one or more pages (max 500 for bots, 50 for others)

    Parameters

    • titles: string[] | string | number[] | number

      page titles or page ids

    • Optional options: ApiPurgeParams

    Returns Promise<ApiResponse>

queryAuthors

  • queryAuthors(title: string): Promise<{ totalBytes: number; users: { bytes: number; id: number; name: string; percent: number }[] }>
  • Query the top contributors to the article using the WikiWho API. This API has a throttling of 2000 requests a day. Supported for EN, DE, ES, EU, TR Wikipedias only

    see

    https://api.wikiwho.net/

    Parameters

    • title: string

    Returns Promise<{ totalBytes: number; users: { bytes: number; id: number; name: string; percent: number }[] }>

rawRequest

read

  • Reads the content and and meta-data of one (or many) pages. Content from the "main" slot is copied over to every revision object for easier referencing (pg.revisions[0].content can be used instead of pg.revisions[0].slots.main.content).

    Parameters

    • titles: string | number | MwnTitle

      for multiple pages use an array

    • Optional options: ApiParams

    Returns Promise<ApiPage>

  • Parameters

    Returns Promise<ApiPage[]>

readGen

request

rollback

  • rollback(page: string | number, user: string, params?: ApiRollbackParams): Promise<ApiResponse>
  • Convenience method for action=rollback.

    Parameters

    • page: string | number

      page title or page id as number or MwnTitle object

    • user: string
    • Optional params: ApiRollbackParams

    Returns Promise<ApiResponse>

save

  • save(title: string | number, content: string, summary?: string, options?: ApiEditPageParams): Promise<ApiEditResponse>
  • Edit a page without loading it first. Straightforward version of edit. No edit conflict detection.

    Parameters

    • title: string | number

      title or pageid (as number)

    • content: string
    • Optional summary: string
    • Optional options: ApiEditPageParams

    Returns Promise<ApiEditResponse>

saveOption

  • saveOption(option: string, value: string): Promise<ApiResponse>

saveOptions

  • saveOptions(options: Record<string, string>): Promise<ApiResponse>

search

  • search(searchTerm: string, limit: number, props: ("size" | "timestamp" | "wordcount" | "snippet" | "redirectitle" | "sectiontitle" | "redirectsnippet" | "titlesnippet" | "sectionsnippet" | "categorysnippet")[], otherParams?: ApiQuerySearchParams): Promise<ApiResponse>
  • Search the wiki.

    Parameters

    • searchTerm: string
    • limit: number
    • props: ("size" | "timestamp" | "wordcount" | "snippet" | "redirectitle" | "sectiontitle" | "redirectsnippet" | "titlesnippet" | "sectionsnippet" | "categorysnippet")[]
    • Optional otherParams: ApiQuerySearchParams

    Returns Promise<ApiResponse>

seriesBatchOperation

  • seriesBatchOperation<T>(list: T[], worker: (item: T, index: number) => Promise<any>, delay?: number, retries?: number): Promise<{ failures: {} }>
  • Execute an asynchronous function on a number of pages (or other arbitrary items) sequentially, with a time delay between actions. Using this with delay=0 is same as using batchOperation with batchSize=1 Use of seriesBatchOperation() is not recommended for MediaWiki API actions. Use the normal mwn methods with async-await in a for loop. The request() method has the better retry functionality (only network errors are retried, other errors are unlikely to go away on retries).

    Type parameters

    • T

    Parameters

    • list: T[]
    • worker: (item: T, index: number) => Promise<any>

      must return a promise

        • (item: T, index: number): Promise<any>
        • Parameters

          • item: T
          • index: number

          Returns Promise<any>

    • Default value delay: number = 5000
    • Default value retries: number = 0

    Returns Promise<{ failures: {} }>

    • resolved when all API calls have finished, with object { failures: { failed item: error, failed item2: error2, ... } }

setApiUrl

  • setApiUrl(apiUrl: string): void
  • Sets the API URL for MediaWiki requests This can be uses instead of a login, if no actions are used that require login.

    Parameters

    Returns void

setDefaultParams

  • Set the default parameters to be sent in API calls.

    Parameters

    Returns void

setOptions

setRequestOptions

setUserAgent

  • setUserAgent(userAgent: string): void

sparqlQuery

  • sparqlQuery(query: string, endpointUrl: string, customRequestOptions?: RawRequestParams): Promise<any>
  • Executes a SPARQL Query On a wiki that supports them, like wikidata

    Parameters

    • query: string
    • endpointUrl: string
    • Optional customRequestOptions: RawRequestParams

    Returns Promise<any>

undelete

  • undelete(title: string, summary: string, options?: ApiUndeleteParams): Promise<ApiResponse>
  • Undeletes a page. Note: all deleted revisions of the page will be restored.

    Parameters

    • title: string
    • summary: string
    • Optional options: ApiUndeleteParams

    Returns Promise<ApiResponse>

upload

  • upload(filepath: string, title: string, text: string, options?: ApiUploadParams): Promise<ApiResponse>
  • Upload an image from a the local disk to the wiki. If a file with the same name exists, it will be over-written.

    Parameters

    • filepath: string
    • title: string
    • text: string
    • Optional options: ApiUploadParams

    Returns Promise<ApiResponse>

uploadFromUrl

  • uploadFromUrl(url: string, title: string, text: string, options?: ApiUploadParams): Promise<ApiResponse>
  • Upload an image from a web URL to the wiki If a file with the same name exists, it will be over-written, to disable this behaviour, use ignorewarning: false in options.

    Parameters

    • url: string
    • title: string
    • text: string
    • Optional options: ApiUploadParams

    Returns Promise<ApiResponse>

userinfo

  • userinfo(options?: ApiQueryUserInfoParams): Promise<any>
  • Get basic info about the logged-in user

    Parameters

    • Default value options: ApiQueryUserInfoParams = {}

    Returns Promise<any>

Static init

  • Initialize a bot object. Login to the wiki and fetch editing tokens. If OAuth credentials are provided, they will be used over BotPassword credentials. Also fetches the site data needed for parsing and constructing title objects.

    Parameters

    • config: MwnOptions

      Bot configurations, including apiUrl, and either the username and password or the OAuth credentials

    Returns Promise<mwn>

    bot object

Object literals

Readonly defaultOptions

defaultOptions: object

Default options. Should be immutable

apiUrl

apiUrl: null = null

maxRetries

maxRetries: number = 3

password

password: null = null

retryPause

retryPause: number = 5000

silent

silent: false = false

suppressAPIWarnings

suppressAPIWarnings: false = false

userAgent

userAgent: string = "mwn"

username

username: null = null

OAuthCredentials

OAuthCredentials: object

accessSecret

accessSecret: null = null

accessToken

accessToken: null = null

consumerSecret

consumerSecret: null = null

consumerToken

consumerToken: null = null

defaultParams

defaultParams: object

format

format: string = "json"

formatversion

formatversion: string = "2"

maxlag

maxlag: number = 5

editConfig

editConfig: object

conflictRetries

conflictRetries: number = 2

exclusionRegex

exclusionRegex: null = null

suppressNochangeWarning

suppressNochangeWarning: false = false

shutoff

shutoff: object

condition

condition: RegExp = /^\s*$/

intervalDuration

intervalDuration: number = 10000

page

page: null = null

onShutoff

  • onShutoff(): void

shutoff

shutoff: object

Emergency shutoff config

hook

hook: null = null

state

state: false = false

Static requestDefaults

requestDefaults: object

httpAgent

httpAgent: Agent = new http.Agent({ keepAlive: true })

httpsAgent

httpsAgent: Agent = new https.Agent({ keepAlive: true })

timeout

timeout: number = 60000

headers

headers: object

Accept-Encoding

Accept-Encoding: string = "gzip"

Generated using TypeDoc