Search code examples
pythondiscordbotspycord

Discord slash commands using python


I have been looking at stackoverflow posts and so many places but still can't find the answer to this question that works for me. How do I make discord python slash commands? Following this post :https://stackoverflow.com/questions/71165431/how-do-i-make-a-working-slash-command-in-discord-py#:~:text=import%20discord%20from%20discord.ext%20import%20commands%20create%20you,ids%20in%20which%20the%20slash%20command%20will%20appear. I got the error:

Traceback (most recent call last): File "/home/container/bot.py", line 3, in bot = discord.Bot(command_prefix="!") AttributeError: module 'discord' has no attribute 'Bot'

With this code:

import discord
from discord.ext import commands
bot = discord.Bot(command_prefix="!")
@bot.slash_command(name="first_slash") #Add the guild ids in which the slash command will appear. If it should be in all, remove the argument, but note that it will take some time (up to an hour) to register the command if it's for all guilds.
async def first_slash(ctx): 
    await ctx.respond("You executed the slash command!")

I tried replacing "bot = discord.Bot" with "bot = commands.Bot" but that didn't work either

The only code I found had no errors was:

import discord
from discord.ext import commands
from discord_slash import SlashCommand, SlashContext

bot = commands.Bot(command_prefix="!")
slash = SlashCommand(bot)
@slash.slash(name="test")
async def _test(ctx: SlashContext):
    await ctx.send("Hello World!")

But no slash commands appeared on discord


Solution

  • You have this error because you use discord's client and not discord.ext's.

    bot = commands.Bot(command_prefix='!',intents=discord.Intents.all()) #gets all intents for the bot to work
    

    Next up, slash won't be used (variable and event). Replace to this event:

    @bot.hybrid_command(put same args as the actual code)
    

    After this is done, update the Command Tree and it should appear no problem on Discord. Link here: https://discordpy.readthedocs.io/en/stable/interactions/api.html#commandtree

    Hope it helped. :D

    EDIT: try this, It's your code but I modified it (if it works well for me, it will work well for you):

    main.py:

    import os
    import discord
    from discord.ext import commands
    bot = discord.Bot(command_prefix="!",intents=discord.Intents.all()) #intents are required depending on what you wanna do with your bot
    
    @bot.hybrid_command(name="first_slash")
    async def first_slash(ctx): 
       await ctx.send("You executed the slash command!") #respond no longer works, so i changed it to send
    
    @bot.event
    async def on_ready():
       await bot.sync() #sync the command tree
       print("Bot is ready and online")
    
    bot.run("Put your token here")
    

    Now it should appear up to an hour after sync. Hope this helps more. (Little precision: if you use Pycord, the code will be different)