Python:Upcopyviol.py

From Botwiki

Jump to: navigation, search
Questo è il codice del bot (quello che parte da "#!/usr/bin/python"), per la spiegazione guarda qui!
#!/usr/bin/env python
# -*- coding: iso-8859-1 -*-
#
# (C) Filnik, 2007
#
# Distributed under the terms of the MIT license.
#
# Upcopyviol 1.5
#
# Based on pywikipedia libraries.
 
"""
Readme-English:
 
This is a little script to upload the result of the copyviol.py script. Indeed
copyviol.py doesn't upload nothing in Wikipedia but it only writes a .txt file
in the "Copyright" folder. This program read it and upload what is written in a
Wikipedia's page (default: User:Filnik/Report).
 
Parameters:
-page:          It let you change the default page (User:Filnik/Report)
                whitout changing the source code.
-directory:     It let you to change the default directory where you
                have the output.txt file. Default: (the folder where is the script)/copyright
-showme:        The bot must show you the results before continue.
-askme:         The script doesn't delete the (read) output.txt at the end
                but it ask you every time.
 
Examples:
 
python upcopyviol.py -page:Wikipedia:Report -directory:C:/pywikipedia/copyright -askme
 
or:
 
python upcopyviol.py
 
TODO: Add a regex to search in the page on Wikipedia, if there is already the
report.
 
Leggimi-Italiano:
 
Questo è un piccolo script che serve per caricare i risultati ottenuti dallo
script copyviol.py di F. Cosoleto. Infatti quello script non carica nulla su
Wikipedia ma scrive soltanto un file .txt nella cartella "Copyright" di
pywikipediabot. Questo programmare lo legge e carica ciò che è scritto nel
file in una pagina di Wikipedia predefinita (default:Utente:Filnik/Report).
 
Parametri:
-page:          Permette di cambiare la pagina di default (Utente:Filnik/Report)
                senza modificare il codice sorgente.
-directory:     Permette di cambiare la directory (percorso) in cui è salvato
                il file. Di default è (cartella dov'è lo script)/copyright
-showme:        Il bot deve mostrare i risultati prima di continuare.
-askme:         Non cancella output.txt (letto) alla fine, ma chiede ogni volta
                all'utente se cancellare o meno.
 
Esempi:
 
python upcopyviol.py -page:Wikipedia:Report -directory:C:/pywikipedia/copyright -askme
 
or:
 
python upcopyviol.py
 
TODO: Aggiungere una regex per vedere se nel Report c'è già la segnalazione trovata in 
output.txt
"""
 
import wikipedia
import os, time
import codecs, config
 
mySite = wikipedia.getSite()
# There's the summary messages in the different languages
message = {
       'de':u'Bot: Automatisierte Copyviol hinzu-fuegen',
       'en':u'Robot: Automated copyviol adding',
       'it':u'Bot: Inserisco i copyviol trovati',
       }
msg = wikipedia.translate(mySite, message)
# I define the report page in Wikipedia.
report = 'Progetto:Cococo/controlli/LusumBot/controlli a campione'
# I define the report page, the directory and show in the PC
diR = str(os.getcwd())
directory = diR + '\\copyright'
always = True
show = False
# I define the answered that i will need to proceed in future.
cancella = ["Delete", "D", "d", "Del", "del", "Cancella", "cancella", "c", "C", "Cancellalo", "cancellalo"]
lascia = ["l", "L", "Let", "let", "leave", "left", "Leave", "Left", "Lascia", "lascia", "lascialo", "Lascialo"]
# Now i introduce the parameters
for arg in wikipedia.handleArgs(): 
        if arg.startswith('-page'):
                if len(arg) == 6:
                        report = wikipedia.input(u'In what page should i upload the new files?')
                else:
                        report = arg[7:]
        elif arg.startswith('-directory'):
                 if len(arg) == 6:
                         directory = str(wikipedia.input(u'Where do you have the folder "copyright"?'))
                 else:
                         directory = str(arg[7:])
        elif arg == '-askme':
                always = False
        elif arg == '-showme':
                show = True
        elif arg == '-show':
                show = True
# To reach the copyviol folder i've to change the directory
# and i use os.chdir() to do that.
os.chdir(directory)
# Now i try to pick up the output.txt file to see if it
# exists (if not it will procude an error)
if os.path.exists(directory + "/output.txt"):
        print "Output.txt exists, ok."
        running = True
elif not os.path.exists(directory + "/output.txt"):
        print "Output.txt doesn't exist!"
        running = False
# I start the main loop
while running:
        # I define the size of the file, to see if it's empty
        # or if it has data inside (that i could upload)
        size = os.path.getsize(directory + "/output.txt")
        if size >= 1:
                print "The file's size is " + str(size) + " byte"
                running = False
        elif size == 0:
                print "The file is empty!"
                break
        # If the data are not a lot i save the Wikipedia
        # page as a minor edit. Otherwise i save it as a
        # normal Edit.
        Edit = size <= 200
        filename = "output.txt"
        # I read the text that is inside Output.txt
        text = []
        f = codecs.open(filename,'r', encoding = "iso-8859-1")
        text = f.read()
        # Now i've read the file, so i change his name so
        # if the copyviol.py is still running and it finds
        # new copyviols i don't lost them.
        f.close()
        os.rename("output.txt", "temp~output.txt")
        if show:
                print "Here is what i've found: \n", text
                choice = wikipedia.inputChoice('Shall i upload the results?',  ['Yes', 'No'], ['y', 'N'], 'N')
                if choice in ['Y', 'y']:
                        print "Ok, i go"
                        pass
                elif choice in ['N', 'n']:
                        finiscila = False
                        while not finiscila:
                                print "But, what shall i do with the results?"
                                risposta = wikipedia.input(u"[D]elete or [L]et it?")
                                for p in cancella:
                                        if p in risposta:
                                                os.remove(directory + "/temp~output.txt")
                                                running = False
                                                print "Done."
                                                finiscila = True
                                for p2 in lascia:
                                        if p2 in risposta:
                                                os.rename("temp~output.txt", "read-output.txt")
                                                running = False
                                                print "Done."
                                                finiscila = True
                        break
        # Now i define the Wikipedia page, exactly.
        pagina = wikipedia.Page('it', report)
        # I take the page if exist.
        if pagina.exists():      
                testoattuale=pagina.get()
        else:
                testoattuale=''
        # I put the new text under the old one.
        pagina.put(testoattuale + "\n" + text, comment = msg, minorEdit = Edit)
        if always:
                os.remove(directory + "/temp~output.txt")
                print "Done."
        else:
                choice = wikipedia.inputChoice('Can i delete the old output.txt?',  ['Yes', 'No'], ['y', 'N'], 'N')
                if choice in ['Y', 'y']:
                        os.remove(directory + "/temp~output.txt")
                        print "Done."
                elif choice in ['N', 'n']:
                        f.close()
                        print "Output.txt still exist."
        wikipedia.stopme()
Personal tools