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

如何修复interactions.py代码中的AttributeError: 'Command'无_options属性

问题:使用interactions.py开发Discord机器人时添加两个命令报错AttributeError: 'Command' object has no attribute '_options'

在使用interactions.py开发Discord机器人时,编写了两个命令:一个用于获取用户产品信息,另一个用于检索特定产品。单独运行其中一个命令时代码正常,但同时添加两个命令就会报错AttributeError: 'Command' object has no attribute '_options'。

以下是出错的代码:

import interactions, requests

bot = interactions.Client(token="tokenhere")


@bot.command(
    name="products",
    description="Get a list of all your products",
    scope=scopeid,
)
@interactions.option('Your roblox UserID',name='UserID', type=interactions.OptionType.INTEGER , required=True)
@bot.command(
    name="retrieve",
    description="Retrieve a certain product that you own",
    scope=scopeid,
    options=[
        interactions.Option(
            name='product',
            description='the product you would like to retrieve',
            type=interactions.OptionType.STRING,
            required=True
        )
    ]
)
async def products(ctx: interactions.CommandContext, userid: int):
    a = str(requests.get('https://jedistuff22.pythonanywhere.com/products/' + str(userid)).text)
    await ctx.send(a)
async def retrieve(ctx: interactions.CommandContext, product: str):
    a = ctx.author.user.username + '#' + ctx.author.user.discriminator
    print(a)
    await ctx.send(a)

bot.start()

解决方案

错误原因是装饰器堆叠顺序错误:你把第二个@bot.command装饰器直接放在了第一个命令的装饰器链后面,导致这个装饰器尝试修改第一个命令的Command对象,而非作用到retrieve函数上,从而引发属性不存在的错误。

正确写法是为每个命令单独配置完整的装饰器链,两个命令代码块完全分开:

import interactions, requests

bot = interactions.Client(token="tokenhere")


# 第一个命令:products
@bot.command(
    name="products",
    description="Get a list of all your products",
    scope=scopeid,
)
@interactions.option('Your roblox UserID', name='UserID', type=interactions.OptionType.INTEGER, required=True)
async def products(ctx: interactions.CommandContext, userid: int):
    a = str(requests.get('https://jedistuff22.pythonanywhere.com/products/' + str(userid)).text)
    await ctx.send(a)


# 第二个命令:retrieve
@bot.command(
    name="retrieve",
    description="Retrieve a certain product that you own",
    scope=scopeid,
    options=[
        interactions.Option(
            name='product',
            description='the product you would like to retrieve',
            type=interactions.OptionType.STRING,
            required=True
        )
    ]
)
async def retrieve(ctx: interactions.CommandContext, product: str):
    a = ctx.author.user.username + '#' + ctx.author.user.discriminator
    print(a)
    await ctx.send(a)

bot.start()

这样每个命令的装饰器仅作用于对应函数,不会互相干扰,即可解决报错问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 21:30:56