discord.py 按钮与Select组件运行异常问题求助
discord.py 交互组件异常排查
Button按钮组件IndentationError报错
问题根因
- Python语法要求函数内部代码必须相对
def声明行缩进1级(通用规范为4个空格),原代码中await ctx.send(...)行无缩进,后续等待交互、响应交互的代码缩进层级混乱,直接触发缩进错误。 - 交互校验逻辑存在拼写错误:将交互属性
custom_id错写为custon_id,即使缩进修复也会触发属性不存在的运行时报错。 - 按钮样式直接传字符串数字兼容性差,discord.py 2.0+版本推荐使用官方
ButtonStyle枚举值,避免样式渲染异常。
修正代码
# 需提前导入对应依赖 from discord.ui import Button from discord import ButtonStyle @bot.command() async def button(ctx): # 函数内代码统一缩进4个空格 await ctx.send("hello", components = [ [ Button(label="hi", style=ButtonStyle.success, custom_id="button1"), Button(label="bye", style=ButtonStyle.danger, custom_id="button2") ] ]) # 修正custom_id拼写错误 interaction = await bot.wait_for("button_click", check = lambda i: i.custom_id == "button1") await interaction.send(content = "Button Clicked", ephemeral=True)
Select下拉选择组件仅输出"urmom"异常
问题根因
- 缩进层级完全错乱:
await ctx.send(...)行未相对函数声明缩进,后续while True循环不在命令函数作用域内,无法获取当前命令的上下文对象。 - 参数拼写错误:响应交互时将临时消息参数
ephemeral错写为emphemral,触发无效参数报错,直接走到except分支输出固定内容"urmom"。 - 逻辑设计缺陷:裸写无限
while True循环会阻塞bot整个事件循环,且未添加交互来源校验,会捕获全服务器所有下拉选择事件,引发逻辑混乱。 - 裸
except会吞掉所有具体报错信息,调试阶段无法定位真实问题原因。
修正代码
# 需提前导入对应依赖 from discord.ui import Select, SelectOption, View @bot.command() async def select(ctx): # 函数内代码统一缩进 select_menu = Select( placeholder = "Select Something", options = [ SelectOption(label="A", value="A"), SelectOption(label="B", value="B") ] ) # 官方2.0+版本要求组件必须挂载到View实例后发送 view = View() view.add_item(select_menu) await ctx.send("Select", view=view) # 添加交互校验:仅响应当前触发命令的用户在当前消息下的操作 def interaction_check(inter): return inter.user == ctx.author and inter.message.id == ctx.message.id select_interaction = await bot.wait_for("select_option", check=interaction_check) # 修正ephemeral拼写错误 await select_interaction.send(content = f"{select_interaction.values[0]} selected", ephemeral=False)
注:如果使用第三方
discord-components库实现交互组件,可保留components传参方式,但仍需修复缩进、拼写、循环逻辑问题。
内容的提问来源于stack exchange,提问作者黃孝彬
相关产品推荐
相关产品推荐

