Jump to content

User:East718/tfabot

From Wikipedia, the free encyclopedia
###################################################
# The sole author of this program is east718.     #
# <http://en.wikipedia.org/wiki/user:east718>     #
#                                                 #
# This program is free software and comes without #
# any warranty, to the extent permissible by law. #
# You can redistribute it, and/or modify it under #
# the terms of the "Do What The Fuck You Want To" #
# Public License: <http://sam.zoy.org/wtfpl/>     #
#                                                 #
# 0. You just DO WHAT THE FUCK YOU WANT TO.       #
###################################################

import blackbox, ircoptions, re, time, traceback, warnings, wikipedia
warnings.simplefilter('ignore')
from simplejson import decoder
from twisted.internet import reactor, protocol
from twisted.words.protocols import irc
message = ''
site = wikipedia.getSite()

class ircBot(irc.IRCClient):
  def __init__(self):
    self.nickname = ircoptions.nickname
    self.password = ircoptions.password
    self.realname = ircoptions.realname
    self.username = ircoptions.username
    
  def signedOn(self):
    self.join('wikipedia-en-admins')
    self.say('wikipedia-en-admins', message.encode('ascii'))
    self.quit(self.realname)

class ircFactory(protocol.ReconnectingClientFactory):
  def __init__(self):
    self.protocol = ircBot

  def clientConnectionLost(self, connector, reason):
    reactor.stop()

  def clientConnectionFailed(self, connector, reason):
    reactor.stop()

def main():
  try:
    page = wikipedia.Page(site, re.compile("\('''\[\[(?P<title>.+ ?)\|more\.\.\.\]\]'''\)", re.UNICODE).search(wikipedia.Page(site, "Wikipedia:Today's featured article/%s" % re.sub('(\s)0([0-9],)', '\\1\\2', time.strftime('%B %d, %Y', time.gmtime(time.time() + 86400)))).get(sysop = True)).group('title'))
    if len(decoder.JSONDecoder().decode(site.postForm('/w/api.php', {'action': 'query', 'format': 'json', 'list': 'logevents', 'leprop': 'ids', 'letype': 'move', 'lelimit': '1', 'ledir': 'newer', 'lestart': time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime(time.time() - 3600)), 'letitle': page.title()})[1])['query']['logevents']) == 0:
      protection = decoder.JSONDecoder().decode(site.postForm('/w/api.php', {'action': 'query', 'format': 'json', 'prop': 'info', 'inprop': 'protection', 'titles': page.title()})[1])['query']['pages'].values()[0]['protection']
      protect = {'edit': '', 'move': '', 'time': time.mktime(time.gmtime(0))}
      if len(protection) > 0:
        for item in protection:
          protect['time'] = time.mktime(time.strptime(item['expiry'], '%Y-%m-%dT%H:%M:%SZ')) if item['expiry'] != 'infinity' else 'infinite'
          protect[item['type']] = item['level']
      if False if protect['time'] == 'infinite' else (protect['time'] < time.mktime(time.strptime(time.strftime('%Y-%m-%dT23:59:00Z', time.gmtime()), '%Y-%m-%dT%H:%M:%SZ')) + 86460 - (3600 if time.localtime()[-1] == 1 else 0)):
        prot(page, protect['edit'], '1441 minutes')
        print 'Protecting %s for a day.' % page.title()
      elif protect['move'] != 'sysop':
        prot(page, protect['edit'], (time.strftime('%H:%M:%S, %B %d, %Y', time.gmtime(protect['time'])) if protect['time'] != 'infinite' else 'infinite'))
        print 'Protecting %s for the duration of its previous protection.' % page.title()
      else:
        print 'Not protecting %s.' % page.title()
      if protect['edit'] == 'autoconfirmed':
        ohno("Hey, this is east718's featured article protection bot. I noticed that [[%s]] is semi-protected; you might want to consider downgrading it to move-only." % page.title(), False)
      elif protect['edit'] == 'sysop':
        ohno("Today's featured article, [[%s]], is fully protected; please downgrade it to move-only or semiprotection." % page.title())
    else:
      ohno("Today's featured article, [[%s]], has been recently moved; please make sure it is in the correct location and move-protected." % page.title())
  except:
    traceback.print_exc()
    ohno("east718's featured article protection robot has run into an unexpected error; please make sure today's featured article is move-protected.")

def ohno(out, severe = True):
  global message
  message = '%s%s' % ('!admin - ' if severe == True else '', out)
  reactor.connectTCP('irc.freenode.net', 6667, ircFactory())
  reactor.run()

def prot(page, edit, duration):
  page.protect(edit, 'sysop', False, "Robot: Move-protecting today's featured article", False, False, '', duration)

if __name__ == '__main__':
  try:
    main()
  finally:
    wikipedia.stopme()
    blackbox.notify()