Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spyder: Cannot close a running event loop

I am currently checking out the Python discord wrapper found here but it doesn't seem to work due to the above mentioned error. I tried calling the nest_asyncio.apply() before running the client.run() function but it doesn't seem to work either as mentioned in this other question. This question is possibly a duplicate but couldn't add a comment in the previous one.

I tried this:

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

as well as this to no avail:

client = discord.Client()
nest_asyncio.apply(client.run(bot_token))
like image 401
whoami Avatar asked Nov 27 '25 11:11

whoami


1 Answers

I've faced a similar, if not the same issue a few months ago, and what I found on a comment to a github issue ultimately led to the following:


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)

This class wraps the discord client into it's own thread and event loop. You'd call your client something like:

dc = DiscordAccessor()
dc.client.whatever_you_want_to_call()
like image 91
Lukas Thaler Avatar answered Nov 29 '25 00:11

Lukas Thaler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!