You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

开发Discord斜杠命令遇AttributeError:找不到Option属性

解决Discord机器人斜杠命令Option导入错误问题

问题根源

你使用的discord.ext.commands是传统前缀命令的模块,斜杠命令(应用命令)的Option并不属于这个模块,这就是触发AttributeError的直接原因。

正确导入方式

斜杠命令相关的Option属于Discord.py的应用命令体系,需要从discord.app_commands模块导入:

# 方式1:直接导入Option
from discord.app_commands import Option

# 方式2:导入整个app_commands模块,后续通过app_commands.Option调用
from discord import app_commands

代码修正示例

假设你原来的错误代码如下:

from discord.ext import commands

@commands.slash_command(name="online")
async def online(ctx, server: commands.Option(str, description="要查询的服务器")):
    # 命令逻辑
    await ctx.respond(f"查询服务器{server}在线状态")

修正后的正确代码:

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

class MyBot(commands.Bot):
    def __init__(self):
        super().__init__(command_prefix="!", intents=discord.Intents.default())

    async def setup_hook(self):
        # 同步命令到指定服务器(全局同步需等待1小时,测试建议用服务器ID)
        await self.tree.sync(guild=discord.Object(id=你的服务器ID))

bot = MyBot()

@bot.tree.command(name="online")
async def online(interaction: discord.Interaction, server: app_commands.Option(str, description="要查询的服务器")):
    await interaction.response.send_message(f"查询服务器{server}在线状态")

bot.run("你的机器人Token")

额外注意事项

  • 确保你的Discord.py版本为v2.0及以上,v1.x版本不支持原生斜杠命令,需升级:
    pip install -U discord.py
    
  • 官方斜杠命令的装饰器是@bot.tree.command(),而非旧第三方库的@commands.slash_command()

内容的提问来源于stack exchange,提问作者Planetech

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 03:07:37