我试图找到一种在同步函数调用中使用异步XMPP库的方法。
我想编写一个简单的Python函数,通过XMPP消息发送其参数,接收回复,并返回此回复:
def read_ans(a,b,c):
# send [a,b,c] via an XMPP message
# wait for XMPP message with reply, z
return z
我找到了sleekxmpp
库,并编写了一个简单的脚本来执行此操作。我遇到的问题是sleekxmpp
在多个线程中运行,并为接收的消息指定回调。我不确定如何同步运行它。
到目前为止我的内容如下。如何将self.last_message
传递给read_ans
以便可以返回?
谢谢!
import sleekxmpp
class XMPP(sleekxmpp.ClientXMPP):
def __init__(self, jid, password, myargs):
sleekxmpp.ClientXMPP.__init__(self, jid, password)
self.add_event_handler("session_start", self.start)
# Store arguments
self.myargs = myargs
# This is where we store the last message received
self.last_message = ""
self.add_event_handler("message", self.message)
def start(self, event):
self.send_presence()
self.get_roster()
self.send_message(mto=recipient, mbody=str(self.myargs))
def message(self, msg):
if msg['type'] in ('chat', 'normal'):
#Store the received message
self.last_message = msg['body']
self.disconnect()
def read_ans(a,b,c):
xmpp = XMPP("user", "pass", [a,b,c])
if xmpp.connect():
xmpp.process(block=True)
# How can I return the message here?
return '!?!?'
if __name__ == '__main__':
read_ans(1,2,3)