Search code examples
pythontwisted

Recurring function call with twisted


I have a basic IRC bot that looks something like this (see below), what I would like to do is use something like the _5_mins function to be called every 5 mins with a LoopingCall

import sys
import re
from twisted.internet import reactor, task, defer, protocol
from twisted.python import log
from twisted.words.protocols import irc
from twisted.application import internet, service
import time

HOST, PORT = 'irc.freenode.net', 6667

class IrcProtocol(irc.IRCClient):
    nickname = 'BOTSNAME'
    password = 'NICKPASSWORD'
    timeout = 600.0

    def signedOn(self):
        pMess = "IDENTIFY %s" % self.password
        self.msg("NickServ",pMess)
        time.sleep(10)
        for channel in self.factory.channels:
            self.join(channel)

    def _5_mins(self):
        self.msg(self.factory.channels[0],"5 minutes have elapsed")

class IrcFactory(protocol.ReconnectingClientFactory):
    channels = ['#BOTCHANNEL']
    protocol = IrcProtocol

if __name__ == '__main__':
    reactor.connectTCP(HOST, PORT, IrcFactory())
    log.startLogging(sys.stdout)
    reactor.run()

elif __name__ == '__builtin__':
    application = service.Application('IrcBot')
    ircService = internet.TCPClient(HOST, PORT, IrcFactory())
    ircService.setServiceParent(application)

How do I alter the signedOn function work with the task.LoopingCall function or is there a better way?

EDIT: I was really close to a solution, the following is what I have gone with

def signedOn(self):
    pMess = "IDENTIFY %s" % self.password
    self.msg("NickServ",pMess)
    time.sleep(10)
    for channel in self.factory.channels:
        self.join(channel)
    lc = task.LoopingCall(self._5_mins)
    lc.start(self.timeout)

Solution

  • def signedOn(self):
        pMess = "IDENTIFY %s" % self.password
        self.msg("NickServ",pMess)
        time.sleep(10)
        for channel in self.factory.channels:
            self.join(channel)
        lc = task.LoopingCall(self._5_mins)
        lc.start(self.timeout)