Utente:BimBot/Scripts: differenze tra le versioni

Contenuto cancellato Contenuto aggiunto
Nessun oggetto della modifica
PAWBot (discussione | contributi)
m Fix, replaced: <source → <syntaxhighlight (17), </source → </syntaxhighlight (17)
 
(73 versioni intermedie di 7 utenti non mostrate)
Riga 1:
__NEWSECTIONLINK__
Copiate gente, copiate! (<small>Che poi va a fuoco il computer...</small>) :-D
 
== <ttkbd>sistemaredirectredirectlinks.py</ttkbd> v. 3.0 ==
<syntaxhighlight lang="python">
<pre>
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# -*- coding: utf-8 -*-
 
#################################################################################################
# #
# Questo bot permette di modificare i link ad un redirect #
# redirectlinks.py #
# perche' puntino direttamente alla pagina giusta. #
# #
# Usa il framework pywikipedia. #
# This script corrects links to a redirect. #
################################################################
# #
# Syntax: redirectlinks.py [options] #
# Options: -dest:Destpage #
# It gets all redirects which link to Destpage and corrects their references. #
# #
# -page:Redirpage #
# It corrects all the references of the specified redirect. #
# #
# You must specify the -page OR the -dest option. #
# #
#################################################################################################
 
import re, wikipedia
 
def main():
args = wikipedia.handleArgs()
for argh in args:
if argh.startswith("-dest:"):
destPage = wikipedia.Page(wikipedia.getSite(), argh[6:])
redirs = destPage.getReferences(redirectsOnly = True)
if argh.startswith("-page:"):
redirs = [wikipedia.Page(wikipedia.getSite(), argh[6:])]
if not redirs[0].isRedirectPage():
raise wikipedia.IsNotRedirectPage(redirs[0])
destPage = redirs[0].linkedPages()[0]
wikipedia.output(destPage.title())
for r in redirs:
redirRefPages = r.getReferences()
for ref in redirRefPages:
wikipedia.output("Correcting links in page: " + ref.title())
oldtext = ref.get()
newtext = oldtext
linkRegexp = "\[\[" + re.escape(r.title()) + "(\|[^]]+)?\]\]"
ptrn = re.compile(linkRegexp, re.IGNORECASE)
linkMatch = re.search(ptrn, newtext)
while linkMatch != None:
oldLink = newtext[linkMatch.start():linkMatch.end()]
afterLink = linkMatch.group(1)
if afterLink == None:
afterLink = ""
newLink = re.sub(linkRegexp, "[[" + destPage.title() + afterLink + "]]", oldLink)
choice = wikipedia.inputChoice("Replacing link " + oldLink + " to " + newLink + ".\nDo you want to change the link?", ["Accept", "Change"], ['a', 'c'], 'a')
if choice in ['C', 'c']:
linkText = wikipedia.input("Insert link (without square brackets): [[" + destPage.title())
newLink = "[[" + destPage.title() + linkText + "]]"
newtext = newtext[:linkMatch.start()] + newLink + newtext[linkMatch.end():]
linkMatch = re.search(ptrn, newtext)
wikipedia.showDiff(oldtext, newtext)
choice = wikipedia.inputChoice(u'Modifico?', ['Yes', 'No'], ['y', 'N'], 'N')
if choice in ['Y', 'y']:
ref.put(newtext, unicode("Correcting links to redirect: " + r.title()))
 
if __name__ == "__main__":
try:
main()
finally:
wikipedia.stopme()
</syntaxhighlight>
 
== <kbd>lonelypages.py</kbd> ==
Prende le pagine da [[Speciale:Lonelypages]], verifica che siano veramente orfane e inserisce l'avviso in quelle che non lo hanno già.
Script spostato [http://www.botwiki.sno.cc/wiki/Python:Lonelypages.py qui].
 
== <kbd>proxyaperti.py</kbd> ==
Questo script fa semplicemente un edit in una pagina.
In verità serve per scovare i proxy aperti, agendo da sloggati.
Occorre però crackare wikipedia.py.
Utilizzabile solo da personale addestrato ;-)
 
<syntaxhighlight lang="python">
#! -*- coding: utf-8 -*-
 
import urllib, re
import wikipedia
 
args = wikipedia.handleArgs()
pagina = wikipedia.Page(wikipedia.getSite(), args[0])
oldtxt = pagina.get()
newtxt = oldtxt + '\nSono un vandalo malvagissimo. Non bloccatemi. --~~~~'
wikipedia.showDiff(oldtxt, newtxt)
choice = wikipedia.inputChoice('Posso procedere?', ['Yes', 'No'], ['y', 'N'], 'N')
if choice in ['Y', 'y']:
wikipedia.setAction('Bot anonimo per individuare proxy aperti firmato Pietrodn. Non bloccare please.')
pagina.put(newtxt)
wikipedia.stopme()
</syntaxhighlight>
 
== <kbd>lavorosporco.py</kbd> ==
Questo script serve per aggiornare le [[Progetto:Coordinamento/Statistiche manutenzioni|statistiche del lavoro sporco]].
 
<syntaxhighlight lang="python">
#!/usr/bin/env python
# -*- coding: utf-8 -*-
 
import re, wikipedia
from templatecount import TemplateCountRobot
 
