Category: Discord Bot Tutorials

Discord Bot Tutorial#3Adding Subcommands to Slash Commands!

This post was translated from the Korean original.

Contents5 sections

Hi there! It's Mojangcam 😎 This time, we're stepping up to a more advanced feature! Let's look at subcommands, which group slash commands together!

For example...

  • /user info → View user info
  • /user ban → Ban a user

This way, you put several features inside a single command group!


🧩 Subcommands? What Are They?

A subcommand is a structure you use in the form /명령어 서브명령어 (that is, /command subcommand). The more features your bot has, the more useful they get, because they keep everything neatly organized!


🧑‍💻 Example Code

Python
import discord
from discord.ext import commands
from discord import app_commands

class UserCommandGroup(app_commands.Group):
    def __init__(self):
        super().__init__(name="user", description="A collection of user commands!")

    @app_commands.command(name="info", description="Shows info about a user.")
    async def info(self, interaction: discord.Interaction, user: discord.User):
        await interaction.response.send_message(f"{user.name}'s ID is {user.id}.")

    @app_commands.command(name="ban", description="Bans a user.")
    async def ban(self, interaction: discord.Interaction, user: discord.User, reason: str):
        await interaction.response.send_message(f"Banned {user.name} for '{reason}'!")

intents = discord.Intents.default()
bot = commands.Bot(command_prefix="!", intents=intents)
bot.tree.add_command(UserCommandGroup())   # Register the group before sync()!

@bot.event
async def on_ready():
    await bot.tree.sync()
    print(f"✅ {bot.user} is ready!")

bot.run("YOUR_TOKEN")

🚀 Usage Examples

  1. /user info user:@JohnDoe → JohnDoe's ID is 1234567890.
  2. /user ban user:@JohnDoe reason:swearing → Banned JohnDoe for 'swearing'!

🎁 Bonus Tips

  • You can set the group name with name="..." and its description with description="..."!
  • To add commands inside the group, use the @app_commands.command() decorator.
  • They're perfect when you're grouping things like admin features, game commands, and settings commands on a real server!

📌 Wrapping Up

Subcommands become a must as your bot grows more features! Grouping your commands neatly makes your bot feel much more polished.

Next time...

I'll show you how to add UI components like buttons and select menus (SelectMenu)! 😎

Series · Part 3 of 32

Discord Bot Tutorial

  1. #1Discord Bot Tutorial - Mastering Slash Commands!
  2. #2Adding Options (Arguments) to Slash Commands!
  3. #3Adding Subcommands to Slash Commands!You are here
  4. #4Sending Embeds with Slash Commands!
  5. #5Implementing Button Interactions!
  6. #6Implementing a Dropdown (Select Menu)!
  7. #7Getting User Input with a Modal (Python Example)
  8. #8Styling Embeds with Images and Fields (Python Example)
  9. #9Connecting AI (Claude & ChatGPT API) to Your Bot! (Python Example)
  10. #10Adding Multi-Language (i18n) Support! (Python Example)
  11. #11Building a Web Dashboard with Flask! (Python Example)
  12. #12Managing Command Cooldowns and Permissions! (Python Example)
  13. #13Automating Roles and Channels to Manage Your Server! (Python Example)
  14. #14Saving Data! JSON vs SQLite (Python Example)
  15. #15슬래시 명령어 그룹(Group)으로 명령어 정리하기! (파이썬 예제) (Korean)
  16. #16리마인더·알림 기능 만들기! 봇이 먼저 말 걸게 하기 (파이썬 예제) (Korean)
  17. #17RAG로 문서 기반 답변봇 만들기! 우리 서버 전용 FAQ 봇 (파이썬 예제) (Korean)
  18. #18투표(Poll) 기능 만들기! 다수결로 정하는 서버 규칙 (파이썬 예제) (Korean)
  19. #19Cog로 코드 쪼개기! 1000줄 봇도 안 더러워지는 구조 (파이썬 예제) (Korean)
  20. #20자동 환영 메시지·온보딩 만들기! 규칙 동의 버튼으로 자동 역할 부여 (파이썬 예제) (Korean)
  21. #21키워드 자동응답·금지어 필터 만들기! 경고 누적으로 자동 제재까지 (파이썬 예제) (Korean)
  22. #22슬래시 명령어 자동완성(Autocomplete) 만들기! 금지어를 골라서 추가·삭제 (파이썬 예제) (Korean)
  23. #23aiosqlite로 비동기 DB 제대로 설계하기! JSON 탈출 (파이썬 예제) (Korean)
  24. #24채널 난독화(Channel Obfuscation) 대응하기! 11/16부터 안 보이는 채널이 생겨요 (파이썬 예제) (Korean)
  25. #25봇이 죽지 않게! 에러 핸들링·로깅 체계 잡기 (파이썬 예제) (Korean)
  26. #26티켓(Ticket) 문의 시스템 만들기! 버튼 하나로 1:1 상담 채널 자동 생성 (파이썬 예제) (Korean)
  27. #27티켓 담당자 배정·우선순위 만들기! 스태프가 여러 명이어도 안 꼬이게 (파이썬 예제) (Korean)
  28. #28레벨·경험치(XP) 시스템 만들기! 채팅할수록 레벨업, 랭킹판까지 (파이썬 예제) (Korean)
  29. #29화폐·상점(Economy) 시스템 만들기! 코인 벌어서 아이템 사기 (파이썬 예제) (Korean)
  30. #30Build a Poll & Survey Bot! Native Polls + Buttons with Real-Time Tallies (Python Example) 🗳️
  31. #32Build a Server Log & Audit Log Channel! Auto-Log Message Deletes, Edits, Joins/Leaves, and Kicks (Python Example) 🕵️
  32. #33임시 음성방 확장, 파티방 만들기! 방장 위임·강퇴·초대 전용(비공개) 방 + 전용 채팅방 자동 생성 (파이썬 예제) 🎉 (Korean)
Show all 32Collapse

Author

Mojangcam

A hands-on dev and IT log: code I write, servers I run, and the errors I fix along the way.