To create a command using Discord's native commands system in discord.py, you'll need to use the discord.ext.commands extension. As of April 2021, the discord.py library introduced support for Discord's slash commands, which are part of Discord's interactions API.
Below is an example of how you can create a slash command /tableflip using discord.py with the discord-py-interactions library, which is commonly used to handle interactions like slash commands.
First, make sure you have the library installed:
pip install -U discord-py-interactions
Now, here's the code to create a simple /tableflip command:
import discord
from discord.ext import commands
from discord_slash import SlashCommand, SlashContext
intents = discord.Intents.default()
client = commands.Bot(command_prefix="!", intents=intents)
slash = SlashCommand(client, sync_commands=True) # Initialize slash commands
# Define the /tableflip command
@slash.slash(name="tableflip", description="Flips a table!")
async def tableflip(ctx: SlashContext):
await ctx.send("┻━┻ ︵ヽ(`Д´)ノ︵ ┻━┻")
# Define the /showimage command which takes an image URL as an argument
@slash.slash(name="showimage", description="Displays an image from a URL.")
async def showimage(ctx: SlashContext, url: str):
await ctx.send(content="Here's your image:", embed=discord.Embed().set_image(url=url))
client.run("YOUR_BOT_TOKEN")
Explanation:
-
Library Initialization: We initialize a Bot instance with a prefix and use the SlashCommand class to register slash commands.
-
Tableflip Command: This command simply sends an ASCII art of a table flip when invoked.
-
Showimage Command: This command demonstrates how to handle a string parameter, which is a URL pointing to an image. When you run the /showimage [url] command, it will send an embedded message with the image from the URL.
Important Notes:
- Replace
"YOUR_BOT_TOKEN" with your actual Discord bot token.
- To use slash commands, your bot requires a specific set of permissions, including
applications.commands.
- After deploying changes to slash commands, it may take a few minutes for them to propagate across all servers your bot is in.
- The
discord-py-interactions library simplifies the slash command implementation but requires you to keep up with any major changes or updates in Discord's API. As of the writing, the discord.py project stopped maintaining the library, hence any continuation with the library should consider community forks or alternatives for up-to-date features.
This is a basic implementation, and there are many more functionalities you can implement, like handling options, contexts, sub-commands, etc.