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

Python开发Discord机器人斜杠命令ping报错:'NoneType'无edit属性

问题分析与修复

错误原因

AttributeError: 'NoneType' object has no attribute 'edit' 是因为 Interaction.response.send_message() 方法返回的是 None,而非你预期的 Message 对象。Discord.py 中,斜杠命令的初始响应方法不会返回消息实例,直接赋值给 message 后调用 edit 自然会报错。

另外你的代码存在冗余:同时实例化了 discord.Client 和 commands.Bot,后者是前者的子类,完全可以单独使用 Bot 来管理前缀命令和斜杠命令,无需重复创建客户端。

修复步骤

  1. 移除冗余的客户端实例:删掉 client = discord.Client(intents=intents),改用 bot 来初始化命令树。
  2. 正确编辑初始响应:使用 await interaction.edit_original_response() 来修改斜杠命令的初始回复,或者通过 await interaction.get_original_response() 获取消息对象后再编辑。
  3. 规范变量名:将 Interaction 改为小写的 interaction,符合 Python 命名规范。

修改后的完整代码

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

intents = discord.Intents.default()
prefix = "-"
# 只保留Bot实例,无需单独创建Client
bot = commands.Bot(command_prefix=prefix, intents=intents)
# 使用bot的命令树
tree = app_commands.CommandTree(bot)

@bot.event
async def on_ready():
    await tree.sync(guild=discord.Object(id=ID))  # 替换为你的服务器ID
    print("Ready!")

@tree.command(name="ping", description="test command", guild=discord.Object(id=ID))
async def ping(interaction):
    before = time.monotonic()
    # 发送初始响应
    await interaction.response.send_message("pong")
    ping = (time.monotonic() - before) * 1000
    # 方式1:直接编辑初始响应
    await interaction.edit_original_response(content=f"pong `{int(ping)}ms`")
    
    # 方式2:如果需要获取消息对象,可使用下面的代码
    # message = await interaction.get_original_response()
    # await message.edit(content=f"pong `{int(ping)}ms`")

bot.run('TOKEN')  # 替换为你的机器人Token

额外说明

  • 确保你已经替换代码中的 ID(服务器ID)和 TOKEN(机器人令牌)为真实值。
  • 如果需要全局同步命令(而非仅单个服务器),可以去掉 guild=discord.Object(id=ID) 参数,但全局同步可能需要1小时左右生效,开发阶段建议用服务器同步测试。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 02:31:32