Skip to content
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

feat: Add possibility to start bot via async context manager #1801

Merged
2 changes: 2 additions & 0 deletions CHANGELOG.md
Expand Up @@ -12,6 +12,8 @@ These changes are available on the `master` branch, but have not yet been releas

### Added

- Added possibility to start bot via async context manager.
([#1801](https://github.com/Pycord-Development/pycord/pull/1801))
- Added new parameters (`author`, `footer`, `image`, `thumbnail`) to `discord.Embed`.
([#1996](https://github.com/Pycord-Development/pycord/pull/1996))
- Added new events `on_bridge_command`, `on_bridge_command_completion`, and
Expand Down
22 changes: 22 additions & 0 deletions discord/client.py
Expand Up @@ -30,6 +30,7 @@
import signal
import sys
import traceback
from types import TracebackType
from typing import TYPE_CHECKING, Any, Callable, Coroutine, Generator, Sequence, TypeVar

import aiohttp
Expand Down Expand Up @@ -253,6 +254,27 @@
VoiceClient.warn_nacl = False
_log.warning("PyNaCl is not installed, voice will NOT be supported")

async def __aenter__(self) -> Client:
loop = asyncio.get_running_loop()
self.loop = loop
self.http.loop = loop
self._connection.loop = loop

Check warning on line 261 in discord/client.py

View check run for this annotation

Codecov / codecov/patch

discord/client.py#L258-L261

Added lines #L258 - L261 were not covered by tests

self._ready = asyncio.Event()

Check warning on line 263 in discord/client.py

View check run for this annotation

Codecov / codecov/patch

discord/client.py#L263

Added line #L263 was not covered by tests

return self

Check warning on line 265 in discord/client.py

View check run for this annotation

Codecov / codecov/patch

discord/client.py#L265

Added line #L265 was not covered by tests

async def __aexit__(
self,
exc_t: BaseException | None,
exc_v: BaseException | None,
exc_tb: TracebackType | None,
) -> None:
if not self.is_closed():
await self.close()

Check warning on line 274 in discord/client.py

View check run for this annotation

Codecov / codecov/patch

discord/client.py#L273-L274

Added lines #L273 - L274 were not covered by tests

# internals

def _get_websocket(
self, guild_id: int | None = None, *, shard_id: int | None = None
) -> DiscordWebSocket:
Expand Down
29 changes: 29 additions & 0 deletions examples/basic_async_bot.py
@@ -0,0 +1,29 @@
import asyncio

import discord
from discord.ext import commands

bot = commands.Bot(
command_prefix=commands.when_mentioned_or("!"),
intents=discord.Intents.default(),
)


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


@bot.slash_command(guild_ids=[...]) # Create a slash command.
async def hello(ctx: discord.ApplicationContext):
"""Say hello to the bot""" # The command description can be supplied as the docstring
await ctx.respond(f"Hello {ctx.author.mention}!")


async def main():
async with bot:
await bot.start("TOKEN")


asyncio.run(main())