def main():
args = wikipedia.handleArgs()
while 1:
wikiSite = wikipedia.getSite()
redirectLinks = dict()
counter = TemplateCountRobot()
all = 0;
templates = { 'A': 'Aiutare',
ic = inputchoice()
'C': 'Controllare',
if ic == u'.':
'Categorizzare': 'Da categorizzare',
safeexit()
'Controlcopy': 'Controlcopy',
if ic == u'P':
'E': 'Ency',
name = wikipedia.input(u'Inserisci il nome della pagina da cui ricavare i redirect [punto per terminare]:')
if name == u '.O': 'Orfane',
safeexit() 'P': 'NPOV',
'Senzafonti': 'Senza fonti',
page = wikipedia.Page(wikipedia.getSite(), name)
'S': 'Stub',
redirectLinks = getlinkstoredirectstopage(page)
'T': 'Tradurre',
else:
'U': 'Unire',
name = wikipedia.input(u'Inserisci il nome del redirect [punto per terminare]:')
'W': 'Wikificare',
if name == u'.':
}
safeexit()
page = wikipedia.Page(wikipedia.getSite(), name)
pagina = wikipedia.Page(wikiSite, 'Progetto:Coordinamento/Statistiche manutenzioni')
redirectLinks[page.title()] = page.getReferences()
vecchieStatistiche = pagina.get()
for i in redirectLinks:
page = wikipedia.Page(wikipedia.getSite(), i)
templateCountDict = counter.countTemplates(templates.keys(), None)
dest = wikipedia.Page(wikipedia.getSite(), page.getRedirectTarget())
ref = redirectLinks[i]
for jk in reftemplateCountDict:
sottopagina = wikipedia.Page(wikiSite, 'Progetto:Coordinamento/Statistiche manutenzioni/' + templates[k])
oldtext = j.get()
oldtxt = sottopagina.get()
lnks = sgamalink(i, oldtext)
newtxt = re.sub("</noinclude>.*", "</noinclude>" + str(templateCountDict[k]), oldtxt)
for k in lnks:
wikipedia.showDiff(oldtxt, newtxt)
print "\n"
choice = wikipedia.inputChoice(u"Modificare?", ['Yes', 'No'], ['y', 'N'], 'N')
print "Nome del redirect: " + page.aslink()
if choice in ['Y', 'y']:
print "Pagina a cui punta il redirect: " + dest.aslink()
wikipedia.setAction(u'Conto lavoro sporco')
print "Link in via di correzione: " + k
sottopagina.put(newtxt)
print "Pagina che contiene il link: " + j.aslink()
print "\n"
findRegexp = "\d+:\d+, \d+ .{3} \d+ \(.*?\)"
if u'|' in k:
replaceRegexp = "~~~~~"
regex = u"\[\[%s\|(.*?)\]\]" % i
nuoveStatistiche = re.sub(findRegexp, replaceRegexp, vecchieStatistiche)
p = re.compile(regex, re.IGNORECASE)
wikipedia.showDiff(vecchieStatistiche, nuoveStatistiche)
dopolink = re.search(p, oldtext)
choice = wikipedia.inputChoice(u"Aggiorno le date?", ['Yes', 'No'], ['y', 'N'], 'N')
choice = "[[" + dest.title() + "|" + dopolink.group(1) + "]]"
if choice in ['Y', 'y']:
else:
wikipedia.setAction(u'Aggiorno le date del conto')
choice = linkchoice(dest.title(), i)
pagina.put(nuoveStatistiche)
if choice == u'.':
safeexit()
newtext = sistema(oldtext, page.title(), choice)
wikipedia.showDiff(oldtext, newtext)
choice = wikipedia.inputChoice('Posso procedere?', ['Yes', 'No'], ['y', 'N'], 'N')
if choice in ['Y', 'y']:
wikipedia.setAction(u'Correggo i link che puntano al redirect "%s"' % page.title())
j.put(newtext)
wikipedia.stopme();
 
if __name__ == "__main__":
def safeexit():
try:
wikipedia.stopme()
exit main()
finally:
wikipedia.stopme()
</syntaxhighlight>
 
== <kbd>statistichemanutenzioni.py</kbd> ==
def getlinkstoredirectstopage(page):
Questo script serve per aggiornare le statistiche manutenzioni dei progetti tematici. Andrebbe generalizzato ed unito con lavorosporco.py.
 
<syntaxhighlight lang="python">
#!/usr/bin/env python
# -*- coding: utf-8 -*-
 
import re, wikipedia
from catlib import Category
 
def main():
args = wikipedia.handleArgs()
wikiSite = wikipedia.getSite()
categories = { u'Da controllare per copyright - psicologia': 'Controlcopy',
u'Da verificare per enciclopedicità - psicologia': 'Ency',
u'Da aiutare psicologia': 'Aiutare',
u'Pagine orfane - psicologia': 'Orfane',
u'Da controllare psicologia': 'Controllare',
u'Segnalazioni NPOV psicologia': 'NPOV',
u'Voci mancanti di fonti - psicologia': 'Senza fonti',
u'Stub psicologia': 'Stub',
u'Da tradurre - psicologia': 'Tradurre',
u'Da unire - psicologia': 'Unire',
u'Da wikificare psicologia': 'Wikificare',
}
pagina = wikipedia.Page(wikiSite, 'Progetto:Psicologia/Statistiche manutenzioni')
vecchieStatistiche = pagina.get()
for k in categories:
currentCategory = Category(wikiSite, 'Category:' + k)
categoryCount = len(currentCategory.articlesList(recurse=True))
sottopagina = wikipedia.Page(wikiSite, 'Progetto:Psicologia/Statistiche manutenzioni/' + categories[k])
oldtxt = sottopagina.get()
newtxt = str(categoryCount)
wikipedia.showDiff(oldtxt, newtxt)
choice = wikipedia.inputChoice(u"Modificare?", ['Yes', 'No'], ['y', 'N'], 'N')
if choice in ['Y', 'y']:
wikipedia.setAction(u'Conto lavoro sporco')
sottopagina.put(newtxt, "Aggiorno statistiche manutenzioni")
 
