User:芯/Codes

This page contains source codes of mine.

API requestsEdit

Byte Counts Data By UserEdit

This is a request to output a table of written byte count data aggregated by user. Save and run as a Python file (extension: .py) with the modification of lines 122 and 123 to update the contents of Drug:Data#Byte Counts by User. You will need to install Python and requests module.

import requests
import time
import datetime
import os
import sys

S = requests.Session()
URL = "https://en.wikiwiki.li/api.php"


def getSize(page):
    params = {
        "action": "query",
        "prop": "revisions",
        "titles": page,
        "rvprop": "size",
        "format": "json"
    }
    data = S.get(url=URL, params=params).json()
    return list(data["query"]["pages"].items())[0][1]["revisions"][0]["size"]


params = {
    "action": "query",
    "list": "logevents",
    "leprop": "title|user|timestamp",
    "leaction": "create/create",
    "lenamespace": 0,
    "lelimit": 500,
    "format": "json"
}
data = S.get(url=URL, params=params).json()
logEvents = data["query"]["logevents"]
while "continue" in data:
    time.sleep(0.5)
    params["lecontinue"] = data["continue"]["lecontinue"]
    data = S.get(url=URL, params=params).json()
    logEvents.append(data["query"]["logevents"])
logEventsLen = len(logEvents)

f = open("lastCheckedTimestamp.txt", 'w')
f.write(logEvents[0]["timestamp"])
f.close()

IPUsers = {
    "172.70.223.86": "ひしょう", "60.145.16.169": "芯"
}
byteCntArrsByUser = {
    "Yuito": [],
    "MediaWiki default": [],
    "キュアラプラプ": [],
    "せうゆ": [],
    "Mapilaplap": [],
    "芯": [],
    "Popbob": [],
    "Notorious": [],
    "しんたろう": [],
    "Long谷": [],
    "神座麟": [],
    "ケツアゴコロロ": [],
    "ひしょう": [],
    "いせ": [],
    "デデ二オン": [],
    "MagnoliaWoolery": [],
    "210.151.113.170": []
}
processed = 0
for le in logEvents:
    creator = le["user"]
    if creator not in byteCntArrsByUser:
        if creator in IPUsers:
            creator = IPUsers[creator]
        else:
            raise Exception("An unknown IP user.")
    byteCntArrsByUser[creator].append(getSize(le["title"]))
    time.sleep(0.5)
    processed += 1
    print("\rlogEvents to byteCntArrsByUser: {:.2f}%".format(
        processed / logEventsLen * 100), end="")

minMaxTtlAvg = {}
for user, data in byteCntArrsByUser.items():
    if data:
        ttl = sum(data)
        avg = round(ttl/len(data), 2)
        sortedData = sorted(data)
        min, max = sortedData[0], sortedData[-1]
        minMaxTtlAvg[user] = [
            str(min) + "  bytes",
            str(max) + "  bytes",
            str(ttl) + "  bytes",
            str(avg) + "  bytes"
        ]
    else:
        minMaxTtlAvg[user] = None

wTable = "{| class=\"wikitable sortable\" style=\"text-align: right;\"\n! User !! style=\"width:7em;\" | Minimum !! style=\"width:7em;\" | Maximum !! style=\"width:7em;\" | Total !! style=\"width:7em;\" | Average"
for user, data in minMaxTtlAvg.items():
    wTable += "\n|-\n! [[User:" + user + "|" + user + "]]"
    if data:
        wTable += "\n| " + data[0] + "\n| " + \
            data[1] + "\n| " + data[2] + "\n| " + data[3]
    else:
        for i in range(4):
            wTable += "\n| style=\"text-align: center;\" | -"
wTable += "\n|}"

now = datetime.datetime.now()
revisionNote = "Last revised at around " + str(now.year) + "/" + str(now.month) + "/" + str(
    now.day) + "/" + str(now.hour) + ":" + str(now.minute) + ":" + str(now.second)

wText = "==Byte Counts by User==\nThis section shows you how many bytes in total the respective users have written as the new contents of standard articles. The source is at: [[User:芯/Codes#Byte Counts Data By User]]\n" + \
    wTable + "\n" + revisionNote

params = {
    "action": "query",
    "meta": "tokens",
    "type": "login",
    "format": "json"
}
LOGIN_TOKEN = S.get(url=URL, params=params).json()[
    "query"]["tokens"]["logintoken"]

params = {
    "action": "login",
    "lgname": [Replace with your bot name],
    "lgpassword": [Replace with your bot password],
    "lgtoken": LOGIN_TOKEN,
    "format": "json"
}
if S.post(URL, data=params).json()["login"]["result"] == "Failed":
    choice = input(
        "\rLogin faild. Still continue with your IP? [y/N]: ").lower()
    if choice in ["yes", "ye", "y"]:
        pass
    elif choice in ["no", "n"]:
        print("\nProcessing has been aborted.")
        sys.exit()

params = {
    "action": "query",
    "meta": "tokens",
    "format": "json"
}
CSRF_TOKEN = S.get(url=URL, params=params).json()[
    "query"]["tokens"]["csrftoken"]

params = {
    "action": "edit",
    "title": "Drug:Data",
    "section": 1,
    "text": wText,
    "summary": "Revised ''Byte Counts by User''",
    "bot": True,
    "token": CSRF_TOKEN,
    "format": "json"
}
print("\n" + str(S.post(URL, data=params).json()))