Sending ICQ messages from outside event handlers in Twisted, Oscar

885 views Asked by At

I'm making an ICQ (and XMPP in prospect) bot for a service, which should send and receive messages from users.

I'm using Python and Twisted. I started from the official documentation's example (this one: http://twistedmatrix.com/documents/current/words/examples/oscardemo.py)

So far I successfully receive and process messages from ICQ contacts. Now I need to send messages, but not in a respond to their message or some event. I need to send messages with Oscar (Twisted's thing for ICQ messaging) from outside the class with event handlers. How do I do that?

I'd appreciate any help since I fail to google anything useful, there's not so much about using Oscar out there.

2

There are 2 answers

10
sloth On BEST ANSWER

When you connect

protocol.ClientCreator(reactor, OA, SN, PASS, icq=icqMode).connectTCP(*hostport)

add a Deferred, which will be called when the connection is done:

oscar_prot = None

def get_B_instance(b_instance):
    global oscar_prot
    oscar_prot = b_instance

d = Deferred()
d.addCallback(get_B_instance)

protocol.ClientCreator(reactor, OA, SN, PASS, deferred=d, icq=icqMode).connectTCP(*hostport)

In the get_B_instance function, you can keep the reference to the instance of the protocol class.

Then you can just call sendMessage on that instance.

oscar_prot.sendMessage(username, message)
6
Jean-Paul Calderone On

There is no "inside" or "outside". The containment metaphor in programming is a mostly damaging one. You'd be better off forgetting about it.

Consider this class:

class Foo(object):
    def bar(self):
        return "Foo.bar says hello"

    def baz(self):
        print self.bar()

Given an instance of Foo named aFoo, consider these two ways of using it:

aFoo.baz()
print aFoo.bar()

What is the difference in behavior from these two uses? There isn't one, yet one calls bar from "inside" and one calls bar from "outside". The containment metaphor is useless and irrelevant here, nothing changes based on "where" the function is called from.