Pywikibot/Use on non-WMF wikis

From Wikibooks, open books for an open world
Jump to: navigation, search

The pywikibot may be used to do all kind of things that are important for the maintenance of a MediaWiki project. When this software is to be used outside of the Wikimedia projects, some configuration needs to be done.

Some non-Wikimedia projects, or families, are already supported. These can be found in the families folder [1] which can be downloaded.

Using the existing files as examples, it should be easy to adapt the bot to your own project.

{{:../Overview}} #REQUIRED

Instructions[edit] file[edit]

Open a text file. (Notepad.exe is a text file editor)

Save the text file as, in the main pywikipedia folder.

Add the following three required lines to

Code Explanation
mylang = 'xx'

xx is the code for the language code you are working on, "en" is English.[1]

usernames['sitename']['en'] = u'ExampleBot'[2]

Your file needs to specify the bot's username.

In this example, the user is working on English sitename, and has created a bot account with the username "ExampleBot".

family = 'sitename'

"Sitename" is the name of the site you're working on.

Sitename is the same name as the sitename in the above username line (usernames['sitename']['en'] = u'ExampleBot'.)

Now save again. file[edit]

Modify the existing files, or create a new file, in a text editor.

Save the file in the pywikipedia/families folder, with a name such as

Follow the sections below in order (each section makes the following section easier).

You must have the correct details as described in the sections below. Potential problems (this might help you in troubleshooting):

  • errors in the custom namespaces mean the family file won't work properly (though you'll get a warning when you login?)
  • an error in specifying index.php will prevent you logging in;
  • an error in specifying api.php seems likely to lead to problems, since the wiki is accessed via API.

The README-family.txt file in the families folder offers considerable documentation of the options available to family files. In fact, README-family.txt is a simple 'prototype' family file. You can just copy README-family.txt to, then open up the file in a text editor, and tweak it per the instructions below.


To check you have the correct path for your index.php, test which address redirects to your wiki's homepage - probably one of these:


(You may be able to guess from the address of a regular wiki page, but you need to check it - e.g. a wiki page may be but the correct path may be 'w/index.php' - this occurs at for example.)

Near the end of your file, you find this, for example. Modify or remove the "/w" as necessary:

     def path(self, code):
         return '/w/index.php' #The path of index.php, look at your wiki address. 
# This line may need to be changed to /wiki/index.php or /w/index.php, 
# depending on the folder where your mediawiki program is located.


The API.php file is found in the same place as index.php - but you can test by navigating to (say):



The correct address will give you an auto-generated MediaWiki API documentation page (the important thing is that it confirms you have the correct address).

For the '/w/api.php' case, api is defined like this:

     def apipath(self, code):

         return '/w/api.php' #The path of api.php

Custom Namespaces[edit]

Adding a custom namespace to a family file is not well documented in the README-family.txt file. The Uncyclopedia example below has some examples using custom namespaces, but the addition of these namespaces to your family file requires knowing the numerical ID of each namespace.

Finding the details you need: Start with the api url (which you found above) and add this string to the end:

?action=query&meta=siteinfo&siprop=general|namespaces|namespacealiases|statistics your address might look something like:|namespaces|namespacealiases|statistics

The resulting page will will list the information about your namespaces that you need for the family file, including the numerical ID.

Typically these numerical IDs start at 100, and each even number is a content space and the following odd number is the talk space for that content space. However, to get the exact list, directing your browser to your Wiki's API.php file, and calling certain commands, is ideal.

Also, note that README-family.txt lists two ways to provide translations of namespaces - either changing a specific language's namespace like so:

self.namespaces[2]['en'] = u'Wikiuser'
self.namespaces[3]['en'] = u'Wikiuser talk'

Or else changing an entire batch of languages in one go:

