User:Wikimodels Wikibot (Python)/code

"""   upload_file_directly.py

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

MIT license (c) 2007-2021 MediaWiki API documentation editors, list at https://www.mediawiki.org/w/index.php?title=API:Upload&action=history """ print("This Wikibot does not require login.") print("Loading...") try: import requests except ImportError:  import os  os.system("python -m pip install requests") S = requests.Session print("Setting api url...") URL = "https://wikimodels.miraheze.org/w/api.php" from tkinter import filedialog types = (        ('Models', '*.stl'), ) from tkinter import filedialog as fd print("Ignore the blank tkinter window, use the newly opened 'Open' window!") FILE_PATH = fd.askopenfilename(  title="Select model to upload",  filetypes=types )

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

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

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

PARAMS_2 = { "action": "login", "lgname": "Wikimodels Wikibot (Python)", "lgpassword": "wikibot1", "format": "json", "lgtoken": LOGIN_TOKEN }
 * 1) Step 2: Send a post request to login. Use of main account for login is not
 * 2) supported. Obtain credentials via Special:BotPasswords
 * 3) (https://www.mediawiki.org/wiki/Special:BotPasswords) for lgname & lgpassword

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

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

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

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

PARAMS_4 = { "action": "upload", "filename": FILE_PATH, "format": "json", "token": CSRF_TOKEN, "ignorewarnings": 1 }
 * 1) Step 4: Post request to upload a file directly

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

R = S.post(URL, files=FILE, data=PARAMS_4) DATA = R.json print("Done, if no errors triggered, the file should be on commons.\n(Remember to add a Wikimodels compliant copyright tag.)") print("JSON output:\n" + DATA) input("Press Enter to exit... ")