본문 바로가기
Discord/Discord Bot Python

Discord 봇 만들기 - Dropdown

by 깐테 2023. 6. 16.

Examples - Dropdown

https://github.com/Rapptz/discord.py/blob/master/examples/views/dropdown.py

 

GitHub - Rapptz/discord.py: An API wrapper for Discord written in Python.

An API wrapper for Discord written in Python. Contribute to Rapptz/discord.py development by creating an account on GitHub.

github.com

  • 해당 예제를 사용하기 위해서는 discord-ui, py-cord 설치 필요
  • 위 방법으로 해결되지 않는다면 Git clone을 통한 버전 업그레이드.
    1. pip install discrod-ui pip install py-cord
    2. pip install -U git+https://github.com/Rapptz/discord.py
    3. Discord Developer Portal → Privileged Gateway Intents 3개 모두 체크최종적으로 Discord Developer Portal → Privileged Gateway Intents 3개 모두 체크

 

 

소스코드

import discord
from discord.ext import commands
from dico_token import Token

# Defines a custom Select containing colour options
# that the user can choose. The callback function
# of this class is called when the user changes their choice
class Dropdown(discord.ui.Select):
    def __init__(self):

        # Set the options that will be presented inside the dropdown
        options = [
            discord.SelectOption(label='Red', description='Your favourite colour is red', emoji='🟥'),
            discord.SelectOption(label='Green', description='Your favourite colour is green', emoji='🟩'),
            discord.SelectOption(label='Blue', description='Your favourite colour is blue', emoji='🟦'),
        ]

        # The placeholder is what will be shown when no option is chosen
        # The min and max values indicate we can only pick one of the three options
        # The options parameter defines the dropdown options. We defined this above
        super().__init__(placeholder='Choose your favourite colour...', min_values=1, max_values=1, options=options)

    async def callback(self, interaction: discord.Interaction):
        # Use the interaction object to send a response message containing
        # the user's favourite colour or choice. The self object refers to the
        # Select object, and the values attribute gets a list of the user's
        # selected options. We only want the first one.
        await interaction.response.send_message(f'Your favourite colour is {self.values[0]}')


class DropdownView(discord.ui.View):
    def __init__(self):
        super().__init__()

        # Adds the dropdown to our view object.
        self.add_item(Dropdown())

# $ 또는 @[봇 멘션]이 명령어가 된다.
class Bot(commands.Bot):
    def __init__(self):
        intents = discord.Intents.default()
        intents.message_content = True

        super().__init__(command_prefix=commands.when_mentioned_or('$'), intents=intents)

    async def on_ready(self):
        print(f'Logged in as {self.user} (ID: {self.user.id})')
        print('------')


bot = Bot()

# @[봇 멘션] or $colour
@bot.command(aliases=['color'])
async def colour(ctx):
    """Sends a message with our dropdown containing colours"""

    # Create the view containing our dropdown
    view = DropdownView()

    # Sending a message containing our view
    await ctx.send('Pick your favourite colour:', view=view)


bot.run(Token)

 

Class Dropdown

  • options = [discord.selectOption] 부분은 드랍다운 메뉴에 표시될 아이템들과 설명을 하나의 메뉴로 표현한다.
  • placeholder: 드랍다운 선택 전 표시될 문구와 최소, 최대 선택 가능 개수를 지정한다.
  • callback: interaction을 통해 선택한 메뉴의 값을 메시지를 통해 전송한다.('@' 멘션 or 커맨드 명령어)

 

Class DropdownView

  • add_item: 드랍다운 메뉴를 표시한다.

 

결과

반응형