在python中简单地连续运行XMPP客户端 [英] Simple continuously running XMPP client in python

查看:46
本文介绍了在python中简单地连续运行XMPP客户端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 python-xmpp 发送 jabber 消息.一切正常,除了每次我想发送消息(每 15 分钟)我需要重新连接到 jabber 服务器,同时发送客户端离线并且无法接收消息.

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.

所以我想写一个非常简单的、无限期运行的 xmpp 客户端,它一直在线并且可以在需要时发送(和接收)消息.

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?

在研究了所有关于并发的选项后,我决定使用扭曲和 wokkel.如果可以,我会删除这篇文章.

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

推荐答案

主页 xmpppy 本身(这是 python-xmpp 的另一个名称),它几乎可以满足您的需求:xtalk.py

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

它基本上是一个控制台 jabber 客户端,但应该不难将其重写为您想要的机器人.

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.

这篇关于在python中简单地连续运行XMPP客户端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