「利用者:芯/サンドボックス/6」の版間の差分

編集の要約なし
10行目: 10行目:
import time
import time
import datetime
import datetime
import os
import sys
import sys


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


def getLogs(usr=False, action=False, ns=None):
    PARAMS = [{
        "action": "query",
        "list": "logevents",
        "leprop": "title|type|user",
        "lelimit": 500,
        "format": "json"
    }]
    if usr:
        PARAMS[0]["leuser"] = usr
    if action:
        PARAMS[0]["leaction"] = action
    if ns != None:
        PARAMS[0]["lenamespace"] = ns
    R = [S.get(url=URL, params=PARAMS[0])]
    DATA = [R[0].json()]
    output = DATA[0]["query"]["logevents"]
    flg = False
    if "continue" in DATA[0]:
        flg = True
    while flg:
        PARAMS.append({
            "action": "query",
            "list": "logevents",
            "lecontinue": DATA[-1]["continue"]["lecontinue"],
            "leprop": "title|type|user",
            "lelimit": 500,
            "format": "json"
        })
        if usr:
            PARAMS[-1]["leuser"] = usr
        if action:
            PARAMS[-1]["leaction"] = action
        R.append(S.get(url=URL, params=PARAMS[-1]))
        DATA.append(R[-1].json())
        output += DATA[-1]["query"]["logevents"]
        if "continue" not in DATA[-1]:
            flg = False
    return output
def isRedir(page):
    PARAMS = {
    "action": "parse",
    "page": page,
    "prop": "wikitext",
    "format": "json"
    }
    R = S.get(url=URL, params=PARAMS)
    DATA = R.json()
    cont = DATA["parse"]["wikitext"]["*"].lower()
    if "#転送" in cont or "#redirect" in cont:
        return True
    else:
        return False


def getSize(page):
def getSize(page):
     PARAMS = {
     params = {
         "action": "query",
         "action": "query",
         "prop": "revisions",
         "prop": "revisions",
79行目: 25行目:
         "format": "json"
         "format": "json"
     }
     }
     R = S.get(url=URL, params=PARAMS)
     data = S.get(url=URL, params=params).json()
    DATA = R.json()
     return list(data["query"]["pages"].items())[0][1]["revisions"][0]["size"]
     pageid = list(DATA["query"]["pages"])[0]
 
     return DATA["query"]["pages"][pageid]["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 = {
IPUsers = {
     "172.70.223.86": "ひしょう", "60.145.16.169": "芯"
     "172.70.223.86": "ひしょう", "60.145.16.169": "芯"
}
}
 
byteCntArrsByUser = {
createLogs = getLogs(action="create/create", ns=0)
     "Yuito": [],
createLogsLen = len(createLogs)
    "MediaWiki default": [],
pageDataByUser = {
    "キュアラプラプ": [],
     "Yuito": [], "MediaWiki default": [], "キュアラプラプ": [], "せうゆ": [],
    "せうゆ": [],
     "Mapilaplap": [], "芯": [], "Popbob": [], "Notorious": [], "しんたろう": [], "Long谷": [],
     "Mapilaplap": [],
     "神座麟": [], "ケツアゴコロロ": [], "ひしょう": [], "いせ": [], "デデ二オン": [],
    "芯": [],
     "MagnoliaWoolery": [], "210.151.113.170": []
    "Popbob": [],
    "Notorious": [],
    "しんたろう": [],
    "Long谷": [],
     "神座麟": [],
    "ケツアゴコロロ": [],
    "ひしょう": [],
    "いせ": [],
    "デデ二オン": [],
     "MagnoliaWoolery": [],
    "210.151.113.170": []
}
}
processed = 0
processed = 0
for lg in createLogs:
for le in logEvents:
     creator = lg["user"]
     creator = le["user"]
     if creator not in pageDataByUser:
     if creator not in byteCntArrsByUser:
         if creator in IPUsers:
         if creator in IPUsers:
             creator = IPUsers[creator]
             creator = IPUsers[creator]
         else:
         else:
             raise Exception("An unknown IP user.")
             raise Exception("An unknown IP user.")
     if not isRedir(lg["title"]):
     byteCntArrsByUser[creator].append(getSize(le["title"]))
        pageDataByUser[creator].append({"title": lg["title"], "size": getSize(lg["title"])})
    time.sleep(0.5)
        time.sleep(0.5)
     processed += 1
     processed += 1
     print("\rpageDataByUser: {:.2f}%".format(processed/createLogsLen*100), end="")
     print("\rlogEvents to byteCntArrsByUser: {:.2f}%".format(
 
        processed / logEventsLen * 100), end="")
byteCnt = {}
for usr, data in pageDataByUser.items():
    byteCnt[usr] = []
    for page in data:
        byteCnt[usr].append(page["size"])


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


