Fandom



apanel.py Bearbeiten

Dieses Skript ist eine Actionpanel wannabe. Es zeigt vorher ausgewählte Seiten an und lässt sie verschieben, weiterleiten, kategorisieren, etc.

Die Auswahl der Seiten erfolgt mit den üblichen Verdächtigen: -cat, -usercontribs, -search, -titleregex (!), usw. Ein minimaler Aufruf ist von der Form python apanel.py SUCHTERM; dies ist dasselbe wie python apanel.py -search:SUCHTERM. Ohne irgendeine Auswahl wird python apanel.py -new:24 aufgerufen (die 24 neuesten Fragen).

Es wird jeweils eine Seite mit ihrem kompletten Inhalt angezeigt, mitsamt einem Interface für verschiedene Funktionen. Wird eine Funktion erfolgreich ausgeführt, dann kommt die nächste Seite dran. Die einzigen Ausnahmen sind das Öffnen im Browser und das Verschieben. Möchte man also gleichzeitig eine Seite verschieben und bearbeiten, dann sollte man das Verschieben zuerst nehmen.

Weitere Parameter
  • -withredirects
    • verhindert, dass Weiterleitungen ausgelassen werden
  • -safe
    • fügt sicherheitshalbere Nachfragen hinzu
  • -sysop
    • Seiten als Admin bearbeiten
  • -static:ZIEL
    • Beim Verschieben und Weiterleiten wird normalerweise die letzte Eingabe erneut als Default vorgeschlagen. Mit diesem Parameter wird stattdessen immer das angegebene ZIEL vorgeschlagen.
  • -summary:ZUSAMMENFASSUNG
    • jetzt mit eigener Zusammenfassung!
undokumentiert
  • Gibt man als Verschiebungs-/Redirectziel/Kategorie "abort" ein, bricht man ab und kommt wieder ins Auswahlmenü
  • der Editor fürs Bearbeiten kann in der user-config.py vorgegeben werden, etwa editor = 'emacs'.
    • bekannter Bug: Wenn das temporäre Bearbeitungsfenster nicht abgespeichert wird, kackt das Skript ab.
  • mit -summary:None gibt es keine oder automatische Zusammenfassungen
#!/usr/bin/python
# -*- coding: utf-8  -*-
"""

This tries to mimic some of the funcionalities of
Wikia's answers-wiki action panel (AP). 

The following parameters are available for selecting pages:

&params;

unnamed           Show pages containing given term (like '-titleregex').

If no pages are given, the AP will work on the 24 newest pages.


Other parameters:

-withredirects          If given, the AP will not skip redirects.

-safe                   If given, the AP will ask for confirmation.

-sysop                  For editing pages with admin privileges.

-static:TARGETNAME      With this, the AP will always suggest TARGETNAME
                        as default move/redirect target.

-summary:SUMMARY        Replace the AP's summaries with your own.

"""
#
# guttenborged from unlink.py, upload.py, replace.py, movepages.py
#
# (C) Leonardo Gregianin, 2006
# (C) Andreas J. Schwab, 2007
# (C) Daniel Herding & the Pywikipedia team, 2004-2010
# (C) Rob W.W. Hooft, Andre Engels 2003-2004
# (C) Pywikipedia bot team, 2003-2010
#
# Distributed under the terms of the MIT license.
#
#

import wikipedia as pywikibot
import pagegenerators
import editarticle
import sys
import webbrowser

# This is required for the text that is shown when you run this script
# with the parameter -help.
docuReplacements = {
    '&params;': pagegenerators.parameterHelp
}

