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

如何解决Pycord中的交互错误?附代码修正指引

解决Pycord斜杠命令的交互错误:将ctx.send()替换为ctx.respond()

在Pycord中开发斜杠命令时,直接使用ctx.send()会触发交互错误,这是因为Discord的交互系统要求斜杠命令必须先通过ctx.respond()完成初始响应,之后才能使用ctx.send()发送额外消息。

修改后的完整代码

import discord
import os
from discord.ext import commands
from dotenv import load_dotenv

load_dotenv()
intents = discord.Intents.all()
bot = commands.Bot(command_prefix="t.", intents=intents)

servers = [1249591729171071077]

@bot.event
async def on_ready():
    print(f"{bot.user} is ready and online!")

@bot.slash_command(description="Приветствие от бота")
async def hello(ctx):
    # 斜杠命令必须用respond完成初始响应
    await ctx.respond("Привет! Я бот Discord!")

@bot.slash_command(guild_ids=servers, name="ping", description="Отправляет задержку бота.")
async def ping(ctx):
    await ctx.respond(f"Pong! Задержка составляет {round(bot.latency * 1000)} мс.")
    # 如果需要发送额外消息,可在respond之后使用send
    # await ctx.send("这是额外的消息")

bot.run(os.getenv('TOKEN'))

关键说明

  • 初始响应必须用ctx.respond():Discord要求斜杠命令触发后,机器人必须在3秒内返回一个交互响应,ctx.respond()就是完成这个要求的方法,它会告诉Discord"机器人已收到请求并正在处理"。
  • 后续消息可用ctx.send():如果你需要在同一个交互中发送多条消息,在调用ctx.respond()之后,可以正常使用ctx.send()发送后续内容。
  • 优化延迟显示:原代码中bot.latency返回的是秒数,乘以1000并用round()取整后,显示的延迟会更符合用户认知的毫秒单位。

内容的提问来源于stack exchange,提问作者Ваня Горушкин

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 18:42:44