Advanced Examples¶
The following examples should work out-of-the-box and assume you have your bot set up.
For setup, see the Bot setup guide.
Looking for examples about older features? Check out Legacy Examples
About these examples
Each example is self-contained and can be copied directly into your bot
between setup and bot.run()
.
Beware of similar command names!
Table of Contents¶
Adding Persistent Data¶
Demonstrates how to inject user-defined data to run alongside your bot. This example uses a PG database connection.
from dataclasses import dataclass
import asyncpg
@dataclass
class MyState(discord.BaseConfig):
pg_conn: asyncpg.Pool = None # pool of connections
@client.setup_hook
async def init_db(bot: discord.Client):
bot.config.pg_conn = await asyncpg.create_pool(
host="your-host",
user="your-username",
database="your-db-name"
)
print("DB pool initialized")
@client.shutdown_hook
async def close_db(bot: discord.Client):
await bot.config.pg_conn.close()
print("DB pool closed")
Note on .config
type
While .config
can technically be anything, it is recommended to use discord.BaseConfig
and the dataclass decorator.
Dataclasses make accessing fields more object-like instead of dict-like.
Requesting a Resource¶
Resources (like a channel or a message) can be requested for through client.
Demonstrates requesting a message to attach a thread.
@client.command(discord.SlashCommand('example', 'Demonstrates creating a thread from a resource!'), guild_id=GUILD_ID)
async def on_example(bot: discord.Client, event: discord.InteractionEvent):
resp = await event.interaction.respond('You got it!', with_response=True)
await bot.channel_from_id(event.interaction.channel_id).create_thread_from_message(resp.interaction.response_message_id, 'Thread name')