if __name__ == "__main__":
try:
main()
finally:
wikipedia.stopme()
</syntaxhighlight>
 
== <kbd>frazioni.py</kbd> ==
Questo script serve per aggiungere <kbd><nowiki>{{Tmp|Frazione}}</nowiki></kbd> a tutte le frazioni che non contengono il template {{Tl|Frazione}}.
 
<syntaxhighlight lang="python">
#!/usr/bin/env python
# -*- coding: utf-8 -*-
 
import re, wikipedia, catlib
 
def main():
args = wikipedia.handleArgs()
all = False
frazTemplateRegexp = re.compile("\{\{ *([Tt]emplate: *)?[Ff]razione")
tmpTemplateRegexp = re.compile("\{\{ *([Tt]emplate: *)?[Tt]mp *\| *[Ff]razione")
frazCat = catlib.Category(wikipedia.getSite(), "Categoria:Frazioni comunali italiane")
frazList = frazCat.articles(recurse=True)
for currentFraz in frazList:
try:
oldtxt = currentFraz.get()
except wikipedia.IsRedirectPage:
continue
if (re.search(frazTemplateRegexp, oldtxt) != None) or (re.search(tmpTemplateRegexp, oldtxt) != None):
continue
wikipedia.output(">>>>> " + currentFraz.title() + " <<<<<")
newtxt = "{{Tmp|Frazione}}\n" + oldtxt
wikipedia.showDiff(oldtxt, newtxt)
if not all:
choice = wikipedia.inputChoice(u'Aggiungo la segnalazione di template mancante?', ['Yes', 'No', 'All'], ['y', 'N', 'a'], 'N')
if choice in ['A', 'a']:
all = True
if (choice in ['Y', 'y']) or all:
currentFraz.put(newtxt, unicode("Template Frazione mancante: aggiungo {{Tmp|Frazione}}"))
if __name__ == "__main__":
try:
main()
redirectLinks = dict()
finally:
ref = page.getReferences()
wikipedia.stopme()
redirectList=list()
</syntaxhighlight>
for i in ref:
if i.isRedirectPage():
redirectLinks[i.title()] = i.getReferences()
return redirectLinks;
except wikipedia.IsNotRedirectPage:
print page.isRedirectPage()
print u"Non e' un redirect!"
return 0
except wikipedia.NoPage:
print u'La pagina non esiste!'
return 0
 
== <kbd>monitoraggioimmagini.py</kbd> ==
def inputchoice():
<syntaxhighlight lang="python">
choice = wikipedia.inputChoice(u"Vuoi inserire il nome di un redirect o di una pagina a cui linkano dei redirect? [punto per terminare]", [u'Redirect', u'Page', u'.'], [u'R', u'p', u'.'], u'R')
#!/usr/bin/env python
if choice == u'.':
# -*- utf-8 -*-
return u'.'
import wikipedia, catlib, re
elif choice in [u'P', u'p']:
return u'P'
else:
return u'R'
 
args = wikipedia.handleArgs()
def linkchoice(newpage, oldpage):
all = False
scelte = [u"[[" + newpage + u"]]", u"[[" + newpage + u"|" + newpage[0].lower() + newpage[1:] + u"]]", u"[[" + newpage + u"|" + oldpage + u"]]", u"[[" + newpage + u"|" + oldpage[0].lower() + oldpage[1:] + u"]]", u'.']
for currentArgument in args:
sceltecopy = scelte
if currentArgument.startswith("-always"):
choice = wikipedia.inputChoice(u"Scegli una delle seguenti alternative per il link: [punto per terminare]", sceltecopy, [u'1', u'2', u'3', u'4', u'.'], u'1')
all = True
if choice == u'.':
return u'.'
categoria = catlib.Category(wikipedia.getSite('it', 'wikipedia'), 'Categoria:Progetto:Aree protette/Tabella monitoraggio automatico - immagini nc')
return scelte[int(choice)-1][:len(scelte[int(choice)-1])-4]
discussioni = categoria.articles()
 
try:
def sgamalink(oldtitle, oldtext):
for i in discussioni:
regex = u"\[\[%s.*?\]\]" % oldtitle
if not i.isTalkPage():
p = re.compile(regex, re.IGNORECASE)
continue
lst = re.findall(p, oldtext)
associatedPage = i.toggleTalkPage()
return lst
pageText = associatedPage.get()
match = re.search('\[\[(image|immagine):', pageText, re.IGNORECASE)
if match == None:
wikipedia.output(">>>>> " + associatedPage.title() + " <<<<<")
talkText = i.get()
newTalkText = re.sub('\|immagini=\n', '|immagini=d\n', talkText)
wikipedia.showDiff(talkText, newTalkText)
if not all:
choice = wikipedia.inputChoice(u"Modificare?", ['Yes', 'No', 'All'], ['y', 'N', 'a'], 'N')
else:
choice = 'y'
if choice in ['A', 'a']:
all = True
choice = 'y'
if choice in ['Y', 'y']:
wikipedia.setAction(u'Non ci sono immagini: valutazione "d"')
i.put(newTalkText)
finally:
wikipedia.stopme()
</syntaxhighlight>
 
== <kbd>aggiornaCitazioniPP.py</kbd> ==
def sistema(text, oldtitle, choice):
Script usato per aggiornare le citazioni del giorno sulla pagina principale.
regex = u"\[\[%s.*?\]\]" % oldtitle
 
p = re.compile(regex, re.IGNORECASE)
<syntaxhighlight lang="python">
text = re.sub(p, choice, text)
#!/usr/bin/python
# -*- coding: utf-8 -*-
import wikipedia
import re, datetime
 
