MediaWiki API client written in node.js
- At minimum Node.js at the maintenance version
npm install nodemw
Or Download the latest stable version via GitHub.
git clone https://github.com/macbre/nodemw.git
Note
To run integration tests against production Wikipedia and WikiData servers, you first need to reate your own bot account at https://test.wikipedia.org/wiki/Special:BotPasswords.
And then set the TEST_BOT_USERNAME and TEST_BOT_PASSWORD env variables when running tests.
Otherwise, we're getting rate-limited (HTTP 429 responses).
CI checks are already set up.
- HTTP requests are stored in the queue and performed in parallel with limited number of "threads" (i.e. there's no risk of flooding the server)
- articles creation / edit / move / delete
- file uploads (using given content or via provided URL)
- Special:Log processing
- listing articles in categories
- and much more
- getting claims from WikiData
- Over 25k edits on Poznań Wiki as Pyrabot - scripts repository
An example script can be found in /examples directory.
cd examples
node pagesInCategory.jsYou can enter debug mode by setting DEBUG enviromental variable:
DEBUG=1 node examples/pagesInCategory.js
You can enter dry-run mode (all "write" operations like edits and uploads will be disabled) by setting DRY_RUN environmental variable (or dryRun entry in the config):
DRY_RUN=1 node examples/pagesInCategory.js
npm testvar bot = require("nodemw"); // pass configuration object var client = new bot({ protocol: "https", // Wikipedia now enforces HTTPS server: "en.wikipedia.org", // host name of MediaWiki-powered site path: "/w", // path to api.php script debug: false, // is more verbose when set to true }); client.getArticle("foo", function (err, data) { // error handling if (err) { console.error(err); return; } // ... });
nodemw can use config files as well as objects directly provided to bot object constructor.
// read config from external file var client = new bot("config.js");
Config file is a JSON-encoded object with the following fields (see /examples/config-DIST.js file):
{ "protocol": "https", // protocol to use (defaults to 'https') "server": "en.wikipedia.org", // host name of MediaWiki-powered site "port": 443, // port to use (optional, defaults to protocol default) "path": "/w", // path to api.php script "debug": false, // is more verbose when set to true "username": "foo", // account to be used when logIn is called (optional) "password": "bar", // password to be used when logIn is called (optional) "domain" : "auth.bar.net", // domain to be used when logIn is called (optional) "userAgent": "Custom UA", // define custom bot's user agent "concurrency": 5, // how many API requests can be run in parallel (defaults to 3) "proxy": "http://proxy:8080", // HTTP proxy to use (optional) "referer": "https://example.com", // referer header to send (optional) "dryRun": false // dry-run mode - disables write operations (optional) }
nodemw allows you make direct calls to MediaWiki API (example querying Semantic MediaWiki API):
var bot = require("nodemw"), client = new bot({ server: "semantic-mediawiki.org", path: "/w", }), params = { action: "ask", query: "[[Modification date::+]]|?Modification date|sort=Modification date|order=desc", }; client.api.call( params /* api.php parameters */, function ( err /* Error instance or null */, info /* processed query result */, next /* more results? */, data /* raw data */, ) { console.log(data && data.query && data.query.results); }, );
The last parameter of each function in nodemw API is a callback which will be fired when the requested action is done.
Callbacks use node.js style - err is always passed as the first argument.
Log-in using given credentials - read more
You can also call
logIn(callback)without arguments to use credentials from config file.
Gets the list of all categories on a wiki (optionally filtered by prefix)
Gets the list of all categories on a wiki
Gets the list of all pages from the main namespace (excludes redirects) - read more
Gets the list of pages in a given category - read more
By providing
Category:Fooastitlesargument tobot.purgeyou can purge all pages in a given category (available since MW 1.21)
Gets the list of pages in a given namespace - read more
Gets the list of pages by a given prefix - read more
Gets the list of pages that transclude the given pages - read more
Performs a search and returns matching pages
Performs a search with specified sort order
Gets article content and redirect info - read more
Gets all revisions of a given article - read more
Gets all categories a given article is in - read more
Gets all info of a given article - read more
Gets list of all pages that are used on a given page
Returns XML with preprocessed wikitext (expanded templates) - read more
Returns parsed wikitext (HTML output) - read more
Creates / edits an article (and mark the edit as minor if minor is set to true) - read more
Adds given content to the end of the page - read more
Adds given content to the beginning of the page - read more
Add a Flow topic - read more
Moves (aka renames) given article - read more
Deletes an article - read more
Undeletes an article (restores all revisions) - read more
Purge a given list of articles (titles or page IDs can be provided) - read more
By providing
Category:Fooastitlesargument you can purge all pages in a given category (available since MW 1.21)
Send an email to an user - read more
Returns token required for a number of MediaWiki API operations - read more / for MW 1.24+
Uploads a given raw content as a File:[filename] - read more
Uploads a given external resource as a File:[filename]
Uploads a given video as a File:[filename] (Wikia-specific API)
Gets information about current bot's user (including rights and rate limits) - read more
Gets information about a specific user (including rights, current block, groups) - read more
Gets information about specific users (including rights, current block, groups) - read more
Create account using given credentials - read more
Send an email to an user - read more
Gets information about current bot's user (including rights and rate limits) - read more
Gets information about a specific user (including rights, current block, groups) - read more
Gets information about specific users (including rights, current block, groups) - read more
Moves (aka renames) given article - read more
Gets list of all images on a wiki
Gets list of all articles using given image
Get list of all images that are used on a given page - read more
Gets metadata (including uploader, size, dimensions and EXIF data) of given image
Get entries form Special:Log - read more
Get log entries of a specific type from Special:Log
Returns XML with preprocessed wikitext - read more
Returns parsed wikitext - read more
Makes a GET request to provided resource and returns its content.
Gets list of all images on a wiki
Gets list of all articles using given image
Get list of all images that are used on a given page - read more
Gets metadata (including uploader, size, dimensions and EXIF data) of given image
Returns entries from recent changes (starting from a given point)
Returns site information entries - read more
Returns site statistics (number of articles, edits etc) - read more
Returns entries from QueryPage-based special pages
Returns the version of MediaWiki given site uses - read more
Returns token required for a number of MediaWiki API operations - read more / for MW 1.24+
Uploads a given raw content as a File:[filename] - read more
Uploads a given external resource as a File:[filename]
Uploads a given video as a File:[filename] (Wikia-specific API)
Gets a value of a given template parameter from article's preparsed content (see expandTemplates)
Gets all external links used in article
Gets all articles that links to given article
Performs a search
Performs a search limited to page titles
Returns site information entries - read more
Returns site statistics (number of articles, edits etc) - read more
Returns entries from QueryPage-based special pages
Gets contributions of a given user
Returns entries from recent changes (starting from a given point)
Send an email to an user - read more
Log a message using the bot's logger
Log a JSON object to the console
Log an error message
Returns a random string (useful for generating unique edit summaries or tokens)
Gets config entry value (returns def value if not found)
Sets config entry value
Returns a diff colored using ANSI colors (powered by diff)
Makes a GET request to provided resource and returns its content. Optional encoding parameter (defaults to 'utf-8', use 'binary' for binary data)
Gets a value of a given template parameter from article's preparsed content (see expandTemplates)
Wikia-specific bot methods
They're grouped in
bot.wikia"namespace".
Get wiki-specific settings (like ThemeDesigner colors and hubs).
Get information (avatar, number of edits) about a given user
Get information (avatar, number of edits) about a given set of users (by their IDs)
This API is Promise-based, use await keyword.
Examples:
const wikidata = require("nodemw/lib/wikidata"); const client = new wikidata(); // Where is Saksun, Faroe Islands located? const geo = await client.getEntityClaim( "Q928875" /* Saksun */, "P625" /* place location */, ); // will give you the geolocation of the place expect(geo[0].mainsnak.datavalue.value).toMatchObject({ latitude: 62.248888888889, longitude: -7.1758333333333, }); // When was Albert Einstein born? const res = await client.getArticleClaims("Albert Einstein"); const dateOfBirth = res.P569[0].mainsnak.datavalue.value; expect(dateOfBirth.time).toMatch(/1879-03-14/); const dateOfDeath = res.P570[0].mainsnak.datavalue.value; expect(dateOfDeath.time).toMatch(/1955-04-18/); // interwiki links for a given artlice const links = await client.getArticleSitelinks("Albert Einstein"); console.log(links.enwiki); // {site: "enwiki", title: "Albert Einstein", badges: ["Q17437798"]}