在使用discord.py
库时,如果你想要可靠地从用户那里获取输入,并且这些输入必须是从一个预定义的选项列表中选择的,你可以使用以下几种方法:
discord.py
提供了一个命令系统,允许你定义用户可以通过聊天界面调用的命令。以下是一个使用discord.py
创建下拉菜单并从用户那里获取选择的示例:
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.messages = True
intents.guilds = True
bot = commands.Bot(command_prefix='!', intents=intents)
class Select(discord.ui.Select):
def __init__(self):
options = [
discord.SelectOption(label="Option 1", value="option1"),
discord.SelectOption(label="Option 2", value="option2"),
discord.SelectOption(label="Option 3", value="option3"),
]
super().__init__(placeholder="Choose an option...", options=options)
async def callback(self, interaction: discord.Interaction):
await interaction.response.send_message(f'You selected {self.values[0]}', ephemeral=True)
class Dropdown(discord.ui.View):
def __init__(self):
super().__init__()
self.add_item(Select())
@bot.command()
async def choose(ctx):
await ctx.send("Please choose an option:", view=Dropdown())
bot.run('YOUR_BOT_TOKEN')
如果你在使用上述代码时遇到问题,比如用户的选择没有被正确处理,可能的原因和解决方法包括:
如果你发现用户的选择没有被正确捕获,可以尝试在callback
方法中添加日志记录,以便跟踪问题:
import logging
logging.basicConfig(level=logging.DEBUG)
class Select(discord.ui.Select):
async def callback(self, interaction: discord.Interaction):
logging.debug(f'User selected {self.values[0]}')
await interaction.response.send_message(f'You selected {self.values[0]}', ephemeral=True)
通过这种方式,你可以更容易地诊断问题所在,并采取相应的解决措施。
领取专属 10元无门槛券
手把手带您无忧上云