class BasicBot:
    # Edit summary message that should be used.
    # NOTE: Put a good description here, and add translations, if possible!
    msg_move = {
        'de': u'Action-Panel',
        'en': u'action panel'
    }
    msg_redir = {
        'de': u'Action-Panel: Weiterleitung auf [[%s]]',
        'en': u'action panel: redirecting to [[%s]]'
    }
    msg_del = {
        'de': u'Action-Panel; Letzter Bearbeiter: [[Spezial:Beiträge/%s|%s]]',
        'en': u'action panel; last editor: [[Special:Contributions/%s|%s]]'
    }
    msg_cats = {
        'de': u'Action-Panel: Kategorien hinzugefügt (%s)',
        'en': u'action panel: added categories (%s)'
    }
    msg_edit = {
        'de': u'Action-Panel: manuelle Bearbeitung',
        'en': u'action panel: manual edit'
    }

    def __init__(self, generator, withredirects, safe, static, summary, sysop):
        """
        Constructor. Parameters:
            @param generator: The page generator that determines on which pages
                              to work.
            @type generator: generator.
            @param withredirects: Wether we look at redirects or not
            @type withredirects: Boolean
            @param safe: Do we need extra confirmation?
            @type safe: Boolean
            @param sysop: Do we want to edit as admin?
            @type sysop: Boolean
            @param static: A fixed redirect/move target
            @type static: String
            @param summary: A fixed, alternative summary
            @type summary: String
        """
        self.generator = generator
        self.withredirects = withredirects
        self.safe = safe
	self.sysop = sysop
        if static:
            self.fixed = True
            # this'll be our memory of the last entered target
            self.target = static
        else:
            self.fixed = False
            self.target = u'No good title'
        # Set the edit summary message
        if summary:
            self.summary = True
            if summary == 'None':
            	self.movesummary = ''
            	self.editsummary = ''
            	pywikibot.setAction('')
            else:
            	self.movesummary = summary
            	self.editsummary = summary
        else:
            self.movesummary = pywikibot.translate(pywikibot.getSite(),
                 self.msg_move)
            self.editsummary = pywikibot.translate(pywikibot.getSite(),
                 self.msg_edit)
            self.summary = False
        # What are the categories called around here?
        self.category = pywikibot.getSite().namespace(14)

    def run(self):
        for page in self.generator:
            self.treat(page)

    def treat(self, page):
        """
        Loads the given page, shows it, and lets you rock it.
        """
        target = self.target
        text = self.load(page, False)
        if not text:
            return

        # Show the title in purple, then the whole text.
        pywikibot.output(u'\n\n>>> \03{lightpurple}%s\03{default} <<<'
                         % page.title())
        pywikibot.output(u'%s' % text)
        choice = pywikibot.inputChoice(
            u'\nWhat to do?\n',
            ['next', 'move', 'redirect',
             'delete', 'add categories', 'edit', 'open in browser', 'quit'],
            ['N', 'm', 'r', 'd', 'c', 'e', 'b', 'q'], 'n')
        pywikibot.output(u'')
        if choice == 'n':
            # skip this
            return
        elif choice == 'm':
            pywikibot.output(
                u'Press Enter to target "%s" or give another name.' % target)
            target = pywikibot.input(u'Where to move?')
            if target == u'abort':
                return self.treat(page)
            if not target:
                target = self.target
            else:
                if not self.fixed:
                    self.target = target
            # we need the target page to check it out eventually
            targetpage = pywikibot.Page(pywikibot.getSite(), target)
            if targetpage.exists():
                pywikibot.output(
                    u'\nTarget page exists:\n\03{lightblue}%s\03{default}'
                     % self.load(targetpage, showredirects=True))
                return self.treat(page)
            if self.safe:
                fine = pywikibot.inputChoice(
                    u'\nMove to "%s"?\n' % target,
                    ['yes', 'no'],
                    ['Y', 'n'], 'y')
                if fine == 'n':
                    return self.treat(page)
            leave = True
            redir = pywikibot.inputChoice(
                u'\nLeave redirect?\n',
                ['yes', 'no'],
                ['Y', 'n'], 'y')
            if redir == 'n':
                leave = False
            try:
                pywikibot.output(u'\nMoving page %s to [[%s]]'
                                 % (page.title(asLink=True), target))
                page.move(target, self.movesummary, throttle=False,
                          leaveRedirect=leave)
            except pywikibot.LockedPage:
                pywikibot.output(u'Page %s is locked!' % page.title())
            targetpage = pywikibot.Page(pywikibot.getSite(), target)
            return self.treat(targetpage)
        elif choice == 'r':
            pywikibot.output(
                u'Press Enter to target "%s" or give another name.' % target)
            target = pywikibot.input(u'Where to redirect?')
            if target == u'abort':
                return self.treat(page)
            if not target:
                target = self.target
            else:
                if not self.fixed:
                    self.target = target
            # Enforce existing target _page_
            targetpage = pywikibot.Page(pywikibot.getSite(), target)
            try:
                targetpage.pageAPInfo()
            except pywikibot.IsRedirectPage:
                pywikibot.output(
                       u'\nTarget is a redirect:\n\03{lightblue}%s\03{default}'
                        % self.load(targetpage, showredirects=True))
                return self.treat(page)
            except pywikibot.NoPage:
                pywikibot.output(
                    u"\n\03{lightred}Your target doesn't exist.\03{default}")
                return self.treat(page)
            # everything dandy
            if self.safe:
                fine = pywikibot.inputChoice(
                    u'\nRedirect to "%s"?\n' % target,
                    ['yes', 'no'],
                    ['Y', 'n'], 'y')
                if fine == 'n':
                    return self.treat(page)
            if self.summary:
                redirsummary = self.movesummary
            else:
                redirsummary = pywikibot.translate(pywikibot.getSite(),
                     self.msg_redir) % target
            self.put(page, u'#REDIRECT [[%s]]' % target, redirsummary)
            return
        elif choice == 'd':
            if self.safe:
                fine = pywikibot.inputChoice(
                    u'\nDelete "%s"?\n' % page.title(),
                    ['yes', 'no'],
                    ['Y', 'n'], 'y')
                if fine == 'n':
                    return self.treat(page)
            if self.summary:
                delcomment = self.movesummary
            else:
                delcomment = pywikibot.translate(pywikibot.getSite(),
                     self.msg_del) % (page.userName(),page.userName())
            page.delete(reason = delcomment, prompt=False, throttle=False)
            return
        elif choice == 'c':
            cat_comment = pywikibot.translate(pywikibot.getSite(),
                 self.msg_cats)
            cats = ''
            newcat = pywikibot.input(
                u'\nEnter one new category, or nothing when finished.\n')
            while newcat:
                if newcat == 'abort':
                    return self.treat(page)
                cats = cats + (u'\n[[%s:%s]]' % (self.category,newcat))
                newcat = pywikibot.input(
                    u'\nEnter one new category, or nothing when finished.\n')
            if cats == '':
                pywikibot.output(u'\n\03{lightred}Nothing changed.\03{default}')
                return self.treat(page)
            if self.safe:
                fine = pywikibot.inputChoice(
                    u'\nAdd these? %s\n' % cats,
                    ['yes', 'no'],
                    ['Y', 'n'], 'y')
                if fine == 'n':
                    return self.treat(page)
            newText = text + cats
            if self.summary:
                self.put(page, newText, self.movesummary)
            else:
                self.put(page, newText, cat_comment % cats)
            return
        elif choice == 'e':
            editor = editarticle.TextEditor()
            newText = editor.edit(text)
            if self.safe:
                if not self.save(newText, page, self.editsummary, sysop=self.sysop):
                    pywikibot.output(u'Page %s not saved.' %
                             page.title(asLink=True))
                    self.treat(page)
            else:
                self.put(page, newText, self.editsummary, sysop=self.sysop)
            return
        elif choice == 'b':
            webbrowser.open("http://%s%s" % (
                page.site().hostname(),
                page.site().nice_get_address(page.title())
            ))
            self.treat(page)
        elif choice == 'q':
            sys.exit()

    def load(self, page, showredirects):
        """
        Loads the given page, does some changes, and saves it.
        """
        try:
            # Load the page
            if self.withredirects:
                text = page.get(get_redirect=True)
            else:
                # sometimes we want to view redirects no matter what
                text = page.get(get_redirect=showredirects)
        except pywikibot.NoPage:
            pywikibot.output(u"Page %s does not exist; skipping."
                             % page.title(asLink=True))
        except pywikibot.IsRedirectPage:
            pywikibot.output(u"Page %s is a redirect; skipping."
                             % page.title(asLink=True))
        else:
            return text
        return None

    # this is just to evade repetitive code
    def put(self, page, text, comment, sysop=False):
        try:
            # Save the page
            page.put(text, comment,
                     minorEdit=True, botflag=True, sysop=sysop)
        except pywikibot.LockedPage:
            pywikibot.output(u"Page %s is locked; skipping."
                             % page.title(asLink=True))
        except pywikibot.EditConflict:
            pywikibot.output(
                u'Skipping %s because of edit conflict'
                % (page.title()))
        except pywikibot.SpamfilterError, error:
            pywikibot.output(
u'Cannot change %s because of spam blacklist entry %s'
                % (page.title(), error.url))  

    def save(self, text, page, comment, minorEdit=True, botflag=True, sysop=False):
        # only save if something was changed
        if text != page.get():
            # Show the title of the page we're working on.
            # Highlight the title in purple.
            pywikibot.output(u"\n\n>>> \03{lightpurple}%s\03{default} <<<"
                             % page.title())
            # show what was changed
            pywikibot.showDiff(page.get(), text)
            choice = pywikibot.inputChoice(
                u'Do you want to accept these changes?',
                ['Yes', 'No'], ['Y', 'n'], 'y')
            if choice == 'y':
                self.put(page, text, comment, sysop=sysop)
        return False

