clean_sandbox.py :  » Network » Python-Wikipedia-Robot-Framework » pywikipedia » Python Open Source

Home
Python Open Source
1.3.1.2 Python
2.Ajax
3.Aspect Oriented
4.Blog
5.Build
6.Business Application
7.Chart Report
8.Content Management Systems
9.Cryptographic
10.Database
11.Development
12.Editor
13.Email
14.ERP
15.Game 2D 3D
16.GIS
17.GUI
18.IDE
19.Installer
20.IRC
21.Issue Tracker
22.Language Interface
23.Log
24.Math
25.Media Sound Audio
26.Mobile
27.Network
28.Parser
29.PDF
30.Project Management
31.RSS
32.Search
33.Security
34.Template Engines
35.Test
36.UML
37.USB Serial
38.Web Frameworks
39.Web Server
40.Web Services
41.Web Unit
42.Wiki
43.Windows
44.XML
Python Open Source » Network » Python Wikipedia Robot Framework 
Python Wikipedia Robot Framework » pywikipedia » clean_sandbox.py
# -*- coding: utf-8 -*-
"""
This bot cleans a sandbox by replacing the current contents with predefined
text.

This script understands the following command-line arguments:

    -hours:#       Use this parameter if to make the script repeat itself
                   after # hours. Hours can be defined as a decimal. 0.01
                   hours are 36 seconds; 0.1 are 6 minutes.

    -delay:#       Use this parameter for a wait time after the last edit
                   was made. If no parameter is given it takes it from
                   hours and limits it between 5 and 15 minutes.
                   The minimum delay time is 5 minutes.

"""
#
# (C) Leonardo Gregianin, 2006
# (C) Wikipedian, 2006-2007
# (C) Andre Engels, 2007
# (C) Siebrand Mazeland, 2007
# (C) xqt, 2009
#
# Distributed under the terms of the MIT license.
#
__version__ = '$Id: clean_sandbox.py 8206 2010-05-25 13:38:02Z xqt $'
#

import time
import wikipedia as pywikibot

content = {
    'als':u'{{subst:/Vorlage}}',
    'ar': u'{{       (  )}}\n<!-- !           .           6 . -->',
    'bar':u'{{Bitte erst NACH dieser Zeile schreiben! (Begrungskasten)}}\r\n',
    'cs': u'{{subst:/uhrabat}}',
    'da': u'{{subst:Sandkasse tekst}}',
    'de': u'{{Bitte erst NACH dieser Zeile schreiben! (Begrungskasten)}}\r\n',
    'en': u'{{Please leave this line alone (sandbox heading)}}\n<!-- Hello! Feel free to try your formatting and editing skills below this line. As this page is for editing experiments, this page will automatically be cleaned every 12 hours. -->',
    'fa': u'{{subst:User:Amirobot/sandbox}}',
    'fi': u'{{subst:Hiekka}}',
    'he': u'{{ }}\n<!--      , . -->',
    'id': u'{{Bakpasir}}\n<!-- Uji coba dilakukan di baris di bawah ini -->',
    'it': u'{{sandbox}}<!-- Scrivi SOTTO questa riga senza cancellarla. Grazie. -->',
    'ja': u'{{subst:}}',
    'ko': u'{{ }}',
    'ksh':u'{{subst:/Schablon}}',
    'nds':u'{{subst:/Vrlaag}}',
    'nl': u'{{subst:Wikipedia:Zandbak/schoon zand}}',
    'no': u'{{Sandkasse}}\n<!-- VENNLIGST EKSPERIMENTER NEDENFOR DENNE SKJULTE TEKSTLINJEN! SANDKASSEMALEN {{Sandkasse}} SKAL IKKE FJERNES! -->}}',
    'nn': u'{{sandkasse}}\n<!-- Ver snill og IKKJE FJERN DENNE LINA OG LINA OVER ({{sandkasse}}) Nedanfre kan du derimot ha det artig og prve deg fram! Lykke til! :-)  -->',
    'pl': u'{{Prosimy - NIE ZMIENIAJ, NIE KASUJ, NIE PRZENO tej linijki - pisz niej}}',
    'pt': u'<!--no apague esta linha-->{{pgina de testes}}<!--no apagar-->\r\n',
    'commons': u'{{Sandbox}}\n<!-- Please edit only below this line. -->',
    'ru': u'{{/ }}\n<!--  , ,  ,   -->',
    'sr': u'{{}}\n<!-- ,    . . -->',
    'sv': u'{{subst:Sandldan}}',
    'th': u'{{}}\n<!--  / -- Please leave this line as they are. Thank you! -->',
    'zh': u'{{subst:User:Sz-iwbot/sandbox}}\r\n',
    }

