Skip to content

Commit 56548be

Browse files
committed
Add task11 prototype code
1 parent dd009af commit 56548be

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

tsb_task_11.py

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
import pywikibot
2+
import requests
3+
from datetime import datetime
4+
5+
class SwapCategories:
6+
7+
def __init__(self, category_name, site):
8+
self.category_name = category_name
9+
self.site = site
10+
self.edit_count = 0
11+
self.max_edits = 5
12+
self.BASE_URL = "https://en.wikipedia.org/w/api.php"
13+
14+
def get_formatted_timestamp(self, timestamp):
15+
return datetime.strptime(timestamp, '%Y-%m-%dT%H:%M:%SZ').strftime('%B %Y')
16+
17+
def update_page_category(self, member):
18+
timestamp = self.get_formatted_timestamp(member['timestamp'])
19+
page = pywikibot.Page(self.site, member['title'])
20+
text = page.text
21+
old_category = '[[Category:Wikipedia usernames with possible policy issues]]'
22+
new_category = f'[[Category:Wikipedia usernames with possible policy issues from {timestamp}]]'
23+
24+
if old_category in text:
25+
text = text.replace(old_category, new_category)
26+
page.text = text
27+
page.save(f"Moved from 'Wikipedia usernames with possible policy issues' to 'Category:Wikipedia usernames with possible policy issues from {timestamp}'")
28+
self.edit_count += 1
29+
30+
def run_bot(self):
31+
PARAMS = {
32+
"action": "query",
33+
"format": "json",
34+
"list": "categorymembers",
35+
"cmtitle": self.category_name,
36+
"cmprop": "ids|title|timestamp",
37+
"cmnamespace": "3",
38+
"cmsort": "timestamp",
39+
"cmdir": "newer",
40+
"cmlimit": "500"
41+
}
42+
43+
while self.edit_count < self.max_edits:
44+
response = requests.get(self.BASE_URL, params=PARAMS)
45+
data = response.json()
46+
members = data.get('query', {}).get('categorymembers', [])
47+
48+
for member in members:
49+
if self.edit_count >= self.max_edits:
50+
return
51+
self.update_page_category(member)
52+
53+
if 'continue' in data and 'cmcontinue' in data['continue']:
54+
PARAMS['cmcontinue'] = data['continue']['cmcontinue']
55+
else:
56+
break
57+
58+
59+
if __name__ == "__main__":
60+
# Initialize the site object for English Wikipedia.
61+
site = pywikibot.Site("en", "wikipedia")
62+
bot = SwapCategories("Category:Wikipedia usernames with possible policy issues", site)
63+
bot.run_bot()

0 commit comments

Comments
 (0)