Esempio n. 1
0
def process(user, data, ab):
    page = None
    summary = data["summary"]
    if data["action"] in ["block", "notifyUser"]:
        page = user.getUserTalkPage()
    elif data["action"] == "notify":
        page = wp.Page(data["pageReport"])

    if data["action"] == "block":
        expiry = "1 day"
        if user.isRegistered():
            if "blockDuration" in data:
                expiry = data["blockDuration"]
        else:
            if "anonBlockDuration" in data:
                expiry = data["anonBlockDuration"]
        try:
            user.block(reason=u"โรบอต: " + data["summary"], expiry=expiry)
        except NotImplementedError:
            return
        summary = u"แจ้งการถูกบล็อก: " + summary

    if page is not None:
        lnotify.notify(data["template"], page, {
                            "user": user.name(),
                            "title": ab["title"],
                       }, u"โรบอต: " + summary, nocreate=False, botflag=False)
Esempio n. 2
0
def callback(page, err):
    if isinstance(err, pywikibot.LockedPage) or isinstance(err, pywikibot.PageNotSaved) or repr(err) == """APIError("protectednamespace-interface", "You're not allowed to edit interface messages", {})""":
        if hasattr(page, 'u_nomore'):
            page.u_err = True
        else:
            page.u_nomore = True
            page.put(page.u_text, u"ปรับปรุงหน้าอัตโนมัติโดยบอต", as_group='sysop')
            return
    elif err:
        page.u_err = True

    if hasattr(page, 'u_err'):
        pywikibot.output("<!-- Begin error -->")
        pywikibot.output(page.text)
        pywikibot.output("<!-- End error -->")
        page.u_elist.append(u"ผิดพลาด: ไม่เกิดการเขียนหน้า <pre>{}</pre>".format(sys.exc_info()[0]))
        wp.error()
        return

    """
    if page.u_checkcat:
        time.sleep(30)
        for cat in page.u_checkcat:
            if cat.isEmptyCategory():
                page.u_elist.append((u"[[:{}]] ว่างลงแล้ว "
                                     u"แสดงว่าไม่มีพารามิเตอร์ล้าสมัย "
                                     u"คุณอาจเขียนคู่มือการใช้งานใหม่"
                                     u"และลบการตั้งค่าพารามิเตอร์ล้าสมัยออก").format(cat.title()))
    """

    #for user in config["notifyuser"]:
    for user in ["Nullzero"]:
        lnotify.notify("updatePage", wp.User(user).getUserTalkPage(), {
                    "page": page.title(),
                    "error": "".join(map(lambda x: "* " + x + "\n", page.u_elist)),
                    "warn_module": u"และดู [[:หมวดหมู่:หน้าที่มีสคริปต์ผิดพลาด]] " if # มีเดียวิกิ:Scribunto-common-error-category
                                   page.namespace() == 828 else "",
                    "page_config": conf.title,
                    "revision": page.latestRevision(),
                }, u"แจ้งการปรับปรุงหน้าอัตโนมัติ")
