Skip to content

Conversation

DA-344
Copy link
Contributor

@DA-344 DA-344 commented Nov 11, 2024

Summary

This PR refactors the Client.run logic to fix problems involving asyncio due to how the library used the loop:

Needs testing

Exception
  File "/home/container/main.py", line 23, in <module>
    bot.run(BOT_TOKEN)

  File "/home/container/.local/lib/python3.11/site-packages/discord/client.py", line 772, in run
    loop.run_forever()

  File "/usr/local/lib/python3.11/asyncio/base_events.py", line 608, in run_forever
    self._run_once()

  File "/usr/local/lib/python3.11/asyncio/base_events.py", line 1936, in _run_once
    handle._run()

  File "/usr/local/lib/python3.11/asyncio/events.py", line 84, in _run
    self._context.run(self._callback, *self._args)

  File "/usr/local/lib/python3.11/asyncio/selector_events.py", line 956, in _read_ready
    self._read_ready_cb()

  File "/usr/local/lib/python3.11/asyncio/selector_events.py", line 988, in _read_ready__get_buffer
    self._protocol.buffer_updated(nbytes)

  File "/usr/local/lib/python3.11/asyncio/sslproto.py", line 439, in buffer_updated
    self._do_handshake()

  File "/usr/local/lib/python3.11/asyncio/sslproto.py", line 560, in _do_handshake
    self._sslobj.do_handshake()

  File "/usr/local/lib/python3.11/ssl.py", line 979, in do_handshake
    self._sslobj.do_handshake()

Information

  • This PR fixes an issue.
  • This PR adds something new (e.g. new method or parameters).
  • This PR is a breaking change (e.g. methods or parameters removed/renamed).
  • This PR is not a code change (e.g. documentation, README, typehinting,
    examples, ...).

Checklist

  • I have searched the open pull requests for duplicates.
  • If code changes were made then they have been tested.
    • I have updated the documentation to reflect the changes.
  • If type: ignore comments were used, a comment is also left explaining why.
  • I have updated the changelog to include these changes.

@Lulalaby Lulalaby requested review from NeloBlivion, plun1331 and Dorukyum and removed request for ChickenDevs November 11, 2024 23:03
DA-344 and others added 2 commits November 19, 2024 08:23
Co-authored-by: Dorukyum <[email protected]>
Signed-off-by: DA344 <[email protected]>
Co-authored-by: Dorukyum <[email protected]>
Signed-off-by: DA344 <[email protected]>
@DA-344
Copy link
Contributor Author

DA-344 commented Nov 19, 2024

Applied all the changes Dorukyum requested.

Before merging, I would like some feedback on this discussion message

@DA-344
Copy link
Contributor Author

DA-344 commented Sep 1, 2025

Pls fix Luma's issue

This has been fixed on the latest commit.

@Lumabots
Copy link
Contributor

Lumabots commented Sep 2, 2025

I'll review and test that around 1pm

Copy link
Member

@Paillat-dev Paillat-dev left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Still having issues. Seems like changing to _loop in DiscordWebSocket fixes it but I'll let you confirm.

INFO:discord.client:logging in using static token
Traceback (most recent call last):
  File "C:\Users\jerem\Documents\pycord\pycord\test_client_async.py", line 39, in <module>
    asyncio.run(main())
  File "C:\Users\jerem\AppData\Roaming\uv\python\cpython-3.12.11-windows-x86_64-none\Lib\asyncio\runners.py", line 195, in run
    return runner.run(main)
           ^^^^^^^^^^^^^^^^
  File "C:\Users\jerem\AppData\Roaming\uv\python\cpython-3.12.11-windows-x86_64-none\Lib\asyncio\runners.py", line 118, in run
    return self._loop.run_until_complete(task)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\jerem\AppData\Roaming\uv\python\cpython-3.12.11-windows-x86_64-none\Lib\asyncio\base_events.py", line 691, in run_until_complete
    return future.result()
           ^^^^^^^^^^^^^^^
  File "C:\Users\jerem\Documents\pycord\pycord\test_client_async.py", line 33, in main
    await bot.start(os.getenv("TOKEN_2", ""))
  File "C:\Users\jerem\Documents\pycord\pycord\discord\client.py", line 872, in start
    await self.connect(reconnect=reconnect)
  File "C:\Users\jerem\Documents\pycord\pycord\discord\client.py", line 759, in connect
    self.ws = await asyncio.wait_for(coro, timeout=60.0)
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\jerem\AppData\Roaming\uv\python\cpython-3.12.11-windows-x86_64-none\Lib\asyncio\tasks.py", line 520, in wait_for
    return await fut
           ^^^^^^^^^
  File "C:\Users\jerem\Documents\pycord\pycord\discord\gateway.py", line 348, in from_client
    ws = cls(socket, loop=client.loop)
                          ^^^^^^^^^^^
  File "C:\Users\jerem\Documents\pycord\pycord\discord\client.py", line 367, in loop
    raise RuntimeError("loop is not set")
