如何使用twisted每隔几秒发送一次IRC消息?

时间:2012-11-29 09:21:50

标签: python twisted irc

扭曲的文档提供了how to create an IRC bot

的示例

以下是我目前拥有的代码(源自上面的示例):

from twisted.words.protocols import irc
from twisted.internet import protocol
from twisted.internet import reactor

class Bot(irc.IRCClient):
    def _get_nickname(self):
        return self.factory.nickname
    nickname = property(_get_nickname)

    def signedOn(self):
        self.join(self.factory.channel)
        print "Signed on as %s." % (self.nickname,)

    def joined(self, channel):
        print "Joined %s." % (channel,)

    def privmsg(self, user, channel, msg):
        print msg

class BotFactory(protocol.ClientFactory):
    protocol = Bot

    def __init__(self, channel, nickname='test-nick-name'):
        self.channel = channel
        self.nickname = nickname

    def clientConnectionLost(self, connector, reason):
        print "Lost connection (%s), reconnecting." % (reason,)
        connector.connect()

    def clientConnectionFailed(self, connector, reason):
        print "Could not connect: %s" % (reason,)


if __name__ == "__main__":

    channel = '#test-channel-123'
    reactor.connectTCP('irc.freenode.net', 6667, BotFactory(channel))
    reactor.run()

现在我想添加发送消息的功能,每隔5秒向频道发送一次。我该怎么做呢?如何从外部获取Bot.msg方法的句柄?

1 个答案:

答案 0 :(得分:1)

  

发送消息说每5秒到频道

查看LoopingCall,您可以使用它来每隔 n 秒调用一个方法。

from twisted.internet import task

task.LoopingCall(yourSendingMethodHere).start(5.0)

  

如何从外部获取Bot.msg方法的句柄?

这取决于你。您创建了BotFactory的实例,并且每个Bot都有对其工厂的引用。