User:GalaxyBot/Task2.py
Appearance
"""
Copyright (c) 2025 DreamRimmer
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
"""
import pywikibot
from datetime import datetime, timedelta
from collections import defaultdict
import re
active_p = "Wikipedia:List of administrators/Active"
semiactive_p = "Wikipedia:List of administrators/Semi-active"
inactive_p = "Wikipedia:List of administrators/Inactive"
admin_list_p = "Wikipedia:List of administrators"
def normalise_date(date_str):
if not date_str:
return None
try:
if "T" in date_str and "Z" in date_str:
date = datetime.strptime(date_str.split("T")[0], "%Y-%m-%d")
else:
parts = date_str.split(", ")[1].split(" ")
date = datetime.strptime(f"{parts[2]} {parts[1]} {parts[0]}", "%Y %B %d")
return date.strftime("%d %B %Y")
except Exception as e:
print(f"Error processing date: {date_str}, error: {e}")
raise
def last_day_of_month(year, month):
if month == 12:
return (datetime(year + 1, 1, 1) - timedelta(days=1)).day
else:
return (datetime(year, month + 1, 1) - timedelta(days=1)).day
def is_inactive(latest_contrib, today):
contrib_date = datetime.strptime(latest_contrib, "%d %B %Y")
return (today - contrib_date).days > 90
def is_semi_active(thirtieth_contrib, today):
contrib_date = datetime.strptime(thirtieth_contrib, "%d %B %Y")
return (today - contrib_date).days > 60
def fetch_admin_data():
site = pywikibot.Site("wikipedia:en")
today = datetime.today()
inactive_admins = []
semi_active_admins = []
active_admins = defaultdict(list)
admins = list(site.allusers(group="sysop"))
for admin in admins:
username = admin["name"]
contribs = site.usercontribs(user=username, total=30)
contrib_dates = [normalise_date(contrib["timestamp"]) for contrib in contribs]
if not contrib_dates:
continue
latest_contrib = contrib_dates[0]
thirtieth_contrib = contrib_dates[-1] if len(contrib_dates) >= 30 else None
if is_inactive(latest_contrib, today):
days_inactive = (today - datetime.strptime(latest_contrib, "%d %B %Y")).days
inactive_admins.append((username, days_inactive, latest_contrib))
elif thirtieth_contrib and is_semi_active(thirtieth_contrib, today):
semi_active_admins.append(username)
else:
first_char = username[0].upper()
if not first_char.isalpha():
first_char = '#'
active_admins[first_char].append(username)
inactive_t = "\n".join(
f"# {{{{user3|{username}}}}} - {latest_contrib}"
for username, days_inactive, latest_contrib in sorted(inactive_admins, key=lambda x: x[1], reverse=True)
)
semi_active_t = "\n".join(f"# {{{{user3|{username}}}}}" for username in sorted(semi_active_admins))
active_t = ""
for letter in sorted(active_admins.keys()):
active_t += f"==={letter}===\n"
for username in sorted(active_admins[letter]):
active_t += f"# {{{{user3|{username}}}}}\n"
active_t += "\n"
def update_page(title, new_content, admin_counts):
page = pywikibot.Page(site, title)
existing_content = page.text
start_marker = "<!-- List of administrators start -->"
end_marker = "<!-- List of administrators end -->"
if start_marker in existing_content and end_marker in existing_content:
updated_content = existing_content.split(start_marker)[0] + start_marker + "\n" + new_content + "\n" + end_marker + existing_content.split(end_marker)[1]
else:
print(f"Markers not found in {title}.")
return
#pywikibot.showDiff(existing_content, updated_content, context=50)
if title == active_p:
summary = f"{admin_counts['active']} active admins (bot)"
elif title == semiactive_p:
summary = f"{admin_counts['semi_active']} semi-active admins (bot)"
elif title == inactive_p:
summary = f"{admin_counts['inactive']} inactive admins (bot)"
page.text = updated_content
page.save(summary=summary, minor=False, bot=True)
admin_counts = {
'active': sum(len(usernames) for usernames in active_admins.values()),
'semi_active': len(semi_active_admins),
'inactive': len(inactive_admins)
}
update_page(active_p, active_t, admin_counts)
update_page(semiactive_p, semi_active_t, admin_counts)
update_page(inactive_p, inactive_t, admin_counts)
update_admin_list(admin_list_p, admin_counts)
def update_admin_list(title, admin_counts):
site = pywikibot.Site("wikipedia:en")
page = pywikibot.Page(site, title)
existing_content = page.text
today_str = datetime.today().strftime("%Y-%m-%d")
active_pattern = re.compile(r"(\d+) of them active \(as of \d{4}-\d{2}-\d{2}\)")
new_active_text = f"{admin_counts['active']} of them active (as of {today_str})"
updated_content = active_pattern.sub(new_active_text, existing_content)
checked_pattern = re.compile(r"Sysop activity status last checked on \d{4}-\d{2}-\d{2}")
new_checked_text = f"Sysop activity status last checked on {today_str}"
updated_content = checked_pattern.sub(new_checked_text, updated_content)
#pywikibot.showDiff(existing_content, updated_content, context=50)
page.text = updated_content
page.save(summary=f"{admin_counts['active']} active admins (bot)", minor=False, bot=True)
if __name__ == "__main__":
fetch_admin_data()