From a4b537dc0013d01786500cd4e5b141c9fd40ef53 Mon Sep 17 00:00:00 2001 From: Alexander Date: Sun, 2 Apr 2023 11:56:39 +0200 Subject: [PATCH] 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". --- examples/basic_async_bot.py | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 examples/basic_async_bot.py diff --git a/examples/basic_async_bot.py b/examples/basic_async_bot.py new file mode 100644 index 0000000000..6588554251 --- /dev/null +++ b/examples/basic_async_bot.py @@ -0,0 +1,32 @@ +import asyncio + +import discord +from discord.ext import commands + +class Bot(commands.AutoShardedBot): + def __init__(self): + super().__init__( + command_prefix="!", + intents=discord.Intents.default(), + ) + + async def on_ready(self): + print("Ready called!") + +def main(): + asyncio.run(start_bot_session()) + +async def start_bot_session(): + async with Bot() as bot: + # NOTE: + # Better add those slash commands to a cog (check examples/app_commands/slash_cog). + # But for the purpose of simplicity, we just define the command here. + @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}!") + + await bot.start("TOKEN") + +if __name__ == "__main__": + main()