(Translated by https://www.hiragana.jp/)
User:TolBot/Task 10 - Meta Jump to content

User:TolBot/Task 10

From Meta, a Wikimedia project coordination wiki
TolBot: Task 10
Status  Approved (inactive)
Wiki w:en:
Summary Create redirects from titles without middle initials
Page(s) Namespace (?): 1
Period one-time
Language Python
Supervision automatic
  • Completed (11–14 Jan 2022)
    • Further runs possible; please enquire on talk.

Source

[edit]
Extended content
import json
import re
import requests
import time

api = 'https://en.wikipedia.org/w/api.php'
username = ''
password = ''

summary_prefix = '[[m:User:TolBot/Task 10|Task 10]]: '
summary = summary_prefix + 'create redirect from title without middle initial ([[{first} {last}]] to [[{first} {initial}. {last}]])'

pattern = re.compile(r'([A-Z][a-zA-Z]+) ([A-Z])\. ([A-Z][a-zA-Z]+)')

redirect_title = '{first} {last}'
redirect_text = '#REDIRECT [[{first} {initial}. {last}]]\n\n{{{{Redirect category shell|1=\n{{{{DEFAULTSORT:{last}, {first}}}}}\n{{{{R from short name}}}}\n}}}}'

def api_request(api, session, params, maxlag = 3, timeout = 300):
  params['format'] = 'json'
  params['formatversion'] = 2
  params['maxlag'] = maxlag
  query = session.post(api, data = params).json()
  sleep = 5
  while (
    ('error' in query) and
    (query['error']['code'] in {'maxlag', 'ratelimited'})
  ):
    time.sleep(sleep)
    query = session.post(api, data = params).json()
    sleep *= 2
    if sleep > timeout:
      raise ConnectionError('Server timed out')
  return query

def login(api, username, password):
  session = requests.Session()
  query = api_request(
    api,
    session,
    {
      'action': 'login',
      'lgname': username,
      'lgpassword': password,
      'lgtoken': api_request(
        api,
        session,
        {
          'action': 'query',
          'meta': 'tokens',
          'type': 'login'
        }
      )['query']['tokens']['logintoken']
    }
  )
  if query['login']['result'] == 'Success':
    return session
  else:
    raise ConnectionError('Login failed: ' + str(query))

def create(api, session, title, text, summary):
  query = api_request(
    api,
    session,
    {
      'action': 'edit',
      'assert': 'bot',
      'title': title,
      'summary': summary,
      # 'bot': True,
      'createonly': True,
      'text': text,
      'token': api_request(
        api,
        session,
        {
          'action': 'query',
          'meta': 'tokens'
        }
      )['query']['tokens']['csrftoken']
    }
  )
  if 'edit' in query and query['edit']['result'] == 'Success':
    return query['edit']
  else:
    raise ConnectionError('Edit failed: ' + str(query))

with open('tolbot-task10.json') as f:
	titles = set(json.load(f))

session = login(api, username, password)

#print('{{hlist', end='')

while titles:
  title = titles.pop()
  match = pattern.match(title)
  if match:
    name = dict(zip(('first', 'initial', 'last'), match.groups()))
    edit = create(
      api,
      session,
      redirect_title.format(**name),
      redirect_text.format(**name),
      summary.format(**name)
    )
    #print('|[[Special:Diff/{0}|{1}]]'.format(edit['newrevid'], x+1), end='')
  else:
    print(title)
    break

#print('}}')

with open('tolbot-task10.json', 'w') as f:
  json.dump(sorted(list(titles)), f)

Licensing

[edit]

This work (all source code in this level 2 section) is licensed under: