简体   繁体   中英

XMPP threaded receiver in Python 3

What I want to do is set up an XMPP receiver using the Slixmpp library which listens for messages throughout the script execution. I think the threading library might provide a solution so tried that. This script is for an online PvP game and I need to receive information from the opponent continuously.

This is the code I have tried:

import time
import threading as td
import slixmpp as slix
import logging
import asyncio

my_jid = "test@xmpp.jp"
my_pass = "test"

class receiver(slix.ClientXMPP):
    def __init__(self, jid, password):
        slix.ClientXMPP.__init__(self, jid, password)
        self.add_event_handler("session_start", self.start)
        self.add_event_handler("message", self.message)

    def start(self, event):
        self.send_presence()
        self.get_roster()

    def message(self, msg):
        if msg['type'] in ('chat', 'normal'):
            msg.reply("Thanks for sending\n%(body)s" % msg).send()
            print(msg['body'])

def function():
    recv = receiver(my_jid, my_pass)
    recv.connect()
    recv.process()



newthread = threading.Thread(target=function)
logging.basicConfig(level="DEBUG", format='%(levelname)-8s %(message)s')


newthread.start()

input("Press Enter to continue")

This returns the following error:

Exception in thread Thread-1:
Press Enter to continueTraceback (most recent call last):
  File "C:\Program Files (x86)\Python37-32\lib\threading.py", line 917, in _bootstrap_inner
    self.run()
  File "C:\Program Files (x86)\Python37-32\lib\threading.py", line 865, in run
    self._target(*self._args, **self._kwargs)
  File "C:/Users/dps/Documents/GitHub/Python-Problems/UltimateTicTacToe-scripts/xmppp.py", line 46, in good
    recv = receiver(my_jid, my_pass)
  File "C:/Users/dps/Documents/GitHub/Python-Problems/UltimateTicTacToe-scripts/xmppp.py", line 32, in __init__
    slix.ClientXMPP.__init__(self, jid, password)
  File "C:\Users\dps\venv\lib\site-packages\slixmpp\clientxmpp.py", line 70, in __init__
    BaseXMPP.__init__(self, jid, 'jabber:client', **kwargs)
  File "C:\Users\dps\venv\lib\site-packages\slixmpp\basexmpp.py", line 48, in __init__
    XMLStream.__init__(self, **kwargs)
  File "C:\Users\dps\venv\lib\site-packages\slixmpp\xmlstream\xmlstream.py", line 219, in __init__
    self.disconnected = asyncio.Future()
  File "C:\Program Files (x86)\Python37-32\lib\asyncio\events.py", line 644, in get_event_loop
    % threading.current_thread().name)
RuntimeError: There is no current event loop in thread 'Thread-1'.

In my case executing:

newthread.daemon = True

Before calling:

newthread.start()

Works as expected creating a non-blocking thread.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM