[Twisted-Python] irc bot, reacting to: irc_ERR_NOSUCHNICK. after the code where the reactor was started

Glyph Lefkowitz glyph at twistedmatrix.com
Wed Oct 7 01:49:45 MDT 2015


> On Oct 6, 2015, at 11:38 PM, peter <commercials24 at yahoo.de> wrote:
> 
> im sure youre solution is just fine, could you show me how you would contruct isBotOnline?
> im assuming that code would go into the class "mybot", next to irc_ERR_NOSUCKNICK?


The problem with just doing that is that there is no affirmative response that a message was sent, so there's no way to fire the deferred successfully if that's all you're doing.  Instead, you can use the ISON command to determine if the bot is online (and of course, the bot might go offline between the check and sending the message, so you will need to handle that case somehow too).

Since doing this is somewhat obscure, here's a working script that just checks if a nick specified on the command line is online on freenode:

from __future__ import print_function
from twisted.internet.defer import Deferred, inlineCallbacks
from twisted.words.protocols.irc import IRCClient
from twisted.internet.endpoints import clientFromString
from twisted.internet.protocol import Factory

class mybot(IRCClient, object):
    def __init__(self):
        self._isonQueue = []
        self.motdReceived = Deferred()

    def irc_RPL_ISON(self, prefix, params):
        username, d = self._isonQueue.pop(0)
        d.callback((username in params[1]))

    def isOnline(self, username):
        d = Deferred()
        self.sendLine("ISON " + username)
        self._isonQueue.append((username, d))
        return d

    def irc_RPL_ENDOFMOTD(self, prefix, params):
        self.motdReceived.callback(None)

@inlineCallbacks
def main(reactor, nick):
    endpoint = clientFromString(reactor, "tcp:chat.freenode.net:6667")
    proto = yield endpoint.connect(Factory.forProtocol(mybot))
    print("Waiting for MOTD...")
    yield proto.motdReceived
    print("Querying...")
    isOnline = yield proto.isOnline(nick)
    if isOnline:
        print(nick, "is online!")
    else:
        print(nick, "is *NOT* online!")

from twisted.internet.task import react
from sys import argv
react(main, argv[1:])


-glyph

-------------- next part --------------
An HTML attachment was scrubbed...
URL: </pipermail/twisted-python/attachments/20151007/80a41b80/attachment-0002.html>


More information about the Twisted-Python mailing list