C-Python异步:在线程中运行discord.py

时间:2019-03-06 19:22:43

标签: c python-3.x asynchronous python-asyncio discord.py

由于无法阻止主线程,因此必须在单独的线程中启动discord.py。
它是游戏服务器C/Python 3.7 (ubuntu 18)

C代码:

int pysDiscord_Init;
...
PyObject *psv_discord;

psv_discord = Python_LoadModule("sv_discord");
if (psv_discord != NULL) {
  pysDiscord_Init = Python_RegisterFunction(psv_discord, "sv_discord", "init");
  Python_Execute(pysDiscord_Init, "");
}

sv_discord.py

import discord
import asyncio
import threading
from concurrent.futures import ThreadPoolExecutor
import multiprocessing

TOKEN = '12345'

client = discord.Client()

def init():
    print("Initializing Discord...")
    print("current_thread: %s" % threading.current_thread())
    t = threading.Thread(target=client.run, args=(TOKEN,))
    t.start()

or

def init():
    print("Initializing Discord...")
    print("current_thread: %s" % threading.current_thread())
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    asyncio.get_child_watcher().attach_loop(loop)
    pool = ThreadPoolExecutor(max_workers=multiprocessing.cpu_count())
    task = loop.run_in_executor(pool, client.run, TOKEN)
    loop.run_until_complete(task)

set_wakeup_fd例外:

...
Initializing Discord...
current_thread: <_MainThread(MainThread, started 4150019840)>

Exception in thread Thread-1:
 Traceback (most recent call last):
 File "./build/Lib/asyncio/unix_events.py", line 92, in add_signal_handler
 ValueError: set_wakeup_fd only works in main thread

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
 File "./build/Lib/threading.py", line 917, in _bootstrap_inner
 File "./build/Lib/threading.py", line 865, in run
 File "./../source/discord.py-rewrite/discord/client.py", line 550, in run
 File "./build/Lib/asyncio/unix_events.py", line 94, in add_signal_handler
RuntimeError: set_wakeup_fd only works in main thread

我应该提到我在python上尝试了相同的代码(没有C代码),并且可以正常工作。
此错误告诉我有关主线程的信息。但是我没有在新线程内创建sv_discord,正如您从日志中看到的那样,它是"Main"方法内的init()线程。我不明白。

2 个答案:

答案 0 :(得分:1)

我有一个类似的情况(实际上不是asyncio的预期用途,但到底是什么)我需要在其中线程discord.py实例的地方。

我最终使用以下内容修改了您的解决方案:

class discordHost(discord.Client):
    async def on_ready(self):
        print(f'{DThread.discord_client.user} has connected.')

class Threader(Thread):
    def __init__(self):
        Thread.__init__(self)
        self.loop = asyncio.get_event_loop()
        self.start()

    async def starter(self):
        self.discord_client = discordHost()
        await self.discord_client.start(DISCORD_TOKEN)

    def run(self):
        self.name = 'Discord.py'

        self.loop.create_task(self.starter())
        self.loop.run_forever()

if not 'Discord.py' in [t.name for t in tenumerate()]:
    DThread = Threader()

这大致上是相同的,但是我将Thread子类化并discord.Client子类化,以便更轻松地处理两者的结果。

这里的唯一警告是,asyncio.get_event_loop()必须先被称为 Thread.start(),否则会造成混乱并丢失其上下文主线程。

答案 1 :(得分:0)

回答我自己的问题:

我应该感谢这个来源asyncio-you-are-a-complex-beast,终于找到了解决方法。
最终的工作代码如下:

import discord
import asyncio
import threading

TOKEN = '12345'
client = discord.Client()


async def start():
    await client.start(TOKEN) # use client.start instead of client.run


def run_it_forever(loop):
    loop.run_forever()


def init():
    asyncio.get_child_watcher() # I still don't know if I need this method. It works without it.

    loop = asyncio.get_event_loop()
    loop.create_task(start())

    thread = threading.Thread(target=run_it_forever, args=(loop,))
    thread.start()


@client.event
async def on_message(message):
    if message.author == client.user:
        return

    print("on_message content: %s, channel: %s" % (message.content, message.channel))
    await message.channel.send('Hello!')


@client.event
    async def on_ready():
    print("Discord bot logged in as: %s, %s" % (client.user.name, client.user.id))

我的主要错误是,对于游戏,我通过点子在系统内部编译并使用了最新的rewrite版本,而我不得不0.16.12并阅读了documentation for 0.16.12,在discord.py.rewrite(例如在on_message内部,我使用了错误的client.send_message,而我不得不使用message.channel.send