跳至內容

用戶:WhitePhosphorus/python/ReplaceLink.py

維基百科,自由的百科全書
import re
import sys
import time
import botsite

# ref: https://en.wikipedia.org/wiki/User:Joeytje50/JWB.js
exclude = (r'(<!--[\s\S]*?-->|'
           '<(?P<tags>nowiki|math|source|syntaxhighlight|pre|gallery|timeline)'
           '[^>]*?>[\s\S]*?<\/(?P=tags)>)')


def do_replace(text, repl_re, new):
    return re.sub(repl_re,
                  lambda m: m.group('p') + new + m.group('s')
                            if m.group(1) is None else m.group(1),
                  text)


def main(old, new, pwd):
    botsite.bot_name = 'WhitePhosphorus@Flood'
    site = botsite.Site()
    site.login(pwd=pwd)
    
    esc = re.escape(old)
    repl_re = re.compile(r'%s|((?P<p>\[\[)%s(?P<s>\||\]\]))' % (exclude, esc))
    
    for page in site.backlinks(old):
        text = site.get_text_by_title(page)
        text = do_replace(text, repl_re, new)
        site.edit(text,
                  summary=('[[User:WhitePhosphorus/python/ReplaceLink.py'
                           '|机器人更改内链]]:[[%s]] → [[%s]]' % (old, new)),
                  title=page, minor=True, bot=True)
        time.sleep(6)


def print_usage():
    print('usage: %s <OldPageName> <NewPageName> <BotPassword>' % sys.argv[0])


if __name__ == '__main__':
    if len(sys.argv) != 4:
        print_usage()
        exit(1)
    main(*sys.argv[1:])