Skip to content

Instantly share code, notes, and snippets.

@mudkipdev
Last active June 2, 2023 04:28
Show Gist options
  • Save mudkipdev/8cddcaed55ac99e4ec252a18bd0a42c3 to your computer and use it in GitHub Desktop.
Save mudkipdev/8cddcaed55ac99e4ec252a18bd0a42c3 to your computer and use it in GitHub Desktop.
A basic slash command example for discord.py v2.x.
from discord.ext import commands
from discord import app_commands
import discord
intents = discord.Intents.default()
intents.message_content = True # Ignore this line if you're not using prefix commands.
# You could use a client here instead, if you don't want to use prefix/hybrid commands.
bot = commands.Bot(intents=intents, command_prefix="!")
# You must sync your slash commands in order for them to appear.
# A prefix command is the preferred way to sync. Note that it might
# take a few minutes for your slash commands to show up, you can also
# try refreshing your Discord client with Ctrl + R.
@bot.command(description="Syncs your slash commands to the Discord API.")
async def sync(ctx: commands.Context) -> None:
await ctx.send("Syncing commands...")
await bot.tree.sync()
@app_commands.describe(
member="The member to ban.",
reason="The reason for banning them.",
delete_messages="Whether to clear their messages in the past day.",
)
@app_commands.guild_only()
@app_commands.checks.bot_has_permissions(ban_members=True)
@app_commands.checks.has_permissions(ban_members=True)
# In an extension, this would be @app_commands.command() instead.
# All slash command arguments need to have type hints. (e.g. str, int, discord.Member, etc)
@bot.tree.command(description="Permanently bans a member from the server.")
async def ban(
interaction: discord.Interaction,
member: discord.Member,
reason: str,
delete_messages: bool = False,
) -> None:
if (
interaction.user.top_role > member.top_role
and interaction.guild.me.top_role > member.top_role
and member != interaction.user
and member != bot.user
):
seconds = 86400 if delete_messages else 0
await member.ban(reason=reason, delete_message_seconds=seconds)
await interaction.response.send_message("That member was banned.")
else:
# An interaction must give exactly one response always. Ephemeral messages are not visible to
# anyone but the person who ran the command.
# https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionResponse
await interaction.response.send_message("You cannot ban that member!", ephemeral=True)
bot.run(YOUR_TOKEN)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment