Spyder:无法关闭正在运行的事件循环

时间:2020-03-11 06:50:50

标签: python discord

我目前正在检查Python不和谐包装器found here,但由于上述错误,它似乎不起作用。我尝试在运行nest_asyncio.apply()函数之前先调用client.run(),但是它似乎也无法像其他question中提到的那样工作。这个问题可能是重复的,但无法在前一个问题中添加评论。

我尝试过:

nest_asyncio.apply()
client = discord.Client()
client.run(bot_token)

以及无济于事:

client = discord.Client()
nest_asyncio.apply(client.run(bot_token))

1 个答案:

答案 0 :(得分:2)

几个月前,我遇到了类似的问题,即使不是同一个问题,而我在comment to a github issue上发现的问题最终导致了以下问题:


class DiscordAccessor:
    '''class to handle discord authentication and async loop handling
    Attributes
    ----------
        dc_coroutine
            the coroutine to start the client
        dc_thread
            the thread to keep the coroutine alive
    Methods
    -------
        start_loop
            starts the async loop'''
    dc_loop = asyncio.new_event_loop()
    client = discord.Client(loop=dc_loop)

    def __init__(self):
        self.dc_coroutine = DiscordAccessor.client.start('YOUR_TOKEN')
        self.dc_thread = threading.Thread(target=self.start_loop,
                                args=(self.dc_loop, self.dc_coroutine))
        self.dc_thread.start()

    def start_loop(self, loop, coro):
        '''starts the async loop
        Parameters
        ----------
            loop
                the asyncio loop
            coro
                the coroutine'''
        loop.run_until_complete(coro)

此类将不和谐的客户端包装到其自己的线程和事件循环中。您会给客户打电话,例如:

dc = DiscordAccessor()
dc.client.whatever_you_want_to_call()