def main():
    # This factory is responsible for processing command line arguments
    # that are also used by other scripts and that determine on which pages
    # to work on.
    titlepart = None
    genFactory = pagegenerators.GeneratorFactory()
    # The generator gives the pages that should be worked upon.
    gen = None
    withredirects = False
    safe = False
    sysop = False
    static = None
    summary = None

    # Parse command line arguments
    for arg in pywikibot.handleArgs():
        if arg.startswith("-withredirects"):
            withredirects = True
        elif arg.startswith("-safe"):
            safe = True
        elif arg.startswith("-static:"):
            static = arg[8:]
        elif arg.startswith("-summary:"):
            summary = arg[9:]
        elif arg.startswith("-sysop"):
            sysop = True
        else:
            # check if a standard argument like
            # -start:XYZ or -ref:Asdf was given.
            if not genFactory.handleArg(arg) and not titlepart:
                titlepart = arg

    if titlepart:
        # We will use this as a title regex (normal search is disabled).
        genFactory.handleArg('-titleregex:%s' % titlepart)
    gen = genFactory.getCombinedGenerator()

    if not gen:
        genFactory.handleArg(u'-new:24')
        gen = genFactory.getCombinedGenerator()
    # The preloading generator is responsible for downloading multiple
    # pages from the wiki simultaneously.
    gen = pagegenerators.PreloadingGenerator(gen)
    bot = BasicBot(gen, withredirects, safe, static, summary, sysop)
    bot.run()