RuntimeError: loop is not set
ERROR:asyncio:Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0x0000019183896540>
ERROR:asyncio:Unclosed connector
connections: ['deque([(<aiohttp.client_proto.ResponseHandler object at 0x00000191843B9A30>, 47503.546)])']
connector: <aiohttp.connector.TCPConnector object at 0x0000019183A48F80>

Test Code
import os
from discord import *
import asyncio
import logging

from dotenv import load_dotenv

logging.basicConfig(level=logging.INFO)

load_dotenv()

bot = Bot(intents=Intents.all())


class MyCog(Cog):
    """Example cog for the bot"""

    def __init__(self, bot: Bot):
        self.bot: Bot = bot

    @Cog.listener()
    async def on_ready(self):
        print(f"Logged in as {self.bot.user} (ID: {self.bot.user.id})")


async def load_cogs():
    bot.add_cog(MyCog(bot))

async def main():
    await load_cogs()

    try:
        await bot.start(os.getenv("TOKEN_2", ""))
    except KeyboardInterrupt:
        await bot.close()


if __name__ == "__main__":
    asyncio.run(main())

Edit, no, that's not all, if you leave it running for some time after, leads to

Exception in thread Thread-1:
Traceback (most recent call last):
  File "C:\Users\jerem\AppData\Roaming\uv\python\cpython-3.12.11-windows-x86_64-none\Lib\threading.py", line 1075, in _bootstrap_inner
    self.run()
  File "C:\Users\jerem\Documents\pycord\pycord\discord\gateway.py", line 167, in run
    f = asyncio.run_coroutine_threadsafe(coro, loop=self.ws.loop)
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\jerem\AppData\Roaming\uv\python\cpython-3.12.11-windows-x86_64-none\Lib\asyncio\tasks.py", line 950, in run_coroutine_threadsafe
    loop.call_soon_threadsafe(callback)
    ^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'call_soon_threadsafe'
C:\Users\jerem\AppData\Roaming\uv\python\cpython-3.12.11-windows-x86_64-none\Lib\threading.py:1077: RuntimeWarning: coroutine 'DiscordWebSocket.send_heartbeat' was never awaited
  self._invoke_excepthook(self)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
WARNING:discord.gateway:Can't keep up, shard ID None websocket is 49.8s behind.
WARNING:discord.gateway:Can't keep up, shard ID None websocket is 99.4s behind.
WARNING:discord.gateway:Can't keep up, shard ID None websocket is 149.0s behind.

Copy link
Contributor

@Lumabots Lumabots left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

test and works great with and without my overlap pr, no idea about paillat issue tho

Paillat-dev
Paillat-dev previously approved these changes Sep 8, 2025
Copy link
Member

@Paillat-dev Paillat-dev left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Alright looks good, can't find any problem. Merge coflicts, and @Lumabots please test your loop stuff one last time with the latest changes.

@Lumabots
Copy link
Contributor

Lumabots commented Sep 8, 2025

tested and no issue with #2771

Lumabots
Lumabots previously approved these changes Sep 8, 2025
Copy link
Contributor

@Lumabots Lumabots left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@Paillat-dev
Copy link
Member

@Lulalaby when your merge this (once review is good) pls make sure to squash so that we can put it in rc2 and then revert it easily if problems

Copy link
Member

@Paillat-dev Paillat-dev left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Luma comment

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
hold: testing This pull request requires further testing
Projects
None yet
Development

Successfully merging this pull request may close these issues.

7 participants