gpn23-recipes/4_post_to_wiki.py

50 lines
1.3 KiB
Python
Raw Normal View History

2025-06-02 00:24:00 +02:00
import os
import mwclient
2025-06-12 13:40:22 +02:00
import click
2025-06-02 00:24:00 +02:00
import sys
2025-06-02 01:38:40 +02:00
from tqdm import tqdm
2025-06-02 00:24:00 +02:00
from config import *
# Template strings
2025-06-08 21:17:47 +02:00
HIDDEN_COMMENT = "<!-- This page is auto-generated. Do not edit manually. -->"
CATEGORY_TEMPLATE = "\n".join(
"[[Category:{0}]]".format(cat) for cat in WIKI_CATEGORY_LIST
)
2025-06-02 00:24:00 +02:00
# Connect to MediaWiki
site = mwclient.Site(WIKI_HOST, path=WIKI_PATH)
2025-06-02 21:17:59 +02:00
site.login(WIKI_USERNAME, WIKI_PASSWORD)
2025-06-02 00:24:00 +02:00
2025-06-12 13:40:22 +02:00
@click.command()
@click.argument('files', nargs=-1)
def post(files):
if files[0] == "all":
files = []
for filename in tqdm(os.listdir(OUTDIR_MEDIAWIKI)):
if filename.endswith(".mediawiki"):
filepath = os.path.join(OUTDIR_MEDIAWIKI, filename)
files.append(filepath)
for filepath in files:
if OUTDIR_MEDIAWIKI not in filepath:
raise ValueError("{filepath} not in {OUTDIR_MEDIAWIKI}")
2025-06-12 13:40:22 +02:00
filename = os.path.basename(filepath)
2025-06-08 21:17:47 +02:00
article_name = WIKI_ARTICLE_PREFIX + filename.replace(".mediawiki", "")
2025-06-02 00:24:00 +02:00
2025-06-08 21:17:47 +02:00
with open(filepath, "r", encoding="utf-8") as f:
2025-06-02 00:24:00 +02:00
content = f.read()
# Compose final content
final_content = f"{HIDDEN_COMMENT}\n\n{content}\n\n{CATEGORY_TEMPLATE}"
# Post to MediaWiki
page = site.pages[article_name]
2025-06-12 13:40:22 +02:00
page.save(final_content, summary="U+1F916 ROBOT FACE")
if __name__ == "__main__":
post()