mesi = {1: 'gennaio',
2: 'febbraio',
3: 'marzo',
4: 'aprile',
5: 'maggio',
6: 'giugno',
7: 'luglio',
8: 'agosto',
9: 'settembre',
10: 'ottobre',
11: 'novembre',
12: 'dicembre',
}
 
def main():
args = wikipedia.handleArgs()
all = False
for currentArgument in args:
if currentArgument.startswith("-always"):
all = True
pageQuote = wikipedia.Page(wikipedia.getSite(code='it', fam='wikiquote'), "Wikiquote:Archivio delle citazioni del giorno/" + mesi[datetime.datetime.today().month])
originalQuotes = re.search("\{\{ArchivioQotd\}\}\n<!--.*?-->\n*(.*)", pageQuote.get(), re.DOTALL).group(1)
newQuotes = "{{Multiview\n" + re.sub("\*'''\[\[Template:Qotd/.*?\|(\d+)(.*?)\]\]:''' (.*?) \(\[\[(.*?)\]\]\)", "|<!--\\1-->[[Image:cquote1.png|12px]] \\3 [[Image:cquote2.png|12px]] <br /> '''[[q:\\4|\\4]]'''", originalQuotes) + "\n}}"
pagePedia = wikipedia.Page(wikipedia.getSite(code='it', fam='wikipedia'), "Template:Pagina principale/Citazione del giorno/Auto")
if pagePedia.exists():
oldtext = pagePedia.get()
else:
oldtext = ""
wikipedia.showDiff(oldtext, newQuotes)
if not all:
choice = wikipedia.inputChoice(u"Modificare?", ['Yes', 'No', 'All'], ['y', 'N', 'a'], 'N')
else:
choice = 'y'
if choice in ['A', 'a']:
all = True
choice = 'y'
if choice in ['Y', 'y']:
pagePedia.put(newQuotes, u"Bot: Aggiorno citazioni da Wikiquote")
 
 
if __name__ == "__main__":
try:
main()
finally:
wikipedia.stopme()
</syntaxhighlight>
 
== <kbd>numero_voci_vetrina.py</kbd> ==
Aggiorna il template contenente il numero di voci in vetrina.
 
<syntaxhighlight lang="python">
# -*- coding: utf8 -*-
import wikipedia, catlib
 
def main():
args = wikipedia.handleArgs()
all = False
for currentArgument in args:
if currentArgument.startswith("-always"):
all = True
vetrinaCat = catlib.Category(wikipedia.getSite('it', 'wikipedia'), "Categoria:Voci in vetrina")
arts = vetrinaCat.articlesList(recurse=False)
newtext = str(len(arts))
wikipedia.output("Numero di voci in vetrina: " + newtext)
page = wikipedia.Page(wikipedia.getSite('it', 'wikipedia'), "Template:Numero voci in Vetrina")
if page.exists():
oldtext = page.get()
else:
oldtext = ""
wikipedia.showDiff(oldtext, newtext)
if not all:
choice = wikipedia.inputChoice(u"Modificare?", ['Yes', 'No', 'All'], ['y', 'N', 'a'], 'N')
else:
choice = 'y'
if choice in ['A', 'a']:
all = True
choice = 'y'
if choice in ['Y', 'y']:
page.put(newtext, u"Bot: Aggiorno numero di voci in vetrina")
 
if __name__ == "__main__":
try:
main()
finally:
wikipedia.stopme()
</syntaxhighlight>
 
== <kbd>codici_autori_fantascienza.py</kbd> ==
<syntaxhighlight lang="python">
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from autorifanta import *
import wikipedia, re, catlib
 
args = wikipedia.handleArgs()
all = False
for currentArgument in args:
if currentArgument.startswith("-always"):
all = True
categoria = catlib.Category(wikipedia.getSite('it', 'wikipedia'), 'Categoria:Autori di fantascienza')
voci = categoria.articles(recurse=True)
 
try:
for i in voci:
wikipedia.output(">>>>> " + i.title() + " <<<<<")
nomi = i.title().split(' ')
print nomi
for j in autoriFantascienza:
authorId = None
if nomi[len(nomi)-1].lower() == j[2].lower() and nomi[0].lower() in j[1].lower():
authorId = j[3]
print j
if authorId:
oldText = i.get()
newText = re.sub("== ?[Cc]ollegamenti esterni ?==", "== Collegamenti esterni ==\n{{Catalogo SF|" + str(authorId) + "}}", oldText)
wikipedia.showDiff(oldText, newText)
i = wikipedia.Page(wikipedia.getSite('it', 'wikipedia'), 'Utente:BimBot/Sandbox') # DEBUG
if not all:
choice = wikipedia.inputChoice(u"Modificare?", ['Yes', 'No', 'All'], ['y', 'N', 'a'], 'N')
else:
choice = 'y'
if choice in ['A', 'a']:
all = True
choice = 'y'
if choice in ['Y', 'y']:
wikipedia.setAction(u'Inserisco id autore SF')
i.put(newText)
finally:
wikipedia.stopme()
</syntaxhighlight>
 
== <kbd>articoli_defaultsort.py</kbd> ==
<syntaxhighlight lang="python">
#!/usr/bin/env python
# -*- coding: utf-8 -*-
 
import re, wikipedia
import pagegenerators
from add_text import add_text
 