wTable = "{| class=\"wikitable sortable\" style=\"text-align: right;"
wTable = "{| class=\"wikitable sortable\" style=\"text-align: right;\"\n! 利用者名 !! style=\"width:7em;\" | 最小値 !! style=\"width:7em;\" | 最大値 !! style=\"width:7em;\" | 合計値 !! style=\"width:7em;\" | 平均値"
wTable += "\"\n! 利用者名 !! style=\"width:7em;\" | 最小値 !! style=\"width:7em;\" | 最大値 !! style=\"width:7em;\" | 合計値 !! style=\"width:7em;\" | 平均値"
for user, data in minMaxTtlAvg.items():
for usr, data in minMaxTtlAvg.items():
     wTable += "\n|-\n! [[利用者:" + user + "|" + user + "]]"
     wTable += "\n|-\n! [[利用者:" + usr + "|" + usr + "]]"
     if data:
     if data:
         wTable += "\n| " + data[0] + "\n| " + data[1] + "\n| " + data[2] + "\n| " + data[3]
         wTable += "\n| " + data[0] + "\n| " + \
            data[1] + "\n| " + data[2] + "\n| " + data[3]
     else:
     else:
         for i in range(4):
         for i in range(4):
144行目: 115行目:


now = datetime.datetime.now()
now = datetime.datetime.now()
revision = "最終更新日時: " + str(now.year) + "/" + str(now.month) + "/" + str(now.day) + "/" + str(now.hour) + ":" + str(now.minute) + " 頃"
revisionNote = "最終更新日時: " + str(now.year) + "/" + str(now.month) + "/" + str(
    now.day) + "/" + str(now.hour) + ":" + str(now.minute) + ":" + str(now.second) + " 頃"


wText = "==利用者別バイト数データ==\n本節では、各々の利用者が作成してきた標準記事(リダイレクトを除く)のバイト数について、その代表値を表示する。ソース: [[利用者:芯/サンドボックス/6#利用者別バイト数データ]]\n"
wText = "==利用者別バイト数データ==\n本節では、各々の利用者が作成してきた標準記事(リダイレクトを除く)のバイト数について、その代表値を表示する。ソース: [[利用者:芯/サンドボックス/6#利用者別バイト数データ]]\n" + \
wText += wTable + "\n" + revision
    wTable + "\n" + revisionNote


PARAMS_0 = {
params = {
     "action": "query",
     "action": "query",
     "meta": "tokens",
     "meta": "tokens",
155行目: 127行目:
     "format": "json"
     "format": "json"
}
}
R = S.get(url=URL, params=PARAMS_0)
LOGIN_TOKEN = S.get(url=URL, params=params).json()[
DATA = R.json()
    "query"]["tokens"]["logintoken"]
LOGIN_TOKEN = DATA["query"]["tokens"]["logintoken"]


myname = # 自分のボットアカウントを表す文字列を入力せよ
params = {
mypass = # 自分のボットパスワードを表す文字列を入力せよ
PARAMS_1 = {
     "action": "login",
     "action": "login",
     "lgname": myname,
     "lgname": "芯@bot芯",
     "lgpassword": mypass,
     "lgpassword": os.environ["BotPass"],
     "lgtoken": LOGIN_TOKEN,
     "lgtoken": LOGIN_TOKEN,
     "format": "json"
     "format": "json"
}
}
R = S.post(URL, data=PARAMS_1)
if S.post(URL, data=params).json()["login"]["result"] == "Failed":
DATA = R.json()
     choice = input(
if DATA["login"]["result"] == "Failed":
        "\rLogin faild. Still continue with your IP? [y/N]: ").lower()
     choice = input("\rLogin faild. Still continue with your IP? [y/N]: ").lower()
     if choice in ["yes", "ye", "y"]:
     if choice in ["yes", "ye", "y"]:
         pass
         pass
     elif choice in ["no", "n"]:
     elif choice in ["no", "n"]:
         print("Processing has been aborted.")
         print("\nProcessing has been aborted.")
         sys.exit()
         sys.exit()


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


PARAMS_3 = {
params = {
     "action": "edit",
     "action": "edit",
     "title": "麻薬:データ",
     "title": "麻薬:データ",
     "section":1,
     "section": 1,
     "text": wText,
     "text": wText,
     "summary": "利用者別バイト数データを更新",
     "summary": "利用者別バイト数データを更新",
    "bot": True,
     "token": CSRF_TOKEN,
     "token": CSRF_TOKEN,
     "format": "json"
     "format": "json"
}
}
R = S.post(URL, data=PARAMS_3)
print("\n" + str(S.post(URL, data=params).json()))
print(R.json())
</pre>}}
</pre>}}
3,314

回編集