self.namespaces[4] = {
    '_default': [u'WIKINAME', self.namespaces[4]['_default']], # REQUIRED
    'de': 'Name des wiki',
    'es': 'Nombre del wiki',
    'fr': 'Nom du wiki',
    # ETC.

When adding custom namespaces, you do not have a choice - you must use the second style. The first method only works because self.namespaces[2]['en'] already exists. With custom namespaces, they do not, so you must use the second style, with curly braces and everything, even if you only have one language. For example, suppose you have a News namespace, and your Wiki only operates in English:

self.namespaces[100] = { 'en': 'News' }
self.namespaces[101] = { 'en': 'News talk' }

If you do not use this format, the family file will not work - and more importantly, the resulting error message will not help - it will ask you to create a file, even if that file already exists and works correctly.

Custom User Groups & Permissions[edit]

PyWikipedia assumes that the Wiki it is running on uses the standard, default user groups and that each group is assigned the usual permissions. This means that it may refuse to do things that its account would allow, and it may attempt to do things that its account is not allowed to do (these attempts will fail, so this is not a security issue).

The fact that it will attempt things it is not allowed to do is minor, but the inability to perform certain actions (e.g. deleting pages) without being in the "Sysop" group can be a sizable limitation. If the bot account has such permissions without being in the "Sysop" group (being part of some other, non-standard group), the only known work-around is the edit itself. This file controls most bot actions, and is found in the main folder PyWikipedia has been installed to.

In the _getUserData() function within, a pair of lines like this exists:

        if 'Sysop' in self._rights[index]:
            self._rights[index].extend(['delete', 'undelete', 'block', 'protect', 'import', 'deletedhistory', 'unwatchedpages'])

In version 2008-10-29T19:21:05.438703Z 6043, this is line 4705 and 4706, but that line number may be different, even very different, in other versions. Using the Find function of your text editor to find "def _getUserData(" (to find the function definition) is recommended.

In order to get the rights listed in the second line, the first line must be changed to recognize your custom user group (note: if your custom user-group has some, but not all of those rights, changing this will not give you those rights - it will simply let PyWikipedia attempt to exercise them if you direct it to. Doing so is strongly not recommended as the program's behavior in such a case is undefined). The exact name of the user group can be found by logging in manually as the bot, and viewing the HTML code of any Wiki page. Near the top, a line as follows should appear:

var wgUserGroups = [ ... ]

Where the ellipsis is replaced by a list of the groups that the bot is a member of. Choose the one that matches the custom user group that gives you the rights that you are attempting to exercise, and replace Sysop in the above code from with that name. This should activate those rights for PyWikipedia.

Running the PyWikipedia Bot[edit]

Refer to Using the python wikipediabot on how to run the bot.


Example: Mozilla wiki[edit]

The Mozilla Foundation's wiki,, is a very simple example because it is only available in one language.

This is the contents of families/ Hints for you to write your own family specification are underlined.

 # -*- coding: utf-8  -*-
import family
 # The official Mozilla Wiki. #Put a short project description here.
class Family(family.Family):
     def __init__(self):
         family.Family.__init__(self) = 'mozilla' # Set the family name; this should be the same as in the filename.
         self.langs = {
             'en': '', # Put the hostname here.

         # Translation used on all wikis for the different namespaces.
         # Most namespaces are inherited from family.Family.
         # Check the file (in main directory) to see the standard
         # namespace translations for each known language.
         # You only need to enter translations that differ from the default.
         self.namespaces[4] = {
             '_default': u'MozillaWiki', # Specify the project namespace here.
         self.namespaces[5] = {
             '_default': u'MozillaWiki talk', # Specify the talk page of the project namespace here. 
     def version(self, code):
         return "1.4.2"  # The MediaWiki version used. Not very important in most cases.
     def scriptpath(self, code):
         return '' # The relative path of index.php, api.php : look at your wiki address. 
# This line may need to be changed to /wiki or /w, 
# depending on the folder where your mediawiki program is located.
# Note: Do not _include_ index.php, etc.

Example: Starwars[edit]

This is the content of the Starwars wiki at wikia. The file is located at families/

Here explains how to configure the Pywikipedia bot to work at this site.

import family
class Family(family.Family):
   def __init__(self):
       family.Family.__init__(self) = 'starwars'
       self.langs = {
           'en': None,
       # Translation used on all wikis for the different namespaces.
       # Most namespaces are inherited from family.Family.
       # Check the file (in main directory) to see the standard
       # namespace translations for each known language.
       # You only need to enter translations that differ from the default.
       self.namespaces[4] = {
           '_default': u'Wookieepedia', # Specify the project namespace here. 
       self.namespaces[5] = {
           '_default': u'Wookieepedia talk', # Specify the talk page of the project namespace here. 
       # A few selected big languages for things that we do not want to loop over
       # all languages. This is only needed by the module, so
       # if you carefully avoid the options, you could get away without these
       # for another wiki family.
       self.languages_by_size = ['en']
   def hostname(self,code):
       return ''
   def path(self, code):
       return '/index.php'
   def version(self, code):
       return "1.9" # Which version of MediaWiki is used?

Example: Memory Alpha[edit] is the "family" definition of Memory Alpha,, a Star Trek wiki. This specification is a little bit more difficult because it has several languages.

 # -*- coding: utf-8  -*-
 import family
 # The Memory Alpha family, a set of StarTrek wikis.
 class Family(family.Family):
     def __init__(self):
         family.Family.__init__(self) = 'memoryalpha'
         self.langs = {  # All available languages are listed here.
             'de': None, # Because the hostname is the same for all languages,
             'en': None, # we don't specify it here, but below in the hostname()
             'nl': None, # function.
             'sv': None,
         # Most namespaces are inherited from family.Family.
         self.namespaces[4] = {
             '_default': u'Memory Alpha', # All languages use the same project namespace name.
         self.namespaces[5] = {
             '_default': u'Memory Alpha talk',
             'de': u'Memory Alpha Diskussion',
             'nl': u'Overleg Memory Alpha',
             'sv': u'Memory Alphadiskussion',
         # A few selected big languages for things that we do not want to loop over
         # all languages. This is only needed by the module, so
         # if you carefully avoid the options, you could get away without these
         # for another wiki family.
         self.biglangs = ['en', 'de'] # Not very important
     def hostname(self,code):
         return '' # The same for all languages
     def scriptpath(self, code):
         return '/%s' % code # The language code is included in the path
     def version(self, code):
         return "1.4"

Example: Uncyclopedia[edit]

The various Uncyclopedias are slightly more awkward as not all are hosted at the same domain or under the same name. Domain names and paths must be specified individually. Just over half are Wikia-hosted; exceptions include fi: hu: ja: ko: no: pt: sv: and zh-tw:. Many have their own registered domain names and many use custom namespaces.

The approaches which work for an Uncyclopædia or a Memory Alpha project typically can be adapted to other Wikia.

Note: There have been subsequent updates and changes, see or uncyclopedia:es:usuario:Chixpy/ for more current versions of the Uncyclopedia interwiki bot configuration. There are also unresolved issues in which some interwiki languages are not available from all Uncyclopedia projects or point to incorrect/inconsistent destinations; proceed with caution.

# -*- coding: utf-8  -*-
import family
# The Uncyclopaedia family, a satirical set of encyclopaedia wikis. (May 2006)
# Save this file to families/ in your pywikibot installation       
# The pywikipediabot itself is available for free download from          

class Family(family.Family):
    def __init__(self):
        family.Family.__init__(self) = 'uncyclopedia'
        self.langs = {
	    'ar': '',
            'ca': '',
            'da': '',
            'de': '',
            'el': '',
            'en': '',
            'es': '',
            'fi': '',
            'fr': '',
	    'he': '',
            'hu': '',
	    'it': '',
            'ja': '',
	    'la': '',
            'no': '',
            'pl': '',
            'pt': '',
            'ru': '',
	    'sv': '',
	    'zh': '',
            'zh-tw': '',
        # Most namespaces are inherited from family.Family.
        self.namespaces[1] = {
            '_default': u'Talk',
            'ar': u'نقاش',
	    'ca': u'Discussió',
	    'da': u'Diskussion',
            'de': u'Diskussion',
            'el': u'Συζήτηση',
            'en': u'Talk',
	    'es': u'Discusión',
	    'fi': u'Keskustelu',
            'fr': u'Discuter',
            'he': u'שיחה',
	    'it': u'Discussione',
	    'la': u'Disputatio',
	    'no': u'Diskusjon',
            'pl': u'Dyskusja',
            'pt': u'Discussão',
            'ru': u'Обсуждение',
	    'sv': u'Diskussion',
            'zh-tw': u'討論',

        self.namespaces[2] = {
            '_default': u'User',
            'ar': u'مستخدم',
	    'ca': u'Usuari',
            'da': u'Bruger',
            'de': u'Benutzer',
            'el': u'Χρήστης',
            'en': u'User',
	    'es': u'Usuario',
	    'fi': u'Käyttäjä',
            'fr': u'Utilisateur',
            'he': u'משתמש',
	    'it': u'Utente',
	    'la': u'Usor',
	    'no': u'Bruker',
            'pl': u'Użytkownik',
            'pt': u'Usuário',
            'ru': u'Участник',
	    'sv': u'Användare',
	    'zh-tw': u'用戶',

        self.namespaces[3] = {
            '_default': u'User talk',
            'ar': u'نقاش المستخدم',
	    'ca': u'Usuari Discussió',
            'da': u'Bruger diskussion',
            'de': u'Benutzer Diskussion',
            'el': u'Συζήτηση χρήστη',
            'en': u'User talk',
	    'es': u'Usuario Discusión',
	    'fi': u'Keskustelu käyttäjästä',
            'fr': u'Discussion Utilisateur',
            'he': u'שיחת משתמש',
	    'it': u'Discussioni utente',
	    'la': u'Disputatio Usoris',
	    'no': u'Brukerdiskusjon',
            'pl': u'Dyskusja użytkownika',
            'pt': u'Usuário Discussão',
            'ru': u'Обсуждение участника',
	    'sv': u'Användardiskussion',
	    'zh-tw': u'用戶討論',

        self.namespaces[4] = {
            '_default': u'Uncyclopedia',
	    'ar': u'ويكيبيديا',
	    'ca': u'Valenciclopèdia',
            'da': u'Spademanns Leksikon',
            'de': u'Uncyclopedia',
	    'el': u'Ανεγκυκλοπαίδεια',
            'en': u'Uncyclopedia',
            'es': u'Inciclopedia',
	    'fi': u'Hikipedia',
            'fr': u'Désencyclopédie',
            'he': u'איןציקלופדיה',
	    'it': u'Nonciclopedia',
	    'la': u'Uncapaedia',
	    'no': u'Wikipedia',
            'pl': u'Nonsensopedia',
            'pt': u'Desciclopédia',
	    'ru': u'Абсурдопедия',
	    'sv': u'Psykelopedia',
	    'zh': u'伪基百科',
	    'zh-tw': u'偽基百科',
        self.namespaces[5] = {
            '_default': u'Uncyclopedia talk',
	    'ar': u'نقاش ويكيبيديا',
	    'ca': u'Valenciclopèdia Discussió',
            'da': u'Spademanns Leksikon diskussion',
            'de': u'Uncyclopedia Diskussion',
	    'el': u'Ανεγκυκλοπαίδεια συζήτηση',
            'en': u'Uncyclopedia talk',
            'es': u'Inciclopedia Discusión',
	    'fi': u'Keskustelu Hikipediasta',
            'fr': u'Discussion Désencyclopédie',
            'he': u'שיחת איןציקלופדיה',
	    'it': u'Discussioni Nonciclopedia',
	    'la': u'Disputatio Uncapaediae',
	    'no': u'Wikipedia-diskusjon',
            'pl': u'Dyskusja Nonsensopedia',
            'pt': u'Desciclopédia Discussão',
	    'ru': u'Обсуждение Абсурдопедии',
	    'sv': u'Psykelopediadiskussion',
	    'zh': u'伪基百科 talk',
	    'zh-tw': u'偽基百科討論',

	self.namespaces[6] = {
	    '_default': u'Image',
            'ar': u'صورة',
	    'ca': u'Imatge',
	    'da': u'Billede',
	    'de': u'Bild',
	    'el': u'Εικόνα',
	    'es': u'Imagen',
	    'fi': u'Kuva',
	    'he': u'תמונה',
	    'it': u'Immagine',
	    'la': u'Imago',
	    'no': u'Bilde',
	    'pl': u'Grafika',
	    'pt': u'Imagem',
	    'ru': u'Изображение',
	    'sv': u'Bild',
	    'zh-tw': u'圖像',

	self.namespaces[7] = {
	    '_default': u'Image talk',
            'ar': u'نقاش الصورة',
	    'ca': u'Imatge Discussió',
	    'da': u'Billede diskussion',
	    'de': u'Bild Diskussion',
	    'el': u'Συζήτηση εικόνας',
	    'es': u'Imagen Discusión',
	    'fi': u'Keskustelu kuvasta',
	    'fr': u'Discussion Image',
	    'he': u'שיחת תמונה',
	    'it': u'Discussioni immagine',
	    'la': u'Disputatio Imaginis',
	    'no': u'Bildediskusjon',
	    'pl': u'Dyskusja grafiki',
	    'pt': u'Imagem Discussão',
	    'ru': u'Обсуждение изображения',
	    'sv': u'Bilddiskussion',
	    'zh-tw': u'圖像討論',

        self.namespaces[8] = {
            '_default': u'MediaWiki',
            'ar': u'ميدياويكي',
            'he': u'מדיה ויקי',
	    'zh-tw': u'媒體維基',

        self.namespaces[9] = {
            '_default': u'MediaWiki talk',
            'ar': u'نقاش ميدياويكي',
	    'ca': u'MediaWiki Discussió',
            'da': u'MediaWiki diskussion',
	    'de': u'MediaWiki Diskussion',
	    'es': u'MediaWiki Discusión',
	    'fr': u'Discussion MediaWiki',
            'he': u'שיחת מדיה ויקי',
	    'it': u'Discussioni MediaWiki',
	    'la': u'Disputatio MediaWiki',
	    'no': u'MediaWiki-diskusjon',
	    'pl': u'Dyskusja MediaWiki',
            'pt': u'MediaWiki Discussão',
            'ru': u'Обсуждение MediaWiki',
	    'sv': u'MediaWiki diskussion',
	    'zh-tw': u'媒體維基討論',

        # Custom namespace list for en: (and fi:)
        self.namespaces[100] = {
        self.namespaces[101] = {
	    '_default':u'Wilde talk',
	    'en':u'Wilde talk',
	    'pl':u'Dyskucja cytatów',
        self.namespaces[102] = {
        self.namespaces[103] = {'_default':u'UnNews talk'}
        self.namespaces[104] = {'_default':u'Undictionary'}
        self.namespaces[105] = {'_default':u'Undictionary talk'}
        self.namespaces[106] = {'_default':u'Game'}
        self.namespaces[107] = {'_default':u'Game talk'}
        self.namespaces[108] = {'_default':u'Babel'}
        self.namespaces[109] = {'_default':u'Babel talk'}
        self.namespaces[110] = {'_default':u'Forum'}
        self.namespaces[111] = {'_default':u'Forum talk'}

        # A few selected big languages for things that we do not want to loop over
        # all languages. This is only needed by the module, so
        # if you carefully avoid the options, you could get away without these
        # for another wiki family.
        self.languages_by_size = ['en', 'pl', 'de', 'es', 'ru', 'fr']

    def hostname(self,code):
        return self.langs[code]

    def scriptpath(self, code):
        if code=='fi':
           return '/hikipedia'
        if code in ['hu', 'ja', 'pt', 'sv', 'zh-tw']:
           return '/w'
        if code=='no':
           return ''
        return '/wiki'

    def version(self, code):
        return "1.7"



For a single-language site, the language specified does not matter as long as it is consistent between the and families/

Login failed. Wrong password?[edit]

Pywikipedia does not report anything more useful than success, failure, or host connection failure. If possible, try accessing the web server logs (apache uses access_log by default) and take a look at the URL strings.

You could also try running in 'very verbose' mode, ie: python -v -v . This will dump a lot of information, including possibly the html code from the server, so you can see exactly what is going on. (this option does however run the risk of possibly revealing some security sensitive info so be careful...)

Make sure your scriptpath, the relative path to your api.php and index.php files, is defined appropriately for your wiki in your families file:

def scriptpath(self, code):
    return '/wiki'

If this does not help, add a line like

  authenticate[''] = ('botName','botPassword')

to your file.

See the mozilla configuration for clues.

Mismatched interwiki configuration[edit]

In some projects (such as Uncyclopedia), each language operates as an independent wiki. This may mean that interwiki tables differ from one individual wiki to another within the same project. is built on the assumption that, if outbound interlanguage links are available at all from a language, the list of available link-destination languages and the destination URL for each will match perfectly across all wikis in the project.

This leads to some potential pitfalls:

  • If one language is missing outbound language interwiki support entirely, one must avoid giving pywikipediabot an account on that wiki (in in order to ensure that leaves that one language wiki untouched.
  • If one language is using a valid but incomplete interwiki table, running on that language wiki will create broken links. Unlike the case where one language is missing project-wide, there is no clean and easy workaround.
  • If a language in a project has been forked (not just mirrored), the interwiki for each individual language pair will point to only one of the multiple forks. Verify the wiki your bot is looking at is the same one that is being linked from the wiki you're editing - otherwise the bot will delete some valid links as "page does not exist".

Customisation of namespaces[edit]

Some projects use non-standard extensions to provide Special:Interwiki and Special:Namespaces lists; where available, these lists should be checked against the configuration files to detect any additional namespace customisations.

Short URL rewrites[edit]

If your site uses short URL rewrites, you may have to add "/api.php" to the blacklists, Otherwise, your bot scripts will not be able to access api.php.

Check your rewrite conditions in your apache conf file, and make an appropriate addition.

Bot & private wikis[edit]

Some wikis require logging in into mediawiki before being able to view any wikipage. If you have any such site, add to your custom family file :

def isPublic(self):
    return False

Fixing Permission Denied problems

Creating page [[Category:Help]] via API                                     
Unknown Error. API Error code:permissiondenied                              
Information:Permission denied 

Your wiki may require users to be part of a particular group in order to edit pages. If so, login to your wiki as an administrator and use Special:UserRights to put your bot into the proper group(s) to avoid API permission problems.

Bot & HTTP auth[edit]

Some sites will require password identication to access the HTML pages at the site. If you have any such site, add lines to your of the following form:

authenticate[''] = ('John','XXXXX') # where John is your login name, and XXXXX your password.

See also[edit]


  1. If you want to work with more than one language, choose the most common one, as you can override configured value in command line by -lang parameter.
  2. The 'u' in front of the username stands for Unicode. The 'u' is important if your username contains non-ASCII characters. If you are using ASCII characters only, you can remove the 'u' (if you have troubles loging in with your bot, otherwise you can leave the 'u' as is).