def main():
args = wikipedia.handleArgs()
all = False
genFactory = pagegenerators.GeneratorFactory()
for currentArgument in args:
if currentArgument.startswith("-always"):
all = True
else:
generator = genFactory.handleArg(currentArgument)
# Check if pages on which the bot should work are specified.
if not generator:
raise NoEnoughData('You have to specify which pages the script has to work on!')
# Main Loop
for i in generator:
attenzioneIo = False # Dubbio su "I" o "An", che possono svolgere diverse funzioni.
titolo = i.title()
wikipedia.output(">>>>> " + titolo + " <<<<<")
nuovoTitolo = re.sub("^(The |A |Il |Lo |La |I |Gli |Le |L'|Uno |Una |Un'|Un )([A-Z0-9].*)", r"{{DEFAULTSORT:\2, \1}}", titolo)
if titolo == nuovoTitolo:
wikipedia.output("Non c'è nessun articolo. Prossima pagina...")
continue
if re.search("^(I |An )", titolo):
attenzioneIo = True
nuovoTitolo = re.sub("[ ']\}\}", "}}", nuovoTitolo) # Toglie spazi, apostrofi...
try:
oldtext = i.get()
except wikipedia.IsRedirectPage:
wikipedia.output(u"%s is a redirect, I'll ignore it." % i.title())
continue
if re.search("\{\{DEFAULTSORT:", oldtext):
wikipedia.output("C'è già un DEFAULTSORT. Prossima pagina...")
continue
newtext = add_text(page = i, addText = nuovoTitolo, putText = False, oldTextGiven = oldtext)[1]
wikipedia.showDiff(oldtext, newtext)
if not all or attenzioneIo:
choice = wikipedia.inputChoice(u"Modificare?", ['Yes', 'No', 'All'], ['y', 'N', 'a'], 'N')
else:
choice = 'y'
if choice in ['A', 'a']:
all = True
choice = 'y'
if choice in ['Y', 'y']:
i.put_async(newtext, comment="Aggiungo: " + nuovoTitolo)
if __name__ == "__main__":
try:
main()
finally:
wikipedia.stopme()
</syntaxhighlight>
 
== <kbd>newsPedia.py</kbd> ==
Prende le ultime notizie da 'news e le sbatte su 'pedia.
<syntaxhighlight lang="python">
#!/usr/bin/env python
# -*- coding: utf-8 -*-
 
import wikipedia, urllib2, re
 
# Costanti
newsListPage = wikipedia.Page(wikipedia.getSite('it', 'wikinews'), 'Utente:BimBot/RecentNews') # Prende qui le notizie
updatePage = wikipedia.Page(wikipedia.getSite('it', 'wikipedia'), 'Template:Pagina principale/Notizie/Auto') # Dove mette le notizie
 
def pageText(url):
request = urllib2.Request(url)
user_agent = 'BimBot/1.0'
request.add_header("User-Agent", user_agent)
response = urllib2.urlopen(request)
text = response.read()
response.close()
return text
def main():
args = wikipedia.handleArgs()
all = False
for currentArgument in args:
if currentArgument.startswith("-always"):
all = True
wikipedia.output(">>>>> " + updatePage.title() + " <<<<<")
try:
oldtext = updatePage.get()
except wikipedia.NoPage:
oldtext = ''
wikipedia.output("Purging input page...")
newsListPage.put(newsListPage.get()) # PURGE
newsListUrl = 'http://' + newsListPage.site().hostname() + newsListPage.site().nice_get_address(newsListPage.title())
try:
htmlText = pageText(newsListUrl)
except urllib2.HTTPError:
try:
wikipedia.output(u"Errore del server. Aspetto 10 secondi... " + time.strftime("%d %b %Y %H:%M:%S (UTC)", time.gmtime()) )
time.sleep(10)
htmlText = pageText(newsListUrl)
except urllib2.HTTPError:
wikipedia.output(u"Errore del server. Chiudo.")
return
divMatch = re.search('(?s)<div id="recentnews">(.*?)</div>', htmlText) # Prendo il blocco che mi interessa
news = re.findall('<li><a .*?>(.*?)</a></li>', divMatch.group(1)) # Array di titoli di notizie
newtext = ''
for i in news:
newtext = newtext + '[[n:' + i + '|' + i + ']] · ' # Formatto il link
newtext = newtext[:len(newtext)-3].decode('utf-8') # Tolgo il pallino alla fine e decodifico
wikipedia.showDiff(oldtext, newtext)
if not all:
choice = wikipedia.inputChoice(u"Aggiorno?", ['Yes', 'No', 'All'], ['y', 'N', 'a'], 'N')
else:
choice = 'y'
if choice in ['A', 'a']:
all = True
choice = 'y'
if choice in ['Y', 'y']:
wikipedia.setAction("Aggiorno notizie da Wikinews")
updatePage.put(newtext)
 
if __name__ == "__main__":
try:
main()
finally:
wikipedia.stopme()
</syntaxhighlight>
 
== <kbd>copyviolInversi.py</kbd> ==
<syntaxhighlight lang="python">
#!/usr/bin/env python
# -*- coding: utf-8 -*-
 
import wikipedia, re, catlib
 
