【问题标题】:How to send IRC messages every few seconds using twisted?如何使用twisted每隔几秒发送一次IRC消息?
【发布时间】:2012-11-29 09:21:50
【问题描述】:

twisted 文档提供了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 方法的句柄?

【问题讨论】:

    标签: python twisted irc


    【解决方案1】:

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

    看看LoopingCall,你可以用它每隔n秒调用一个方法。

    from twisted.internet import task
    
    task.LoopingCall(yourSendingMethodHere).start(5.0)
    

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

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

    【讨论】:

      猜你喜欢
      • 2021-04-27
      • 1970-01-01
      • 2021-11-29
      • 1970-01-01
      • 2010-12-17
      • 1970-01-01
      • 2021-10-06
      • 2011-06-28
      • 1970-01-01
      相关资源
      最近更新 更多