msg = {
    'als':u'Btli: Sandchaschte iigebnet.',
    'ar': u':     ',
    'bar':u'Bot: Spielwiesn gmaht.',
    'cs': u'Uhrabn pskovit',
    'da': u'Bot: Nyt sand (fra[[Skabelon:Sandkasse tekst]])',
    'de': u'Bot: Setze Spielwiese zurck.',
    'en': u'Robot: Automatically cleaned',
    'fa': u':     ',
    'fi': u'Botti siivosi hiekkalaatikon.',
    'he': u':    .',
    'id': u'Bot: Tata ulang',
    'it': u'Bot: pulitura sandbox',
    'ja': u': ',
    'ko': u':  ',
    'ksh':u'Bot: allt Zeush fott gedunn.',
    'nds':u'Bot: Speelwisch leddig maakt.',
    'nl': u'Bot: automatisch voorzien van schoon zand.',
    'no': u'bot: Rydder sandkassa.',
    'pl': u'Robot czyci brudnopis',
    'pt': u'Bot: Limpeza da pgina de testes',
    'commons': u'Bot: This page will automatically be cleaned.',
    'ru': u':  ',
    'sr': u' ',
    'sv': u'Robot krattar sandldan.',
    'th': u': ',
    'zh': u'Bot: ',
    }

sandboxTitle = {
    'als':u'Project:Sandchaschte',
    'ar': u'Project: ',
    'bar':u'Project:Spielwiese',
    'cs': u'Project:Pskovit',
    'da': u'Project:Sandkassen',
    'de': u'Project:Spielwiese',
    'en': u'Project:Sandbox',
    'fa': u'Project: ',
    'fr': u'Project:Bac  sable',
    'fi': u'Project:Hiekkalaatikko',
    'he': u'Project: ',
    'id': u'Project:Bak pasir',
    'it': u'Project:Pagina delle prove',
    'ja': u'Project:',
    'ko': u'Project:',
    'ksh':u'Project:Shpillplaz',
    'nds':u'Project:Speelwisch',
    'nl': u'Project:Zandbak',
    'no': u'Project:Sandkasse',
    'pl': u'Project:Brudnopis',
    'pt': u'Project:Pgina de testes',
    'commons': u'Project:Sandbox',
    'ru': u'Project:',
    'sr': u'Project:',
    'sv': u'Project:Sandldan',
    'th': u'Project:',
    'zh': u'Project:',
    }

class SandboxBot:
    def __init__(self, hours, no_repeat, delay):
        self.hours = hours
        self.no_repeat = no_repeat
        if delay == None:
            self.delay = min(15, max(5, int(self.hours *60)))
        else:
            self.delay = max(5, delay)

    def run(self):
        
        def minutesDiff(time1, time2):
            if type(time1) is long:
                time1 = str(time1)
            if type(time2) is long:
                time2 = str(time2)
            t1 = (((int(time1[0:4])*12+int(time1[4:6]))*30+int(time1[6:8]))*24+int(time1[8:10])*60)+int(time1[10:12])
            t2 = (((int(time2[0:4])*12+int(time2[4:6]))*30+int(time2[6:8]))*24+int(time2[8:10])*60)+int(time2[10:12])
            return abs(t2-t1)

        mySite = pywikibot.getSite()
        while True:
            wait = False
            now = time.strftime("%d %b %Y %H:%M:%S (UTC)", time.gmtime())
            localSandboxTitle = pywikibot.translate(mySite, sandboxTitle)
            if type(localSandboxTitle) is list:
                titles = localSandboxTitle
            else:
                titles = [localSandboxTitle,]
            for title in titles:
                sandboxPage = pywikibot.Page(mySite, title)
                try:
                    text = sandboxPage.get()
                    translatedContent = pywikibot.translate(mySite, content)
                    translatedMsg = pywikibot.translate(mySite, msg)
                    subst = 'subst:' in translatedContent
                    if text.strip() == translatedContent.strip():
                        pywikibot.output(u'The sandbox is still clean, no change necessary.')
                    elif subst and sandboxPage.userName() == mySite.loggedInAs():
                        pywikibot.output(u'The sandbox might be clean, no change necessary.')
                    elif text.find(translatedContent.strip()) <> 0 and not subst:
                        sandboxPage.put(translatedContent, translatedMsg)
                        pywikibot.output(u'Standard content was changed, sandbox cleaned.')
                    else:
                        diff = minutesDiff(sandboxPage.editTime(), time.strftime("%Y%m%d%H%M%S", time.gmtime()))
                        #Is the last edit more than 5 minutes ago?
                        if diff >= self.delay:
                            sandboxPage.put(translatedContent, translatedMsg)
                        else: #wait for the rest
                            pywikibot.output(u'Sleeping for %d minutes.' % (self.delay-diff))
                            time.sleep((self.delay-diff)*60)
                            wait = True
                except pywikibot.EditConflict:
                    pywikibot.output(u'*** Loading again because of edit conflict.\n')
            if self.no_repeat:
                pywikibot.output(u'\nDone.')
                return
            elif not wait:
                if self.hours < 1.0:
                    pywikibot.output('\nSleeping %s minutes, now %s' % ((self.hours*60), now) )
                else:
                    pywikibot.output('\nSleeping %s hours, now %s' % (self.hours, now) )
                time.sleep(self.hours * 60 * 60)

def main():
    hours = 1
    delay = None
    no_repeat = True
    for arg in pywikibot.handleArgs():
        if arg.startswith('-hours:'):
            hours = float(arg[7:])
            no_repeat = False
        elif arg.startswith('-delay:'):
            delay = int(arg[7:])
        else:
            pywikibot.showHelp('clean_sandbox')
            return

    bot = SandboxBot(hours, no_repeat, delay)
    try:
        bot.run()
    except KeyboardInterrupt:
        pywikibot.output('\nQuitting program...')

if __name__ == "__main__":
    try:
        main()
    finally:
        pywikibot.stopme()
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.