# Costanti
site = wikipedia.getSite('it', 'wikipedia')
logPage = wikipedia.Page(site, 'Wikipedia:Copyviol inversi/Segnalazioni/Bot')
archPage = wikipedia.Page(site, 'Wikipedia:Copyviol inversi/Segnalazioni/Archivio/Bot')
copyCat = catlib.Category(site, 'Categoria:Copyviol inversi')
copyTemplate = u'Utente:Marco 27/Sandbox cloni'
logTemplate = u'Utente:Marco 27/Sandbox cloni/2'
def main():
args = wikipedia.handleArgs()
all = False
for currentArgument in args:
if currentArgument.startswith("-always"):
all = True
talkList = copyCat.articles(recurse=True)
logNew = ""
archNew = ""
for i in talkList:
talkText = i.get()
templs = filter((lambda x: x[0]==copyTemplate), i.templatesWithParams()) # Prendo solo i template che mi interessano
for j in templs:
logEntry = '\n' + '{{' + logTemplate + '|pagina=' + i.toggleTalkPage().title() + '|' + str('|').join(j[1]) + '}}'
if re.search("\|esito\s*=\s*(6|7|8|2|3)\s*", logEntry):
archNew += logEntry
else:
logNew += logEntry
# Aggiornamento LOG
wikipedia.output(">>>>> " + logPage.title() + " <<<<<")
try:
logOld = logPage.get()
except wikipedia.NoPage:
logOld = ''
wikipedia.showDiff(logOld, logNew)
if not all:
choice = wikipedia.inputChoice(u"Aggiorno il log?", ['Yes', 'No', 'All'], ['y', 'N', 'a'], 'N')
else:
choice = 'y'
if choice in ['A', 'a']:
all = True
choice = 'y'
if choice in ['Y', 'y']:
wikipedia.setAction("Bot: Aggiorno il log dei presunti [[WP:Copyviol inversi|copyviol inversi]]")
logPage.put(logNew)
# Aggiornamento ARCHIVIO
wikipedia.output(">>>>> " + archPage.title() + " <<<<<")
try:
archOld = archPage.get()
except wikipedia.NoPage:
archOld = ''
wikipedia.showDiff(archOld, archNew)
if not all:
choice = wikipedia.inputChoice(u"Aggiorno l'archivio?", ['Yes', 'No', 'All'], ['y', 'N', 'a'], 'N')
else:
choice = 'y'
if choice in ['A', 'a']:
all = True
choice = 'y'
if choice in ['Y', 'y']:
wikipedia.setAction("Bot: Archivio i [[WP:Copyviol inversi|copyviol inversi]]")
archPage.put(archNew)
 
if __name__ == "__main__":
try:
main()
finally:
wikipedia.stopme()
</syntaxhighlight>
 
== <kbd>importa_asteroidi.py</kbd> ==
<syntaxhighlight lang="python">
# -*- coding: utf-8 -*-
import wikipedia, re, sys, codecs
 
def main():
args = wikipedia.handleArgs()
beginast = args[0]
beginok = False
templatefile = codecs.open("modelloasteroide.txt", "r", "utf-8")
testomodello = templatefile.read()
templatefile.close()
myfile = file(u'MPCORB.DAT')
return text
for theLine in myfile:
if not theLine[0].isdigit(): continue
tupla = adatta(theLine)
if not tupla[31][0].isalpha(): continue
asteroidname = tupla[30] + ' ' + tupla[31]
if (asteroidname != beginast) and (not beginok): continue
beginok = True
print asteroidname
mypage = wikipedia.Page(wikipedia.getSite(), asteroidname)
# mypage = wikipedia.Page(wikipedia.getSite(), u'Utente:BimBot/Sandbox')
if mypage.exists():
continue
oldtxt = u''
newtxt = generatemplate(testomodello, tupla)
wikipedia.showDiff(oldtxt, unicode(newtxt))
print tupla
choice = wikipedia.inputChoice(u"Modificare?", ['Yes', 'No'], ['y', 'N'], 'N')
if choice in [u'Y', u'y']:
wikipedia.setAction(u'Nuovo asteroide')
mypage.put(newtxt)
myfile.close()
wikipedia.stopme()
 
def adatta(txt):
if __name__==u"__main__":
mtch=re.match('^([^ ]*) *(\d+)\.(\d+) *(-?\d+)\.([0-9]+) *([^ ]*) *(\d+)\.(\d+) *(\d+)\.(\d+) *(\d+)\.(\d+) *(\d+)\.(\d+) *(\d+)\.(\d+) *(\d+)\.(\d+) *(\d+)\.(\d+) *\d? *(....? *\d+) *(\d+) *(\d+) *(\d{4})-(\d{4}) *(\d+)\.(\d+) *(M-.) *([^ ]*) *([^ ]*?) *.{4} *\((\d+)\)(.*?) *(\d{8})', txt)
main()
#print txt
</pre>
grps = mtch.groups()
return grps
#
def generatemplate(modello, tupla):
elencosostituzioni = {
u'#nome': tupla[31],
u'#sottotitolo': tupla[30] + ' ' + tupla[31],
u'#magn_ass': tupla[1]+','+tupla[2],
u'#epoca': tupla[5],
u'#anomalia_media': tupla[6]+','+tupla[7],
u'#argomento_perielio': tupla[8]+','+tupla[9],
u'#nodo_ascendente': tupla[10]+','+tupla[11],
u'#inclinazione_asse_su_eclittica': tupla[12]+','+tupla[13],
u'#eccentricità': tupla[14]+','+tupla[15],
u'#semiasse_maggiore': tupla[18]+','+tupla[19],
u'#data': tupla[23]
}
for k in elencosostituzioni:
modello = re.sub(k, elencosostituzioni[k], modello)
return modello
main()
 
#K07B19V 15.7 0.15 K06CV 19.17898 347.71274 101.16774 10.08579 0.0550460 0.19108058 2.9853254 E2007-B48 13 1 16 days 0.37 MPC 0000 2007 BV19 20070124
== <tt>lonelypages.py</tt> ==
</syntaxhighlight>
Prende le pagine da [[Speciale:Lonelypages]], verifica che siano veramente orfane e inserisce l'avviso in quelle che non lo hanno già.
 
