Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I change my bot from using text/prefix based commands to slash commands and buttons in discord.py?

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.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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:
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading