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

DiscordPy 2.0中Ping Cog失效,斜杠命令不显示求助

问题排查与修复方案

核心问题

你的代码存在三个关键问题,导致斜杠命令无法在Discord服务器中显示:

  1. Ping命令使用的是前缀命令装饰器(@commands.command()),而非斜杠命令专用的装饰器,因此不会被注册为Discord斜杠命令
  2. 发送消息时缺失await关键字,会触发运行时错误
  3. 机器人延迟的调用方式错误,应使用self.bot.latency而非self.latency

此外,斜杠命令需要主动同步到Discord服务器,否则服务器无法识别新的斜杠命令。

修复后的代码

修改main.py

添加斜杠命令同步逻辑到on_ready事件:

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


bot = commands.Bot(command_prefix="//", intents=discord.Intents.all())
bot.load_extension("cogs.ping")


@bot.event
async def on_ready():
    print(f"{bot.user} is online !")
    # 同步斜杠命令到Discord
    try:
        # 全局同步(正式环境用,生效需约1小时)
        await bot.tree.sync()
        # 测试时可指定服务器ID立即生效:await bot.tree.sync(guild=discord.Object(id=你的服务器ID))
        print("斜杠命令同步成功")
    except Exception as e:
        print(f"同步斜杠命令失败: {e}")

bot.run('你的TOKEN')

修改cogs/ping.py

替换为斜杠命令装饰器,修复消息发送和延迟获取逻辑:

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


class Ping(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    # 斜杠命令装饰器,指定命令名和描述
    @app_commands.command(name="ping", description="查看机器人响应延迟")
    async def ping(self, interaction: discord.Interaction):
        latency = round(self.bot.latency * 1000, 2)
        await interaction.response.send_message(f"Pong in {latency}ms")


def setup(bot):
    bot.add_cog(Ping(bot))

额外说明

  • 测试阶段建议用指定服务器ID同步,开启Discord开发者模式后,右键服务器即可复制ID
  • 确保机器人账号拥有applications.commands权限,否则无法注册斜杠命令
  • 全局同步的斜杠命令生效较慢,适合正式发布时使用

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 19:05:22