I’m in the process of creating a Discord bot that utilizes cogs, following the guidance provided in the py-cord documentation. However, I’m facing an issue where my slash commands appear to be registered globally instead of being specific to individual guilds, which is leading to significant delays in their availability.
Here’s the code for my main bot file:
import discord
import os
from dotenv import load_dotenv
# Load environment settings
env_file = os.path.join(os.path.dirname(__file__), '..', 'config', '.env')
load_dotenv(env_file)
# Bot settings
TOKEN = os.getenv("BOT_TOKEN")
GUILD_ID = os.getenv("SERVER_ID")
APP_ID = os.getenv("APPLICATION_ID")
# Initialize the bot
client = discord.Bot()
@client.event
async def on_ready():
print(f"{client.user} has connected successfully!")
# Load cogs
extensions = [
'commands.welcome',
'commands.calculator',
]
for ext in extensions:
client.load_extension(f'modules.{ext}')
# Sync commands on demand
@client.command(name="refresh")
async def refresh(ctx):
result = await client.tree.sync()
print(f"Refreshed {len(result)} command(s)")
client.run(TOKEN)
And here’s an example of one of my cogs:
import discord
from discord.ext import commands
class Welcome(commands.Cog):
def __init__(self, client):
self.client = client
@discord.slash_command(name="hi", description="Says hi to user")
async def hi(self, ctx):
await ctx.respond('Hi there!')
@discord.slash_command(name="bye", description="Says goodbye to user")
async def bye(self, ctx):
await ctx.respond('See you later!')
def setup(client):
client.add_cog(Welcome(client))
I’ve attempted to use the sync function but I’m encountering an error stating that the tree attribute does not exist. What steps can I take to ensure these commands are registered more quickly, or to sync them as needed? I’m looking for a solution that allows for instant visibility when testing rather than experiencing significant delays.