I’m currently developing a Discord bot with py-cord and facing a challenge with the registration of slash commands. They appear to be registering globally rather than just within specific guilds, which causes delays in their visibility.
Here’s the content of my main bot script:
import discord
import os
from dotenv import load_dotenv
# Load environment variables
env_path = os.path.join(os.path.dirname(__file__), 'config', '.env')
load_dotenv(env_path)
# Get token and IDs
BOT_TOKEN = os.getenv("DISCORD_TOKEN")
SERVER_ID = os.getenv("DISCORD_GUILD")
APPLICATION_ID = os.getenv("DISCORD_APPLICATION")
# Create a bot instance
bot = discord.Bot()
# Event on bot ready
@bot.event
async def on_ready():
print(f"{bot.user} is ready!")
# List of cogs to load
cogs = [
'welcome',
'calculator',
]
for cog in cogs:
bot.load_extension(f'cogs.{cog}')
# Command to sync commands
@bot.command(name="sync")
async def sync_commands(ctx):
synced = await bot.tree.sync()
print(f"Synced {len(synced)} command(s) successfully.")
bot.run(BOT_TOKEN)
And here’s a snippet from one of my cog files:
import discord
from discord.ext import commands
class Welcome(commands.Cog):
def __init__(self, bot):
self.bot = bot
@discord.slash_command(name="hi", description="Greets the user")
async def greet(self, ctx):
await ctx.respond('Hello!')
@discord.slash_command(name="bye", description="Says goodbye")
async def farewell(self, ctx):
await ctx.respond('Goodbye!')
# Register the cog with the bot
def setup(bot):
bot.add_cog(Welcome(bot))
I’ve encountered this sync function online, but I’m getting an error stating that ‘tree’ is undefined. What strategies can I apply to achieve faster or on-demand syncing for my slash commands? Any insights would be greatly appreciated.