1

扭曲的文档提供了如何创建 IRC 机器人的示例

这是我目前拥有的代码(来自上面的示例):

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 方法的句柄?

4

1 回答 1

2

每 5 秒向频道发送一条消息

看看,您可以使用它每隔nLoopingCall调用一次方法。

from twisted.internet import task

task.LoopingCall(yourSendingMethodHere).start(5.0)

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

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

于 2012-11-29T09:36:39.970 回答