Need help making a slash command

Question:
I have this bot and I want to make a slash command for it, and this isn’t working.

Current code in main.py:

import os
import random

import discord
from discord.ext import commands

intents = discord.Intents.default()
intents.message_content = True

client = discord.Client(intents=intents, application_id=...)  # I hid the App ID


@client.tree.command(name="test", description="test thing")
async def _space(ctx: discord.interactions.Interaction):
    await ctx.response.send_message("cool")


@client.event
async def on_ready():
    print(f"Using discord.py version {discord.__version__}")
    await client.change_presence(
        activity=discord.Activity(
            type=discord.ActivityType.listening, name="goose beats"
        )
    )
    print("Logged in as {0.user}".format(client))
    await client.tree.sync()
    channel = client.get_channel(1174865964760834078)
    await channel.send("goos is loaded!!")


try:
    token = os.getenv("TOKEN") or ""
    if token == "":
        raise Exception("Please add your token to the Secrets pane.")
    client.run(token)
except discord.HTTPException as e:
    if e.status == 429:
        print("The Discord servers denied the connection for making too many requests")
        print(
            "Get help from"
            " https://stackoverflow.com/questions/66724687/in-discord-py-how-to-solve-the-error-for-toomanyrequests"
        )
    else:
        raise e

Some of the code was hidden as it is irrelevant (aka just message interaction stuff) and I get this error:

Traceback (most recent call last):
  File "/home/runner/PyGoose/main.py", line 34, in <module>
    @client.tree.command(name="test", description="test thing")
AttributeError: 'Client' object has no attribute 'tree'

Any fixes?

Nevermind, it works now! I updated my code using this stackoverflow question: python - How do i make a working slash command in discord.py - Stack Overflow.

If anyone has a simpler solution, please send it here. For now, this works!

1 Like

I don’t think there is. Following https://raw.githubusercontent.com/Rapptz/discord.py/master/examples/app_commands/basic.py (except obviously use Secrets) should be the best way in terms of code maintainability.


I could find your app ID in seconds. If that matters, use secrets to store it.

2 Likes

There’s no such thing; this is the only way to use slash commands with discord.py unless you find a separate library that simplifies it, which I doubt you will. Even if you do, it will most likely be deprecated.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.