Utente:FrescoBot/Script
I seguenti script sono tutti derivati dal BasicBot (basic.py) presente nella suite Pywikipedia.
Atleti.py
Si tratta di un semplicissimo script che sarebbe dovuto servire per inserire come parametro letter nel template:SchedaIAAF l'iniziale del cognome dell'atleta soggetto della voce. Chiaramente non era possibile risolvere questo problema con AWB o con replace.py, serviva uno script ad hoc.
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
This is not a complete bot; rather, it is a template from which simple
bots can be made. You can rename it to mybot.py, then edit it in
whatever way you want.
The following parameters are supported:
¶ms;
-dry If given, doesn't do any real changes, but only shows
what would have been changed.
All other parameters will be regarded as part of the title of a single page,
and the bot will only work on that single page.
"""
__version__ = '$Id: basic.py 7845 2009-12-30 17:02:05Z xqt $'
import wikipedia as pywikibot
import wikipedia
import re
import pagegenerators
import string
from decimal import *
# This is required for the text that is shown when you run this script
# with the parameter -help.
docuReplacements = {
'¶ms;': pagegenerators.parameterHelp
}
def annotaproblema1(pag, reason):
try:
log = open("dave_atleti.txt", 'a')
except:
print "qualche problema ad annotare il problema"
return -1
messaggio = "* "+pag+": "+reason+u"\r\n"
log.write(messaggio.encode('utf-8'))
log.close()
print "problema annotato"
class BasicBot:
# Edit summary message that should be used.
# NOTE: Put a good description here, and add translations, if possible!
msg = {
'it': u'Bot: importazione dati',
# 'en': u'Bot: wrong lowercase wikilink to a section',
# 'en': u'Bot: lowercase wikilinks to uppercase sections',
}
def __init__(self, generator, dry):
"""
Constructor. Parameters:
* generator - The page generator that determines on which pages
to work on.
* dry - If True, doesn't do any real changes, but only shows
what would have been changed.
"""
self.generator = generator
self.dry = dry
def run(self):
for page in self.generator:
self.treat(page)
def treat(self, page):
confirmation = True
try:
testo_it = page.get() # scarica il contenuto della pagina
except pywikibot.NoPage:
pywikibot.output(u"Pagina %s non esiste, salto." % page.title(asLink=True))
return
except pywikibot.IsRedirectPage:
pywikibot.output(u"Pagina %s e' un redirect, salto." % page.title(asLink=True))
return
# salva una copia del contenuto originale della pagina
testo_org = testo_it
m = re.search("{{ *[Ss]chedaIAAF *\| *[Ii][dD] *= *(\d+) *}}", testo_it)
if m:
numero = m.group(1)
else:
return # passa direttamente alla prossima voce
m = re.search("\| *Cognome *= *([^\r\n\|\[\]\(\)]+)", testo_it)
if m:
cognome = m.group(1)
else:
m = re.search("^[A-Z]\w+ ([A-Z]\w+) (?:\([^\)\(]+\))?$", page.title())
if m:
cognome = m.group(1)
else:
annotaproblema1(page.title(asLink=True), "")
return # passa direttamente alla prossima voce
iniziale = cognome[0].upper()
pywikibot.output(u"%s" % cognome)
testo_it = re.sub(ur"{{ *[Ss]chedaIAAF *\| *[Ii][dD] *= *(\d+) *}}", ur'{{SchedaIAAF|letter='+iniziale+u'|ID='+str(numero)+u'}}', testo_it, 1)
# salva solo se ci sono stati cambiamenti
if testo_it != page.get():
# mostra in viola il titolo della pagina
pywikibot.output(u"\n\n>>> \03{lightpurple}%s\03{default} <<<" % page.title())
# mostra le differenze
pywikibot.showDiff(page.get(), testo_it)
if not self.dry:
if not confirmation:
choice = 'y' ## AUTO!! senza richiesta di conferma
else:
choice = pywikibot.inputChoice(u'Confermi questi cambiamenti?', ['Yes', 'No'], ['y', 'N'], 'N')
if choice == 'y':
try:
# Salva la pagina
esito = page.put(testo_it, comment="Bot: inserimento parametro letter nel template SchedaIAAF")
if esito[2]['result'] == 'Success':
print "OK"
else:
print esito
annotaproblema(page.title(asLink=True), "Salvataggio fallito!")
except pywikibot.LockedPage:
pywikibot.output(u"La pagina %s e' bloccata, salto." % page.aslink())
except pywikibot.EditConflict:
pywikibot.output(u'Salto %s a causa di un conflitto di edizione...' % (page.title()))
except pywikibot.SpamfilterError, error:
pywikibot.output(u"%s non puo' essere cambiata a causa della presenza nella spam blacklist di %s" % (page.title(), error.url))
except:
print esito, "Filtro antispam?"
annotaproblema(page.aslink(), "Salvataggio fallito (filtro antispam?)")
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.
genFactory = pagegenerators.GeneratorFactory()
# The generator gives the pages that should be worked upon.
gen = None
# This temporary array is used to read the page title if one single
# page to work on is specified by the arguments.
pageTitleParts = []
# If dry is True, doesn't do any real changes, but only show
# what would have been changed.
dry = False
# Parse command line arguments
for arg in pywikibot.handleArgs():
if arg.startswith("-dry"):
dry = True
else:
# check if a standard argument like
# -start:XYZ or -ref:Asdf was given.
if not genFactory.handleArg(arg):
pageTitleParts.append(arg)
if pageTitleParts != []:
# We will only work on a single page.
pageTitle = ' '.join(pageTitleParts)
page = pywikibot.Page(pywikibot.getSite(), pageTitle)
gen = iter([page])
if not gen:
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, dry)
bot.run()
else:
pywikibot.showHelp()
if __name__ == "__main__":
try:
main()
finally:
pywikibot.stopme()