Esempio n. 3
0
def process(pagenow, page, user):
    if page is None:
        page = pagenow
    if (user.editCount() >= 5000 and "autoconfirmed" in user.groups()) or (
                                     "sysop" in user.groups()):
        return
    text = pagenow.get()
    nowrefs = cntref(text)
    pywikibot.output(">>> %s | %s with %d refs" %
                    (pagenow.title(), page.title(), nowrefs))
    ts = None
    for gen in site.deletedrevs(page, get_text=True, reverse=True):
        for rev in gen["revisions"]:
            ratio = difflib.SequenceMatcher(None, text, rev["*"]).ratio()
            oldrefs = cntref(rev["*"])
            pywikibot.output("processing %s; ratio %f; %d refs" %
                            (rev["revid"], ratio, oldrefs))
            if ratio >= 0.8:
                if nowrefs <= oldrefs:
                    ts = pywikibot.Timestamp.fromISOformat(rev["timestamp"])
                    break
                else:
                    pywikibot.output("refs has been improved")
        break

    if ts is None:
        return

    cntdel = 0
    first = True
    deletion = None
    for dl in site.logevents("delete", page=pagenow, reverse=True):
        cntdel += 1
        if dl.timestamp() > ts:
            if first:
                deletion = dl
                first = False

    if deletion is None:
        pywikibot.output("Weird")
        return

    reason = lre.pats["stripcomment"].sub("", deletion.comment()).strip()

    associatedPage = pagenow.toggleTalkPage()
    if associatedPage.exists():
        associatedPage.delete(reason=u"โรบอต: ลบหน้าพูดคุยของหน้าที่ถูกลบอัตโนมัติ", prompt=False)

    pagenow.delete(reason=u"โรบอต: %s" %
                  (reason or u"[[WP:CSD#ท9|ท9]]: สร้างหน้าที่เคยถูกลบใหม่"),
                  prompt=False)

    pywikibot.output("deleted")
    site.login()

    lnotify.notify("t9", user.getUserTalkPage(), {
                        "page": pagenow.title(),
                        "date": ts.strftime("%d/%m/%y %H:%M (UTC)"),
                        "pagefrom": "" if page == pagenow
                                       else u"ของหน้า " + page.title(),
                        "admin": deletion.user(),
                        "reason": (u' "{}"'.format(reason) if reason
                                                           else u"บางประการ"),
                    }, u"แจ้งเตือนการสร้างหน้าที่เคยถูกลบ", nocreate=False,
                    botflag=False)

    pywikibot.output(u"had deleted for {} times".format(cntdel))
    if cntdel >= 3:
        page.protect(edit=None, move=None, create="sysop", 
                     reason=u"โรบอต: หน้าไม่ผ่านเกณฑ์ - ถูกลบหลายครั้งติดต่อกัน", expiry="14 days", prompt=False)
        pywikibot.output("protected")
Esempio n. 4
0
def process(text, page_config):
    global putWithSysop

    params = {}
    for key in conf.seriesKey:
        params[conf.seriesKey[key]] = []

    errorlist = []
    deprecated = []
    checkcat = []
    try:
        for param in lre.pats["param"].finditer(text + "|"):
            param = param.group(1)
            key, dat = param.split("=", 1)
            key = key.strip()
            dat = dat.strip()
            if key in conf.translateKey:
                params[conf.translateKey[key]] = dat
            else:
                num = lre.pats["num"].find(key)
                key = lre.pats["num"].sub("", key)
                if key in conf.seriesKey:
                    params[conf.seriesKey[key]].append((num, dat))
                else:
                    error("unknown parameter", param)
    except:
        wp.error()
        if "source" in params:
            pywikibot.output(u"Error when updating %s" % params["source"])
        else:
            pywikibot.output(u"Error when processing page %s" % page_config)
        return

    if not checkparams(params):
        error("something wrong")
        return

    if "disable" in params and params["disable"] == conf.yes:
        return

    source = wp.Page(params["source"])
    page = wp.Page(params["page"])
    today = site.getcurrenttime()
    originalText = page.get() if page.exists() else None

    if ("stable" in params and (today - pywikibot.Timestamp.fromISOformat(
                    source.getVersionHistory(total=1)[0][1])).days <
                    int(params["stable"])):
        return

    params["notifyuser"] = [lre.pats["user0"].find(x.strip(), 1)
                            for x in params["notifyuser"].split("\n")]
    text = source.get()

    #=======

    for i, (num, sfind) in enumerate(params["find"]):
        newtext = text.replace(parse(sfind), parse(params["replace"][i][1]))
        if newtext == text and sfind != params["replace"][i][1]:
            errorlist.append(u"คำเตือน: ไม่เกิดการแทนที่ข้อความที่ {0}".format(num))
        text = newtext

    def matchbrace(s, i):
        lv = 0
        for i in xrange(i, len(s)):
            if s[i] == "{": lv += 1
            elif s[i] == "}": lv -= 1
            if lv == 0:
                return i
                # not return i + 1 to avoid index out of range

    for irep, (num, sp) in enumerate(params["param"]):
        lst = []
        for i in lre.finditer(r"\{\{\{\s*" + sp + "\s*[\|\}]", text):
            begin, end = i.span()
            end = matchbrace(text, begin)
            lst.append((begin, "begin"))
            lst.append((end, "end"))
        lst = sorted(lst)
        lst.append((sys.maxint, sys.maxint))
        ilst = 0
        out = []
        for i in xrange(len(text)):
            if i == lst[ilst][0]:
                if lst[ilst][1] == "begin":
                    out.append("{{{" + params["translate"][irep][1] + "|")
                else:
                    out.append("}}}")
                    # we should put text[i] before "}}}",
                    # but since text[i] == "}", there is no problem :)
                ilst += 1
            out.append(text[i])
        newtext = "".join(out)
        if newtext == text:
            errorlist.append(u"คำเตือน: ไม่เกิดการแปลพารามิเตอร์ที่ {0}".format(num))
        text = newtext

    for i, (num, sdepr) in enumerate(params["depr"]):
        category = wp.Category("Category:" + page.title().replace(":", "") +
                               u" ที่ใช้พารามิเตอร์ " + sdepr)
        checkcat.append(category)
        deprecated.append(u'<includeonly>{{{{#if:{{{{{{{depr}|}}}}}}|[[{cat}]]'
                          .format(depr=sdepr, cat=category.title()) +
                          ((u'<span class="error">พารามิเตอร์ {depr} '
                          u'ล้าสมัยแล้ว โปรดใช้ {rdepr} แทนที่</span><br />')
                          .format(depr=sdepr, rdepr=params["rdepr"][i][1])
                          if (params["errordepr"][i][1] == conf.yes) else u'') +
                          u'}}</includeonly>')
    text = "".join(deprecated) + text

    #=======

    if (not errorlist) and (text == originalText):
        pywikibot.output(u"ไม่มีการเปลี่ยนแปลงในหน้า %s; "
                         u"ยกเลิกการปรับปรุงและแจ้งเตือน" % source.title())
        return

    if debug:
        pywikibot.showDiff(originalText or "", text)
        return

    if "sandbox" in params and params["sandbox"] == conf.yes:
        page = wp.Page(page.title() + "/sandbox")

    foundError = False

    try:
        page.put(text, u"ปรับปรุงหน้าอัตโนมัติโดยบอต")
    except (pywikibot.LockedPage, pywikibot.PageNotSaved):
        try:
            page.put(text, u"ปรับปรุงหน้าอัตโนมัติโดยบอต", as_group='sysop')
        except:
            foundError = True
    except:
        foundError = True

    if foundError:
        pywikibot.output("<!-- Begin error -->")
        pywikibot.output(text)
        pywikibot.output("<!-- End error -->")
        errorlist.append(u"ผิดพลาด: ไม่เกิดการเขียนหน้า <pre>{}</pre>".format(sys.exc_info()[0]))
        wp.error()

    if checkcat:
        time.sleep(30)
        for cat in checkcat:
            if cat.isEmptyCategory():
                errorlist.append(u"[[:%s]] ว่างลงแล้ว "
                                 u"แสดงว่าไม่มีพารามิเตอร์ล้าสมัย "
                                 u"คุณอาจเขียนคู่มือการใช้งานใหม่"
                                 u"และลบการตั้งค่าพารามิเตอร์ล้าสมัยออก" %
                                 cat.title())

    #for user in params["notifyuser"]:
    for user in ["Nullzero"]:
        lnotify.notify("updatePage", wp.User(user).getUserTalkPage(), {
                    "page": page.title(),
                    "error": "".join(map(lambda x: "* " + x + "\n", errorlist)),
                    "warn_module": u"และดู [[:หมวดหมู่:หน้าที่มีสคริปต์ผิดพลาด]] " if # มีเดียวิกิ:Scribunto-common-error-category
                                   page.namespace() == 828 else "",
                    "page_config": page_config,
                    "revision": page.latestRevision(),
                }, u"แจ้งการปรับปรุงหน้าอัตโนมัติ")