=== <kbd>modello_asteroide.txt</kbd> ===
<pre>
{{S|asteroidi}}
{{Corpo celeste
|tipo = Asteroide
|nome = #nome
|sottotitolo = #sottotitolo
|magn_ass = #magn_ass
|epoca = #epoca
|anomalia_media = #anomalia_media°
|argomento_perielio = #argomento_perielio°
|nodo_ascendente = #nodo_ascendente°
|inclinazione_asse_su_eclittica = #inclinazione_asse_su_eclittica°
|eccentricità = #eccentricità
|semiasse_maggiore = #semiasse_maggiore UA
|data = #data
}}
 
'''#nome''' è un [[asteroide]] del [[sistema solare]]. Scoperto nel [[#data]], presenta un'[[orbita]] caratterizzata da un [[semiasse maggiore]] pari a #semiasse_maggiore [[Unità Astronomica|UA]] e da un'[[eccentricità orbitale|eccentricità]] di #eccentricità, inclinata di #inclinazione_asse_su_eclittica° rispetto all'[[eclittica]].
 
{{Asteroide}}
 
[[Categoria:Asteroidi del sistema solare|#nome]]
</pre>
 
== <kbd>discussioneanonimi3.py</kbd> ==
 
<syntaxhighlight lang="python">
# -*- coding: utf-8 -*-
import wikipedia, re, commands
 
def main():
wikipedia.handleArgs()
talkpages = wikipedia.Page(wikipedia.getSite(), u'Wikipedia:Elenchi generati offline/Discussioni utenti anonimi').linkedPages();
for talk in talkpages:
static=False
if talk.namespace() != 3 or not talk.exists() or not talk.canBeEdited():
continue
wikipedia.output(">>>>> " + talk.title() + " <<<<<")
oldtext = talk.get()
if checkStatic(talk.titleWithoutNamespace()):
newtext = oldtext + u'\n[[Categoria:IP statici]]'
wikipedia.showDiff(oldtext, newtext)
wikipedia.setAction(u'Categorizzo in [[:Categoria:IP statici]]')
talk.put(newtext)
else:
newtext = u'{{BenvenutoIP}}'
match = re.search("\{\{IPcondiviso.*?\}\}", oldtext)
if match != None:
newtext = match.group() + '\n' + newtext
wikipedia.showDiff(oldtext, newtext)
wikipedia.setAction(u'Svuotata pagina ed inserito benvenuto.')
talk.put(newtext)
 
def checkStatic(ip):
response = commands.getoutput("dig -x " + ip + " +short")
wikipedia.output('Dig response: ' + response)
return bool(re.search('[Ss]tatic', response))
if __name__ == "__main__":
try:
main()
finally:
wikipedia.stopme()
</syntaxhighlight>
 
== <kbd>prefissiTelefonici.py</kbd> ==
<syntaxhighlight lang="python">
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import wikipedia, pagegenerators, re, catlib
 
note1 = u"<ref>[http://www2.agcom.it/provv/d_8_01_CIR.htm Delibera n. 8/01/CIR]</ref>"
import wikipedia
note2 = u"<ref>[http://www.paginebianche.it/prefissi-telefonici?pref=%s Elenco sulle Pagine Bianche]</ref>"
sezioneNote = u"== Note ==\n<references />\n"
 
oggetto = u"Aggiungo le fonti per il prefisso telefonico ([[Wikipedia:Bot/Richieste#Aggiungere_fonte_ai_prefissi_telefonici_italiani|richiesta]])."
 
def main():
all = False
args = wikipedia.handleArgs()
startWith=""
for argh in args:
if argh.startswith("-start:"):
startWith = argh[len("-start:"):]
mySite = wikipedia.getSite(code='it', fam='wikipedia')
cat = catlib.Category(mySite, "Categoria:Prefissi telefonici italiani")
gen = pagegenerators.CategorizedPageGenerator(cat, False, startWith)
for p in gen:
voceOk = 1
try:
oldText = p.get()
except wikipedia.NoPage:
wikipedia.output(currentPage.title() + " does not exist!")
continue
except wikipedia.IsRedirectPage:
p = p.getRedirectTarget()
oldText = p.get()
# Per sicurezza se non esegue tutti i match salta la voce
if re.search("== ?[Nn]ote ?==", oldText):
continue
# Ottengo il prefisso "nudo" dal titolo
m = re.match("^(\d+)", p.title());
if m == None:
continue
prefisso = m.group(1)
newText = oldText
# Sostituzione 1
m = re.subn(r"il \[\[prefisso telefonico\]\] del \[\[distretto telefonico\|distretto\]\] di \[\[(.*?)\]\],",
r"il [[prefisso telefonico]] del [[distretto telefonico|distretto]] di [[\1]]" + note1 + ",",
newText, 1)
if m[1]==0:
continue
else:
newText = m[0]
# Sostituzione 2
m = re.subn(r"Il distretto di (.*?) comprende (.*?)\.\s+\{\{[Cc]ompartimento",
r'Il distretto di \1 comprende \2 ' + note2 % prefisso + ".\n\n" + sezioneNote + "\n{{Compartimento",
newText, 1)
if m[1]==0:
continue
else:
newText = m[0]
# Sostituzione 3
newText = re.sub("\{\{[Ff](\|.*?)\}\}\s+", "", newText, 1)
# Visualizza le differenze, chiede e salva
wikipedia.output(u"\n\n>>> \03{lightpurple}%s\03{default} <<<"
% p.title())
wikipedia.showDiff(oldText, newText)
if not all:
choice = wikipedia.inputChoice(u"Modificare?",
['Yes', 'No', 'All', "Quit"],
['y', 'N', 'a', 'q'], 'N')
else:
choice = 'y'
if choice in ['A', 'a']:
all = True
choice = 'y'
if choice in ['Y', 'y']:
p.put_async(newText, minorEdit=False, comment=oggetto)
elif choice in ['Q', 'q']:
return
if __name__ == "__main__":
try:
main()
finally:
wikipedia.stopme()
</syntaxhighlight>
 
== <code>vocicorrelate.py</code> ==
 
<syntaxhighlight lang="python">
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Lo script rimuove i piped links e i corsivi dai link nelle "Voci correlate".
# Si lancia con gli argomenti supportati da pagegenerators.py
#
# Esempi:
# $ python vocicorrelate.py -catr:Informatica
# $ python vocicorrelate.py -start:!
#
# Autore: Pietrodn
 
import wikipedia, pagegenerators, re
 
oggetto = u"Uniformo le [[Aiuto:Voci correlate|voci correlate]]"
 
def main():
all = False
args = wikipedia.handleArgs()
genf = pagegenerators.GeneratorFactory();
for argh in args:
genf.handleArg(argh)
mySite = wikipedia.getSite(code='it', fam='wikipedia')
gen = genf.getCombinedGenerator()
if not gen:
return
for p in gen:
try:
oldText = p.get()
except wikipedia.NoPage:
wikipedia.output(currentPage.title() + " does not exist!")
continue
except wikipedia.IsRedirectPage:
p = p.getRedirectTarget()
oldText = p.get()
newText = oldText
# Cerco il contenuto della sezione voci correlate:
# inizia dal titolo di sezione e finisce alla prima riga che non inizia con un punto elenco
m = re.search(r"(?s)==\s*[Vv]oci correlate\s*==(.*?)\n[^*]", oldText)
# Niente "voci correlate"? Passo alla prossima voce
if not m:
continue
vcorrTextOld = m.group(1)
vcorrText = vcorrTextOld
# Tolgo il corsivo
vcorrText = re.sub(r"''\[\[(.*?)\]\]''", r"[[\1]]", vcorrText);
# Tolgo i piped link
vcorrText = re.sub(r"\[\[(.*?)\|(.*?)\]\]", r"[[\1]]", vcorrText);
# Se non ho effettuato modifiche nella sezione "voci correlate", avanti alla prossima voce
if vcorrText == vcorrTextOld:
continue
# Re-innesto la sezione voci correlate al suo posto nella voce
newText = re.sub(r"(?s)==\s*[Vv]oci correlate\s*==(.*?)(\n[^*])", r"== Voci correlate ==" + vcorrText + r"\2", oldText)
# Visualizza le differenze, chiede e salva
wikipedia.output(u"\n\n>>> \03{lightpurple}%s\03{default} <<<"
% p.title())
wikipedia.showDiff(oldText, newText)
if not all:
choice = wikipedia.inputChoice(u"Modificare?",
['Yes', 'No', 'All', "Quit"],
['y', 'N', 'a', 'q'], 'N')
else:
choice = 'y'
if choice in ['A', 'a']:
all = True
choice = 'y'
if choice in ['Y', 'y']:
p.put_async(newText, minorEdit=True, comment=oggetto)
elif choice in ['Q', 'q']:
return
if __name__ == "__main__":
try:
main()
finally:
wikipedia.stopme()
</syntaxhighlight>
 
== Eliminazione parametro "Stato" dal [[Template:Edificio religioso]] ==
 
Codice da inserire in <kbd>user-fixes.py</kbd>:
 
<syntaxhighlight lang="python">
import re
from pagegenerators import AllpagesPageGenerator
 
def EdRel(match):
args = wikipedia.handleArgs()
# Le parentesi devono essere bilanciate, e le prime parentesi graffe trovate non devono essere chiuse
wikiSite = wikipedia.getSite()
aperte = re.findall(ur'\{\{', match.group(1))
allpages = wikiSite.lonelypages()
chiuse = re.findall(ur'\}\}', match.group(1))
for i in allpages:
if (len(aperte) == len(chiuse)) and (not re.match("(?s)[^{}]*\}\}.*", match.group(1))):
if i.isRedirectPage():
return ur"{{Edificio religioso" + match.group(1)
continue
else:
refs = i.getReferences()
return match.group() # Unchanged
refsList = list()
for j in refs:
fixes['EdificioReligioso'] = {
refsList = refsList + [j]
'regex': True,
if len(refsList) == 0:
'msg': {
regxp = ur'\{\{[Oo]rfan[oa]'
'_default':u'Eliminazione parametro obsoleto del [[Template:Edificio religioso]] ([[Wikipedia:Bot/Richieste#Eliminazione_campo_dal_template_.22Edificio_religioso.22|richiesta]])',
oldtxt = i.get()
},
if re.match(regxp, oldtxt) == None:
'replacements': [
newtxt = u'{{Orfana}}\n' + oldtxt
(ur"(?s)\{\{\s*[Ee]dificio[ _]religioso(.*?)\|\s*[Ss]tato\s*=\s*([^|\n]*)\n", EdRel),
print i
],
wikipedia.showDiff(oldtxt, newtxt)
'exceptions': {
choice = wikipedia.inputChoice(u'Pagina orfana non segnalata! Posso procedere?', [u'Yes', u'No'], [u'y', u'N'], u'N')
'inside-tags': ['comment', 'header', 'pre', 'source', 'ref', 'table', 'hyperlink', 'gallery', 'link', 'interwiki' ],
if choice in [u'Y', u'y']:
}
wikipedia.setAction(u'Voce orfana')
}
i.put(newtxt)
</syntaxhighlight>
wikipedia.stopme()
</pre>