Gebruiker:Bitbotje/nl-mod-activiteit.py

# -*- coding: utf-8 -*-
# Author Simon Bijl, Edo de Roo, bdijkstra
# 2015, MIT-License

import sys
import datetime
from datetime import datetime, date, time, timedelta
from itertools import islice
import pywikibot
from pywikibot.data.api import ListGenerator
import urllib
import csv

debugmode = False
site = pywikibot.Site('nl')
editLimit = 500

now = site.server_time()
oneYearAgo = now.replace(now.year - 1) + timedelta(days=14)

def main():
    pywikibot.output(oneYearAgo)
    botAltData = urllib.request.urlopen('https://nl.wikipedia.org/w/index.php?title=Gebruiker:Wutsje/tmp&oldid=61851161&action=raw')
    # skip 1st 2 lines
    botAltData.__next__()
    botAltData.__next__()
    botDict = {}
    altDict = {}
    for row in csv.reader([l.decode('utf-8') for l in botAltData.readlines()]):
        main = row[0]
        if main == '</pre>':
            break
        bots = row[1]
        if bots and len(bots) > 0:
            botDict[main] = bots.split(', ')
        alts = row[2]
        if alts and len(alts) > 0:
            altDict[main] = alts.split(', ')

    wikiString = (u'Onderstaande tabel geeft een indicatie van de activiteit ' +
        'van een moderator. De vermelde aantallen zijn het aantal ' + 
        'niet-verwijderde bijdragen van de moderator in de afgelopen 351 '
        'dagen, welke wel meetellen bij het afwegen van het ' +
        'activiteitscriterium dat is vastgesteld in de ' +
        '[[Wikipedia:Regelingen rond moderatoren|Wikipedia:Regelingen rond ' +
        'moderatoren]]. Bij een activiteit onder de 250 edits in 365 dagen ' +
        'mag, onder voorwaarden, een aanvraag worden ingediend ter ' + 
        'verwijdering van de moderatorrechten.<br>\n' +
        'Alleen moderatoren met minder dan %d niet-verwijderde ' +
        'bijdragen worden getoond. In de kolommen ernaast wordt een ' +
        'indicatie gegeven van respectievelijk moderatorhandelingen ' + 
        '(beveiliging, blokkering, verwijdering), vandalismebestrijding ' +
        '(markeringen) en bijdragen van aangemelde bots en sokpoppen.\n\n' +
        'Laatste update: {{subst:#timel:Y-m-d H:i (T)}}.\n\n' +
        '{| class="wikitable sortable" style="text-align:right"\n' +
        '! Gebruiker || Bijdragen || Modacties || Markeringen || ' +
        'Bot-<br>bijdragen || Alt-<br>bijdragen\n'
        ) % editLimit
    sysopNames = getSysopNames() # Get sysop list

    # Process for each sysop:
    for username in sysopNames:
        edits = lastYearEditCount(username)
        if edits < editLimit:
            actions = formatCount(lastYearSysopActionCount(username))
            patrols = formatCount(lastYearPatrolCount(username))
            botEdits = 0
            if username in botDict:
                for bot in botDict[username]:
                    botEdits += lastYearEditCount(bot)
            botEdits = formatCount(botEdits)
            altEdits = 0
            if username in altDict:
                for alt in altDict[username]:
                    altEdits += lastYearEditCount(alt)
            altEdits = formatCount(altEdits)
            tableRow = (u'|-\n| style="text-align:left" | {{lg|%(u)s}}\n' +
                '| %(ec)s\n' +
                '| %(a)s\n' +
                '| %(p)s\n' +
                '| %(be)s\n'
                '| %(ae)s\n') % {'u':username, 'ec':edits, 'a':actions, 
                                 'p':patrols, 'be':botEdits, 'ae':altEdits}
            wikiString += tableRow
            if debugmode:
                pywikibot.output(tableRow)
    wikiString += u'|}\n\n[[Categorie:Wikipedia:Moderatoren]]\n'
 
    if not debugmode: 
        pywikibot.Page(site, u'Wikipedia:Regelingen_rond_moderatoren/Activiteit_moderatoren').put(wikiString, summary=u'Update') #Save page

# Returns the user's number of (non-deleted) edits in the last year,
# capped at `editLimit`+2
def lastYearEditCount(username):
    user = pywikibot.User(site, username)
    contributions = user.contributions(total=editLimit+2, end=oneYearAgo)
    editCount = 0
    for contribution in contributions:
        editCount += 1
    return editCount

def lastYearLogEventCount(username, logtype):
    user = pywikibot.User(site, username)
    logevents = user.logevents(
                            logtype=logtype, total=editLimit+2, end=oneYearAgo)
    count = 0
    try:
        for logevent in logevents:
            count += 1
    except pywikibot.exceptions.HiddenKeyError:
        # T78152
        count += 1
        pywikibot.output("HiddenKeyError: user=%s logtype=%s" % (
                                                            username, logtype))
    return count

def lastYearSysopActionCount(username):
    return (lastYearLogEventCount(username, 'block') +
            lastYearLogEventCount(username, 'protect') +
            lastYearLogEventCount(username, 'delete') +
            lastYearLogEventCount(username, 'contentmodel'))

def lastYearPatrolCount(username):
    return lastYearLogEventCount(username, 'patrol')

# Returns list with usernames of all sysops active on site
def getSysopNames():
    array = []
    users = ListGenerator('allusers', site=site, augroup='sysop')
    for user in users:
        array.append(user['name'])
    return array

def formatCount(i):
    if i > editLimit:
        i = "> %d" % editLimit
    return i

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