import datetime
import re
import pywikibot

TEMPLATE_NAME = "Template:Vandalism information"
COMMENT = "[[Wikipedia:Bots/Requests for approval/APersonBot 5|Bot]] updating vandalism level to %d RPM"
TEMPLATE_PATH = "/data/project/apersonbot/bot/defcon/template.txt"
INTERVAL = 60
site = pywikibot.Site("en", "wikipedia")
site.login()

num_reverts = 0
for change in site.recentchanges(
        start=datetime.datetime.now(),
        end=datetime.datetime.now() - datetime.timedelta(minutes=INTERVAL),
        changetype="edit"):
    if re.search("revert|rv\ |rvv\ |undid(?!good( |-)faith)", change[u"comment"],
                 flags=re.IGNORECASE):
        num_reverts += 1
rpm = float(num_reverts) / INTERVAL

template_page = pywikibot.Page(site, TEMPLATE_NAME)
current_rpm_match = re.search("WikiDefcon/levels\|(\d+)", template_page.get())
if (not current_rpm_match) or (int(current_rpm_match.group(1)) != int(rpm)):
    try:
        template = open(TEMPLATE_PATH)
    except IOError as e:
        print(e)
    else:
        try:
            template_page.text = template.read() % (int(rpm), rpm)
            template_page.save(COMMENT % int(rpm))
        except Exception as e:
            print(e)
        finally:
            template.close()

@@ -272,16 +272,151 @@
 AL = 60%0A
+%0A# If it's been longer than this since the last edit, make a null edit to%0A# keep our session alive.%0ANULL_EDIT_THRESHOLD = 3 * 60 * 60%0A%0A
 site = p
@@ -462,16 +462,53 @@
 ogin()%0A%0A
+# Calculate RPM by counting reverts.%0A
 num_reve
@@ -692,16 +692,67 @@
 edit%22):%0A
+    if u%22comment%22 not in change:%0A        continue%0A%0A
     if r
@@ -1057,19 +1057,31 @@
 .get())%0A
-if 
+rpm_changed = (
 (not cur
@@ -1098,16 +1098,31 @@
 atch) or
+%0A              
  (int(cu
@@ -1159,16 +1159,279 @@
 nt(rpm))
+)%0Alast_edit_timestamp = %5Bx for x in template_page.revisions(total=1)%5D%5B0%5D.timestamp%0Aseconds_since_last_edit = (datetime.datetime.utcnow() - last_edit_timestamp).total_seconds()%0Aneed_nudge = seconds_since_last_edit %3E NULL_EDIT_THRESHOLD%0Aif rpm_changed or need_nudge
 :%0A    tr
@@ -1724,16 +1724,16 @@
 inally:%0A
-
         
@@ -1753,8 +1753,139 @@
 close()%0A
+else:%0A    timestamp = datetime.datetime.now().strftime(%22%25Y-%25m-%25d %25H:%25M:%25S%22)%0A    print(%22%5B%7B%7D%5D No edit necessary.%22.format(timestamp))%0A

Make a null edit to keep session alive