Ticket #5641: ircLogBot.patch

File ircLogBot.patch, 1.8 KB (added by David Baumgold, 7 years ago)
  • doc/words/examples/ircLogBot.py

     
    11# Copyright (c) Twisted Matrix Laboratories.
    22# See LICENSE for details.
     3from __future__ import with_statement
    34
    45
    56"""
     
    2526
    2627# twisted imports
    2728from twisted.words.protocols import irc
    28 from twisted.internet import reactor, protocol
     29from twisted.internet import reactor, protocol, task
    2930from twisted.python import log
    3031
    3132# system imports
    3233import time, sys
     34import datetime
    3335
    3436
    3537class MessageLogger:
     
    143145        print "connection failed:", reason
    144146        reactor.stop()
    145147
     148def logDate(filename):
     149    with open(filename, "a") as log:
     150        today = datetime.date.today()
     151        text = time.asctime(today.timetuple()) \
     152            .replace("00:00:00 ", "")
     153        log.write('[%s]\n' % (text))
    146154
    147155if __name__ == '__main__':
     156    channel = sys.argv[1]
     157    filename = sys.argv[2]
     158
    148159    # initialize logging
    149160    log.startLogging(sys.stdout)
    150161   
    151162    # create factory protocol and application
    152     f = LogBotFactory(sys.argv[1], sys.argv[2])
     163    f = LogBotFactory(channel, filename)
    153164
    154165    # connect factory to this host and port
    155166    reactor.connectTCP("irc.freenode.net", 6667, f)
    156167
     168    # set up date logging
     169    def startDateLoop(self, filename):
     170        task.LoopingCall(logDate, filename).start(60*60*24)
     171    # schedule it at one second past midnight
     172    now = datetime.datetime.utcnow()
     173    now_ts = time.mktime(now.timetuple())
     174    midnight = (now + datetime.timedelta(days=1)) \
     175            .replace(hour=0, minute=0, second=1, microsecond=0)
     176    midnight_ts = time.mktime(midnight.timetuple())
     177    reactor.callLater(midnight_ts - now_ts, startDateLoop, filename)
     178
    157179    # run bot
    158180    reactor.run()