簡體   English   中英

Python 3 中的 XMPP 螺紋接收器

[英]XMPP threaded receiver in Python 3

我想要做的是使用 Slixmpp 庫設置一個 XMPP 接收器,該庫在整個腳本執行過程中偵聽消息。 我認為線程庫可能會提供一個解決方案,所以嘗試過。 此腳本用於在線 PvP 游戲,我需要不斷從對手那里接收信息。

這是我試過的代碼:

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")

這將返回以下錯誤:

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'.

在我的情況下執行:

newthread.daemon = True

打電話前:

newthread.start()

按預期工作創建一個非阻塞線程。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM