Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Slash commands not syncing to specific guilds in discord.py

So I have a discord bot which overall functions correctly but the command sync behaves very strangely.

I've read that having the full global sync run in 'on_ready' is a bad idea and can get my bot rate limited, and that the alternative is to have a /sync function which exists only on a test server and will run the full tree.sync(). I've tried to implement this but for some reason I cannot get the /sync function to appear on my test server, and even worse for some reason my full global sync seems to be running anyway.

To test I have two different guilds, one of which is the main test guild that will be used for bot administration. Here's the relevant snippet of code:

# -- setup --
# create client
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
global_synced = False
tree = app_commands.CommandTree(client)

# -- events --
@client.event
async def on_ready():
    # sync commands
    await client.wait_until_ready()
    if(not global_synced):
        for g in guilds: 
            # Before I added this loop and following if statement I was getting a "403 Forbidden"
            # I guess the error was because the secondary guild doesn't have access to the
            # discord Object of the main guild? IDK
            if(g.id == TEST_GUILD_ID): 
                await tree.sync(guild=discord.Object(id=TEST_GUILD_ID))
                global_synced = True

# -- commands --
@tree.command(name = "run_bot", description="Runs the bot")
async def self(interaction: discord.Interaction):
    # this function is available to all guilds and runs the bot
    return

@tree.command(name = "sync", description="Syncs the bot commands", guild=discord.Object(id=TEST_GUILD_ID))
async def self(interaction: discord.Interaction):
    # this function is supposed to be available to only the main test server
    await client.wait_until_ready()
    await tree.sync()
    return

So here are my issues:

  1. "/sync" is not appearing in my main test guild
  2. "/run_bot" is appearing on my secondary test guild even though I explicitly said not to sync all?

I'm at a loss. I'm getting no errors and I've pored over the documentation but can't find an answer. Does it have something to do with asynchronous code (my ongoing nemesis)? Please help!

like image 221
Thomas Rosebrough Avatar asked Dec 04 '25 01:12

Thomas Rosebrough


1 Answers

You missed out the copy global commands to the guild.

self.tree.copy_global_to(guild=guild)
await self.tree.sync(guild=guild)
like image 66
Kim Avatar answered Dec 06 '25 17:12

Kim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!