Skip to content

refactor: Update Client.run to have a better async I/O usage #2645

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 32 commits into
base: master
Choose a base branch
from

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

@Dorukyum Dorukyum added the hold: testing This pull request requires further testing label Mar 31, 2025
@Lumabots
Copy link
Contributor

Lumabots commented May 10, 2025

i tested this pr on my prod bot for some hours and nothing to issue to signal

Lumabots
Lumabots previously approved these changes May 10, 2025
@DA-344
Copy link
Contributor Author

DA-344 commented May 27, 2025

I've done some testing and it has been working as expected. Can this pr get any review more/merge ?

@Paillat-dev
Copy link
Member

This is required if we ever want py 3.14 support, see my pr about that

@DA-344
Copy link
Contributor Author

DA-344 commented May 27, 2025

Not just for 3.14 support, but to fix all asyncio related issues that can be presented in any version due to how the AbstractEventLoop is currently handled.

VincentRPS
VincentRPS previously approved these changes May 27, 2025
Copy link
Contributor

@VincentRPS VincentRPS left a comment

Choose a reason for hiding this comment

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

LGTM

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.

lgtm as long as that MISSING comment is resolved in some way or another, nice pr

@Paillat-dev
Copy link
Member

Could be neat if we could get this merged for 2.7

@Paillat-dev
Copy link
Member

Also please @DA-344 fix conflicts (sry 😅)

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.

Need to test something

@Paillat-dev
Copy link
Member

Paillat-dev commented Jul 25, 2025

@DA-344 The test code below crashes, can you take a look ? I think it has to do with self.loop now being a property, maybe self._loop should be passed to HTTPClient but I am not 100% sure.

loop=self.loop,

Traceback (most recent call last):
  File "C:\Users\Jérémie\Documents\GitHub\pycord\thing.py", line 12, in <module>
    bot = discord.Bot(intents=discord.Intents.all())
  File "C:\Users\Jérémie\Documents\GitHub\pycord\discord\bot.py", line 1171, in __init__
    super().__init__(*args, **options)
    ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^
  File "C:\Users\Jérémie\Documents\GitHub\pycord\discord\bot.py", line 97, in __init__
    super().__init__(*args, **kwargs)
    ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^
  File "C:\Users\Jérémie\Documents\GitHub\pycord\discord\cog.py", line 610, in __init__
    super().__init__(*args, **kwargs)
    ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^
  File "C:\Users\Jérémie\Documents\GitHub\pycord\discord\client.py", line 250, in __init__
    loop=self.loop,
         ^^^^^^^^^
  File "C:\Users\Jérémie\Documents\GitHub\pycord\discord\client.py", line 330, in loop
    raise RuntimeError("loop is not set")
RuntimeError: loop is not set
Test Code
import os
import discord
import asyncio
import logging

from dotenv import load_dotenv

logging.basicConfig(level=logging.INFO)

load_dotenv()

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

@bot.event
async def on_ready():
    print(f"Logged in as {bot.user} ({bot.user.id})")

options = [
    "Option 1",
    "Option 2",
    "Option 3",
    "Option 4",
]

async def my_autocomplete(ctx: discord.AutocompleteContext):
    """Autocomplete function for the command"""
    query = ctx.value.lower()
    return [option for option in options if query in option.lower()]


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

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

    @discord.command(name="hello")
    @discord.option(
        name="option",
        description="An example option",
        required=True,
        autocomplete=my_autocomplete,
    )
    async def hello(self, ctx: discord.ApplicationContext, option: str):
        await ctx.respond(f"Hello! You selected: {option}")


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


async def main():
    await load_cogs()

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


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

@DA-344
Copy link
Contributor Author

DA-344 commented Jul 26, 2025

@DA-344 The test code below crashes, can you take a look ? I think it has to do with self.loop now being a property, maybe self._loop should be passed to HTTPClient but I am not 100% sure.

Yup, I forgot to update that to use _loop instead of loop, should be fixed now.

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