Reputation: 23
I want to sync all slash commands with all guilds in discord.py
My code
import discord
from discord import app_commands
from discord.ext import commands
intents = discord.Intents.default()
client = discord.Client(intents=intents)
tree = app_commands.CommandTree(client)
@client.event
async def on_ready():
print(f'We have logged in as {client.user}')
try:
await tree.sync(guild=discord.Object(id=11234411))
print(f'Synced')
except Exception as e:
print(e)
@tree.command(name="ping", description="Simple ping pong command", guild=discord.Object(id=1032007648566059142))
async def ping(interaction):
await interaction.response.send_message(f"Pong", ephemeral=True)
I tried to just delete the guild=discord.Object(id=11234411) But its not working
Upvotes: 1
Views: 22433
Reputation: 79
I solved this issue by instead of defining a client, I used a bot, which is just an extension of client and can execute both slash command and regular command. You don't have to import app_commands for it.
bot = commands.Bot(command_prefix="/", intents=intents,
case_insensitive=False,)
I define my slash command in the following way:
@bot.tree.command(name="match", description="looking for a match")
async def match(interaction, arg1: str):
***rest of the code***
I define my regular command for syncing as follows:
@bot.command()
async def sync(ctx):
print("sync command")
if ctx.author.id == OWNER_USERID:
await bot.tree.sync()
await ctx.send('Command tree synced.')
else:
await ctx.send('You must be the owner to use this command!')
You can now call the regular "/sync" command to sync the slash commands. Be careful, if you also have on_message event then add await bot.process_commands(message)
. This is because, by default, the on_message event blocks command processing, and if you want to process the message as a command, you need to use that block of code.
Upvotes: 4
Reputation: 179
You shouldn't sync your commands in on_ready
because it's unnecessary and can get you ratelimited. You should create a owner-only command to sync the command tree instead.
@tree.command(name='sync', description='Owner only')
async def sync(interaction: discord.Interaction):
if interaction.user.id == YOUR_ID:
await tree.sync()
print('Command tree synced.')
else:
await interaction.response.send_message('You must be the owner to use this command!')
You don't need to include guild
anywhere because you're syncing global commands. Your extra saftey/security you can create a message command instead.
Upvotes: 3