2
votes

I'm trying to make an IRC bot using the twisted.words.protocols.irc module.

The bot will parse messages from a channel and parse them for command strings.

Everything works fine except when I need the bot to identify a nick by sending a whois command. The whois reply will not be handled until the privmsg method (the method from which I'm doing the parsing) returns.
example:

from twisted.words.protocols import irc

class MyBot(irc.IRClient):

..........

    def privmsg(self, user, channel, msg):
        """This method is called when the client recieves a message"""
        if msg.startswith(':whois '):
            nick = msg.split()[1]
            self.whois(nick)
            print(self.whoislist)

    def irc_RPL_WHOISCHANNELS(self, prefix, params):
        """This method is called when the client recieves a reply for whois"""
        self.whoislist[prefix] = params

Is there a way to somehow make the bot wait for a reply after self.whois(nick)?

Perhaps use a thread (I don't have any experience with those).

2

2 Answers

2
votes

Deferred is a core concept in Twisted, you must be familiar with it to use Twisted.

Basically, your whois checking function should return a Deferred that will be fired when you receive whois-reply.

-2
votes

I managed to fix this by running all handler methods as threads, and then setting a field, following kirelagin's suggestion, before running a whois query, and modifying the method that recieves the data to change the field when it recieves a reply. Its not the most elegant solution but it works.

Modified code:

class MyBot(irc.IRClient):
..........

    def privmsg(self, user, channel, msg):
        """This method is called when the client recieves a message"""
        if msg.startswith(':whois '):
            nick = msg.split()[1]

            self.whois_status = 'REQUEST'
            self.whois(nick)
            while not self.whois_status == 'ACK':
                sleep(1)

            print(self.whoislist)

    def irc_RPL_WHOISCHANNELS(self, prefix, params):
        """This method is called when the client recieves a reply for whois"""
        self.whoislist[prefix] = params

    def handleCommand(self, command, prefix, params):
        """Determine the function to call for the given command and call
        it with the given arguments.
        """
        method = getattr(self, "irc_%s" % command, None)
        try:
            # all handler methods are now threaded.
            if method is not None:
                thread.start_new_thread(method, (prefix, params))
            else:
                thread.start_new_thread(self.irc_unknown, (prefix, command, params))
        except:
            irc.log.deferr()

    def irc_RPL_WHOISCHANNELS(self, prefix, params):
        """docstring for irc_RPL_WHOISCHANNELS"""
        self.whoislist[prefix] = params

    def irc_RPL_ENDOFWHOIS(self, prefix, params):
        self.whois_status = 'ACK'