Skip to content

Commit

Permalink
feat: Add possibility to start bot via async context manager (#1801)
Browse files Browse the repository at this point in the history
* feat: Add possibility to start bot via async context manager

* fix: Add type hints to __aexit__

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* doc: Add async context manager to changelog

* example: Add example to start bot with async context manager

Add basic example to start the bot with an async context manager.
The example contains a `/hello` slash command which responds with a
"Hellp @author".

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Signed-off-by: Lala Sabathil <lala@pycord.dev>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Lala Sabathil <lala@pycord.dev>
  • Loading branch information
3 people authored Apr 18, 2023
1 parent f553fde commit 8a913c3
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 0 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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 @@ def __init__(
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

self._ready = asyncio.Event()

return self

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()

# 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
Original file line number Diff line number Diff line change
@@ -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())

0 comments on commit 8a913c3

Please sign in to comment.