Home > OS >  How do I change my bot from using text/prefix based commands to slash commands and buttons in discor
How do I change my bot from using text/prefix based commands to slash commands and buttons in discor

Time:08-15

I've seen most developers are switching their bots to using slash commands instead of the usual prefix commands. How do I rewrite my bot using slash commands? I have no idea how to get started with slash commands.

CodePudding user response:

You need to install discord.py v2.0 by install the latest version: pip install -U git https://github.com/Rapptz/discord.py.

Basic example (free function command)

import asyncio

from discord.ext import commands
from discord import app_commands

# define Bot with **needed** parameters
bot = commands.Bot(command_prefix="some_prefix", intents=some_intents_definition)

# You can now use `@bot.tree.command()` as a decorator:
@bot.tree.command()
async def my_command(interaction: discord.Interaction) -> None:
  await interaction.response.send_message("Hello from my command!")
### NOTE: the above is a global command, see the `main()` func below:


async def main():
  async with bot:
    # do you setup stuff if you need it here, then:
    bot.tree.copy_global_to(guild=discord.Object(id=...))  # we copy the global commands we have to a guild, this is optional
    await bot.start(MY_TOKEN)

You can find more examples here: https://gist.github.com/AbstractUmbra/a9c188797ae194e592efe05fa129c57f


References:
  • Related