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

使用Nextcord斜杠命令时出现AttributeError错误求助

问题解决:斜杠命令中AttributeError: 'NoneType' object has no attribute 'guild'

问题原因

斜杠命令属于Nextcord的应用命令,其上下文对象(Interaction,即代码里的ctx)的message属性为None——因为斜杠命令不是通过用户发送的消息触发的,自然没有对应的message对象。你试图访问ctx.message.guild,本质是访问None.guild,所以抛出了AttributeError。

修复代码

直接通过上下文对象的guild属性获取服务器ID即可,无需经过message:

@bot.slash_command()
async def name(ctx):
    # 直接使用ctx.guild获取服务器对象
    if ctx.guild is not None:
        server_id = ctx.guild.id
        await ctx.send(f"服务器ID:{server_id}")
    else:
        await ctx.send("此命令只能在服务器中使用!")

补充说明

  • 若用户在DM中执行该斜杠命令,ctx.guild会是None,添加判断可以避免再次触发类似错误,提升命令健壮性。
  • 你的导入语句存在冗余(同时导入了discord和nextcord的相关模块),建议只保留nextcord的导入,避免潜在冲突:
import os
from random import *
from nextcord import *
from nextcord.ext import commands
from nextcord.ui import *

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 10:46:18