簡體   English   中英

Python3 Web服務器在IRC bot的線程之間進行通信

[英]Python3 webserver communicate between threads for IRC bot

我已經閱讀了很多有關線程,隊列,池化等的文檔,但是仍然不知道如何解決我的問題。 情況如下:我構建了一個由cherrypy服務的python3 Django應用程序。 該應用程序基本上是另一個IRC客戶端。 當我第一次使用GUI運行我的代碼時,一個IRC僵屍程序通過守護進程線程啟動並偵聽事件。 我的問題如下:如何向該線程(和我的機器人)發送數據,例如告訴他加入第二個通道? 當我第二次運行代碼時,顯然會創建我的機器人的新實例以及新的服務器連接。 我需要一種通過GUI交互與我的機器人進行通信的方法。 現在,我必須讓我的機器人對特定事物做出反應的唯一方法是讀取數據庫。 其他一些GUI操作將更改該數據庫。 這是一個糟糕的系統。

這是啟動我的機器人的相關代碼。

def DCC_deamonthread(c, server, nickname, upload):
    try:
        c.connect(server, 6667, nickname)
        c.start()
    except irc.client.ServerConnectionError as x:
        log("error" + str(x)).write()
        upload.status, upload.active = "Error during connection", False
        upload.save()

def upload_file(filename, rec_nick, pw):
    global upload
    Upload_Ongoing.objects.all().delete()
    upload = Upload_Ongoing(filename=filename,status="Connecting to server...", active=True)
    upload.save()
    irc.client.ServerConnection.buffer_class.encoding = 'latin-1'
    c = DCCSend(filename, rec_nick, pw)
    server = "irc.rizon.net"
    nickname = ''.join(random.choice(string.ascii_lowercase) for i in range(10))
    t = threading.Thread(target=DCC_deamonthread, args=(c, server, nickname, upload))
    t.daemon=True
    t.start()

正如您所注意到的,問題是,每次上傳時,您都會產生一個新的線程/機器人。 一個可能的解決方案是重寫代碼以執行以下操作:

event_queue = multiprocessing.Queue() # Events that will be sent to the IRC bot thread

def irc_bot_thread():
    bot = connect_to_irc()

    for event in event_queue:
        bot.handle_event(event)

threading.Thread(target=irc_bot_thread).start()

def upload_file(filename, rec_nick, pw):
    # Django stuff

    event_queue.push(<necessary data for use by the bot>)

暫無
暫無

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

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