Участник:Drbug/KPUploadBot

Материал c сайта НП «Викимедиа РУ»
Перейти к навигации Перейти к поиску


"""
    Based on: upload_file_directly.py

    MediaWiki API Demos
    Demo of `Upload` module: Sending post request to upload a file directly

    MIT license
"""

import os
import requests
import time

S = requests.Session()
URL = "https://commons.wikimedia.org/w/api.php"
DIR_PATH = 'C:/Users/Asus/Documents/Code/python/koms/import/'

# Step 1: Retrieve a login token
PARAMS_1 = {
    "action": "query",
    "meta": "tokens",
    "type": "login",
    "format": "json"
}

R = S.get(url=URL, params=PARAMS_1)
DATA = R.json()

LOGIN_TOKEN = DATA["query"]["tokens"]["logintoken"]

# Step 2: Send a post request to login. Use of main account for login is not
# supported. Obtain credentials via Special:BotPasswords
# (https://www.mediawiki.org/wiki/Special:BotPasswords) for lgname & lgpassword
PARAMS_2 = {
    "action": "login",
    "lgname": "Drbug@DrBugUploaderBot",
    "lgpassword": "7jsgdhk3lfgb5ks87asbvohm9oi2hog7",
    "format": "json",
    "lgtoken": LOGIN_TOKEN
}

R = S.post(URL, data=PARAMS_2)

# Step 3: Obtain a CSRF token
PARAMS_3 = {
    "action": "query",
    "meta":"tokens",
    "format":"json"
}

R = S.get(url=URL, params=PARAMS_3)
DATA = R.json()

CSRF_TOKEN = DATA["query"]["tokens"]["csrftoken"]

for root, dirs, files in os.walk(DIR_PATH):
    for f in files:
        fs = f.split("-")
        print(root, dirs, fs)

# Step 4: Post request to upload a file directly
        date = fs[3] + "." + fs[2] + "." + fs[1]
        PARAMS_4 = {
            "action": "upload",
            "filename": "Komsomolskaya-Pravda-" + f,
            "comment": "Комсомольская правда, " + date,
            "text": "=={{int:filedesc}}==\n{{Information\n|description={{ru|1=Выпуск газеты \"Комсомольская правда\" за " + date + "}}\n|date=" + fs[1] + "-" + fs[2] + "-" + fs[3] + "\n|source=Комсомольская правда от " + date + "\n|author=Правообладатель - АО \"ИД \"Комсомольская правда\"\n|permission=\n|other versions=\n}}\n\n=={{int:license-header}}==\n{{Komsomolskaya Pravda |license= |author= |number=от " + date + "\n|category= }}\n\n[[Category:Newspapers of Russia]]\n[[Category:Great Patriotic War]]\n",
            "format": "json",
            "token": CSRF_TOKEN,
            "ignorewarnings": 1
        }


        FILE = {'file':(f, open(DIR_PATH + f, 'rb'), 'multipart/form-data')}

        print(date, PARAMS_4, FILE)

        R = S.post(URL, files=FILE, data=PARAMS_4)
        DATA = R.json()
        print(DATA)

        time.sleep(10)