welcome.py 6.3 KB
Newer Older
1 2 3 4 5
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Script d'accueil pour vikidia


Linedwell's avatar
Linedwell committed
6
# (C) Linedwell, 2011-2018
7 8 9 10 11 12 13 14 15 16
#
# Distribué sous licence GNU GPLv3
# Distributed under the terms of the GNU GPLv3 license
# http://www.gnu.org/licenses/gpl.html

import sys, getopt
sys.path.insert(1, '..') #ajoute au PYTHONPATH le répertoire parent

import mylogging

Linedwell's avatar
Linedwell committed
17
import re
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
from datetime import timedelta

from random import choice

import pywikibot
from pywikibot import i18n
from pywikibot.tools.formatter import color_format

import callback
import logger


# Déclarations

globalsettings = {
Linedwell's avatar
Linedwell committed
33 34 35 36 37
    'reqEditCount' : 1,         #number of edits required to welcome an user
    'timeoffset' : 60,          #skip users newer than # minutes
    'defaultSign' : '--~~~~',   #default signature
    'randomSign' : False,       #pick a random signature instead of default
    'queryLimit' : 50,          #number of users loaded by the bot
38 39 40 41 42 43 44
}

welcomemsg = {
    'fr' : u'{{Bienvenue}}%s',
    'it' : u'{{Benvenuto}}%s',
}

Linedwell's avatar
Linedwell committed
45 46 47 48 49 50 51 52
welcomeschoolmsg = {
    'fr' : u'{{Bienvenue école}}%s',
}

schooldiscriminator = {
    'fr' : ur'coll[eè]ge|[eé]cole|cdi|lyc[eé]|prof',
}

53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
welcomelog = {
    'fr' : u'User:LinedBot/Welcome/Log',
    'it' : u'User:LinedBot/Welcome/Log',
}

random_sign = {
    'fr' : u'User:LinedBot/Welcome/Signatures',
    'it' : u'User:LinedBot/Welcome/Firme',
    #'it' : u'wp:Wikipedia:Benvenuto Bot/Firme',
}

class WelcomeBot:

    # bot initialization
    def __init__(self,viki):
        self.site = pywikibot.Site(viki,'vikidia')
        self.checkManagedSites()
        if globalsettings['randomSign']:
Linedwell's avatar
Linedwell committed
71
            self.signList = self.getSignList()
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
        self.welcomed_users = list()    

    # chek if "autowelcome" is enabled or not on the wiki
    def checkManagedSites(self):
        wlcmsg = i18n.translate(self.site, welcomemsg)
        if wlcmsg is None:
            raise KeyError(
                'welcome.py is not localized for site {0} in welcomemsg dict.'
                ''.format(self.site))    
    
    # random list of signatures used for the welcome message
    def getSignList(self):
        signPageName = creg = i18n.translate(self.site, random_sign)
        if not signPageName:
            pywikibot.output("Random signature disabled on %s; disabling random sign" % self.site)
Linedwell's avatar
Linedwell committed
87
            globalsettings['randomSign'] = False
88 89
            return

Linedwell's avatar
Linedwell committed
90
        signPage = pywikibot.Page(self.site, signPageName)
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110

        if signPage.exists():
            sign = u''
            creg = re.compile(r"^\* ?(.*?)$", re.M)
            signText = signPage.get()
            return creg.findall(signText)
        else:
            pywikibot.output("The random signature list doesn't exist; disabling random sign")
            globalsettings['randomSign'] = False
            return

    # retrieve new users list
    def parseNewUserLog(self):
        start = self.site.server_time() - timedelta(minutes=globalsettings['timeoffset'])
        for ue in self.site.logevents('newusers', total=globalsettings['queryLimit'], start=start):
            yield pywikibot.User(ue.page())


    def run(self):
        for user in self.parseNewUserLog():
Linedwell's avatar
Linedwell committed
111 112
            #print user.name()
            if user.isBlocked():
113
                #showStatus(3)
Linedwell's avatar
Linedwell committed
114
                pywikibot.output(u"%s is blocked; skipping." % user.name())
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
                continue
            if "bot" in user.groups():
                #showStatus(3)
                pywikibot.output(u"%s is a bot; skipping." % user.name())
                continue
            if "bot" in user.name().lower():
                #showStatus(3)
                pywikibot.output(u"%s is probably a bot; skipping." % user.name())
                continue
            if user.editCount() >= globalsettings['reqEditCount']:
                #showStatus(2)
                pywikibot.output(u"%s has enough edits to be welcomed." % user.name())
                ustp =  user.getUserTalkPage()
                if ustp.exists():
                    #showStatus(3)
                    pywikibot.output(u"%s has been already welcomed; skipping." % user.name())
                    continue
                else:
                    welcome_text = i18n.translate(self.site, welcomemsg)
Linedwell's avatar
Linedwell committed
134 135 136 137 138 139
                    welcome_school_text = i18n.translate(self.site, welcomeschoolmsg)
                    if welcome_school_text != None:
                        discrim = i18n.translate(self.site, schooldiscriminator)
                        if discrim != None and re.match(discrim, user.name().lower()): #if the discriminator exists and is present in username
                            pywikibot.output(u"%s is a maybe a school related account; using school welcoming templatei instead." % user.name())
                            welcome_text = welcome_school_text
140
                    if globalsettings['randomSign'] and len(self.signList) > 0:
Linedwell's avatar
Linedwell committed
141 142
                        sign = choice(self.signList)
                    else:
143 144 145 146 147
                        sign = globalsettings['defaultSign']

                    welcome_text = (welcome_text % sign)
                    welcome_cmnt = u"Robot: " + i18n.twtranslate(self.site,'welcome-welcome')

Linedwell's avatar
Linedwell committed
148
                    #print welcome_text
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
                    #print welcome_cmnt
                    ustp.text = welcome_text
                    
                    try:
                        ustp.save(welcome_cmnt,minor=False)
                        pass
                    except pywikibot.EditConflict:
                        pywikibot.output(u"An edit conflict has occurred, "
                                             u"skipping %s." % user.name())


def showStatus(n=0):
    """Output colorized status."""
    staColor = {
        0: 'lightpurple',
        1: 'lightaqua',
        2: 'lightgreen',
        3: 'lightyellow',
        4: 'lightred',
        5: 'lightblue'
    }
    staMsg = {
        0: 'MSG',
        1: 'NoAct',
        2: 'Match',
        3: 'Skip',
        4: 'Warning',
        5: 'Done',
    }
    pywikibot.output(color_format('{color}[{0:5}]{default} ',
                                  staMsg[n], color=staColor[n]), newline=False)

# Exécution
def main():
    
    site = sys.argv[1]
    try:
        wb = WelcomeBot(site)
    except KeyError as error:
        # site not managed by welcome.py
        pywikibot.error(error)
        return False
    wb.run()

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