3

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))
Lukas Thaler
  • 2,672
  • 5
  • 15
  • 31
whoami
  • 83
  • 9

1 Answers1

2

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()
Lukas Thaler
  • 2,672
  • 5
  • 15
  • 31
  • 1
    After making some changes to make it work for Python 3(Thread module has been deprecated), I still get the same error on Spyder. – whoami Mar 11 '20 at 08:05
  • What Python version and discord.py-version are you running? I've been using this with Python 3.6 and discord.py 1.2.5 – Lukas Thaler Mar 11 '20 at 08:07
  • Python 3.7.4 with discord.py 1.3.2 – whoami Mar 11 '20 at 08:09
  • I probably should point out I've been using `threading.Thread`, forgot to add my imports. That said, I have never tested this solution with any other setup than the one I mentioned – Lukas Thaler Mar 11 '20 at 08:16