if __name__ == "__main__":
    try:
        main()
    finally:
        pywikibot.stopme()

show.py Bearbeiten

Dieses kleine Skript kann Seiten ähnlich wie apanel.py auswählen, aber zeigt sie einfach alle in einem Rutsch an. Hilfreich zur Suche oder zur Vorschau vor einem AP-Aufruf.

#!/usr/bin/python
# -*- coding: utf-8  -*-
"""
This does nothing, it just shows you the pages it would work on, with content. 

The following parameters are supported:

&params;

-search and -titleregex are handy. If you give other parameters,
the first one will be used to yield its corresponding search results.

"""
#
# (C) Pywikipedia bot team, 2006-2010
#
# Distributed under the terms of the MIT license.
#
#

import wikipedia as pywikibot
import pagegenerators

# This is required for the text that is shown when you run this script
# with the parameter -help.
docuReplacements = {
    '&params;': pagegenerators.parameterHelp
}

class BasicBot:
    def __init__(self, generator):
        """
        Constructor. Parameters:
            @param generator: The page generator that determines on which pages
                              to work.
            @type generator: generator.
            @param regex: Will this be a regex title search?
            @type regex: boolean.
        """
        self.generator = generator

    def run(self):
        for page in self.generator:
            self.treat(page)

    def treat(self, page):
        """
        Loads the given page and shows it.
        """
        text = self.load(page)
        if not text:
            return

        # Show the title in purple, then the whole text.
        pywikibot.output(u"\n\n>>> \03{lightpurple}%s\03{default} <<<"
                         % page.title())
	pywikibot.output(text)

    def load(self, page):
        """
        How to load.
        """
        try:
            # Load the page
            text = page.get(get_redirect=True)
        except pywikibot.NoPage:
            pywikibot.output(u"Page %s does not exist; skipping."
                             % page.title(asLink=True))
        else:
            return text
        return None

def main():
    # This factory is responsible for processing command line arguments
    # that are also used by other scripts and that determine on which pages
    # to work on.
    titlepart = None
    genFactory = pagegenerators.GeneratorFactory()
    # The generator gives the pages that should be worked upon.
    gen = None

    # Parse command line arguments
    for arg in pywikibot.handleArgs():
        if not genFactory.handleArg(arg) and not titlepart:
            titlepart = arg

    if titlepart:
        # We will use this in a search.
        genFactory.handleArg('-search:%s' % titlepart)

    gen = genFactory.getCombinedGenerator()
    if gen:
        # The preloading generator is responsible for downloading multiple
        # pages from the wiki simultaneously.
        gen = pagegenerators.PreloadingGenerator(gen)
        bot = BasicBot(gen)
        bot.run()
    else:
        pywikibot.showHelp()

if __name__ == "__main__":
    try:
        main()
    finally:
        pywikibot.stopme()
Nutzung von Community-Inhalten gemäß CC-BY-SA , sofern nicht anders angegeben.