Simple continuously running XMPP client in python

2019-06-06 22:58发布

I'm using python-xmpp to send jabber messages. Everything works fine except that every time I want to send messages (every 15 minutes) I need to reconnect to the jabber server, and in the meantime the sending client is offline and cannot receive messages.

So I want to write a really simple, indefinitely running xmpp client, that is online the whole time and can send (and receive) messages when required.

My trivial (non-working) approach:

import time
import xmpp

class Jabber(object):
    def __init__(self):
        server = 'example.com'
        username = 'bot'
        passwd = 'password'
        self.client = xmpp.Client(server)
        self.client.connect(server=(server, 5222))
        self.client.auth(username, passwd, 'bot')
        self.client.sendInitPresence()
        self.sleep()

    def sleep(self):
        self.awake = False
        delay = 1
        while not self.awake:
            time.sleep(delay)

    def wake(self):
        self.awake = True

    def auth(self, jid):
        self.client.getRoster().Authorize(jid)
        self.sleep()

    def send(self, jid, msg):
        message = xmpp.Message(jid, msg)
        message.setAttr('type', 'chat')
        self.client.send(message)
        self.sleep()

if __name__ == '__main__':
    j = Jabber()
    time.sleep(3)
    j.wake()
    j.send('receiver@example.org', 'hello world')
    time.sleep(30)

The problem here seems to be that I cannot wake it up. My best guess is that I need some kind of concurrency. Is that true, and if so how would I best go about that?

EDIT: After looking into all the options concerning concurrency, I decided to go with twisted and wokkel. If I could, I would delete this post.

标签: python xmpp
2条回答
成全新的幸福
2楼-- · 2019-06-06 23:33

There is a good example on the homepage of xmpppy itself (which is another name for python-xmpp), which does almost what you want: xtalk.py

It is basically a console jabber-client, but shouldn't be hard to rewrite into bot you want.

It's always online and can send and receive messages. I don't see a need for multiprocessing (or other concurrency) module here, unless you need to receive and send messages at exact same time.

查看更多
Lonely孤独者°
3楼-- · 2019-06-06 23:38

A loop over the Process(timeout) method is a good way to wait and process any new incoming stanzas while keeping the connection up.

查看更多
登录 后发表回答