Copiate gente, copiate! (Che poi va a fuoco il computer...) :-D

redirectlinks.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-

#################################################################################################
#																								#
#	redirectlinks.py																			#
#																								#
#	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()

lonelypages.py

Prende le pagine da Speciale:Lonelypages, verifica che siano veramente orfane e inserisce l'avviso in quelle che non lo hanno già. Script spostato qui.

proxyaperti.py

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 ;-)

#! -*- coding: utf-8 -*-

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()

lavorosporco.py

Questo script serve per aggiornare le statistiche del lavoro sporco.

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import re, wikipedia
from templatecount import TemplateCountRobot

def main():
	args = wikipedia.handleArgs()
	
	wikiSite = wikipedia.getSite()
	counter = TemplateCountRobot()
	templates = {	'A': 'Aiutare',
					'C': 'Controllare',
					'Categorizzare': 'Da categorizzare',
					'Controlcopy': 'Controlcopy',
					'E': 'Ency',
					'O': 'Orfane',
					'P': 'NPOV',
					'Senzafonti': 'Senza fonti',
					'S': 'Stub',
					'T': 'Tradurre',
					'U': 'Unire',		
					'W': 'Wikificare',	
	}
	
	pagina = wikipedia.Page(wikiSite, 'Progetto:Coordinamento/Statistiche manutenzioni')
	vecchieStatistiche = pagina.get()
	
	templateCountDict = counter.countTemplates(templates.keys(), None)
	
	for k in templateCountDict:
		sottopagina = wikipedia.Page(wikiSite, 'Progetto:Coordinamento/Statistiche manutenzioni/' + templates[k])
		oldtxt = sottopagina.get()
		newtxt = re.sub("</noinclude>.*", "</noinclude>" + str(templateCountDict[k]), oldtxt)
		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)
			
	findRegexp = "\d+:\d+, \d+ .{3} \d+ \(.*?\)"
	replaceRegexp = "~~~~~"
	nuoveStatistiche = re.sub(findRegexp, replaceRegexp, vecchieStatistiche)
	wikipedia.showDiff(vecchieStatistiche, nuoveStatistiche)
	choice = wikipedia.inputChoice(u"Aggiorno le date?",  ['Yes', 'No'], ['y', 'N'], 'N')
	if choice in ['Y', 'y']:
		wikipedia.setAction(u'Aggiorno le date del conto')
		pagina.put(nuoveStatistiche)
	

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

statistichemanutenzioni.py

Questo script serve per aggiornare le statistiche manutenzioni dei progetti tematici. Andrebbe generalizzato ed unito con lavorosporco.py.

#!/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()

frazioni.py

Questo script serve per aggiungere {{Tmp|Frazione}} a tutte le frazioni che non contengono il template {{Frazione}}.

#!/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()
	finally:
		wikipedia.stopme()

monitoraggioimmagini.py

#!/usr/bin/env python
# -*- utf-8 -*-
import wikipedia, catlib, re

args = wikipedia.handleArgs()
all = False
for currentArgument in args:
	if currentArgument.startswith("-always"):
		all = True
 
categoria = catlib.Category(wikipedia.getSite('it', 'wikipedia'), 'Categoria:Progetto:Aree protette/Tabella monitoraggio automatico - immagini nc')
discussioni = categoria.articles()

try:
    for i in discussioni:
        if not i.isTalkPage():
            continue
        associatedPage = i.toggleTalkPage()
        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()

aggiornaCitazioniPP.py

Script usato per aggiornare le citazioni del giorno sulla pagina principale.

#!/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()

numero_voci_vetrina.py

Aggiorna il template contenente il numero di voci in vetrina.

# -*- 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()

codici_autori_fantascienza.py

#!/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()

articoli_defaultsort.py

#!/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", che può essere articolo determinativo italiano o pronome personale inglese
        titolo = i.title()
        wikipedia.output(">>>>> " + titolo + " <<<<<")
          
        nuovoTitolo = re.sub("^(The |A |An |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 ", 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()

newsPedia.py

Prende le ultime notizie da 'news e le sbatte su 'pedia.

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import wikipedia, urllib2, re

# Costanti
newsListUrl = 'http://it.wikinews.org/wiki/Utente:BimBot/RecentNews' # Prende qui le notizie
updatePage = '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
    site = wikipedia.getSite("it", "wikipedia")
    
    for currentArgument in args:   
        if currentArgument.startswith("-always"):
            all = True
    
    page = wikipedia.Page(site, updatePage)
    wikipedia.output(">>>>> " + page.title() + " <<<<<")
    try:
        oldtext = page.get()
    except wikipedia.NoPage:
        oldtext = ''
    
    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")
        page.put(newtext)    

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