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

Discord.py中app_commands斜杠命令部分无响应求助

问题分析与解决方案

核心问题

你的斜杠命令无响应是因为代码存在两处错误,导致命令执行时触发异常但未抛出明显报错:

1. Cog文件缺少必要模块导入

/num命令中使用了random.randint()和datetime.datetime.utcnow(),但Ping Cog文件顶部未导入这两个模块。Cog作为独立模块无法共享主文件的导入,运行时会触发NameError,直接导致命令执行失败。

2. /num命令使用未定义变量

代码里写了{context.author},但该函数的参数是interaction,并未定义context,这里应该改为interaction.user。

3. 可选:命令同步问题

如果是新增的/num和/test命令,可能还未同步到Discord服务器,需要手动触发同步。

修复步骤

步骤1:修正Ping Cog代码

修改后的完整Cog代码如下:

import time
import random  # 新增导入
import datetime  # 新增导入
import discord
from discord.ext import commands
from discord import app_commands
from discord.ext.commands import Context
from discord.ext.commands import Bot

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

    @commands.Cog.listener()
    async def on_ready(self):
        print("Ping.py is ready!")

    @commands.command()
    async def ping(self, ctx):
        yo = round(self.bot.latency * 1000)
        embed = discord.Embed(title="Pong! :ping_pong:", color=discord.Color.random())
        embed.add_field(name="Latency:", value=f"{yo}ms")
        await ctx.send(embed=embed)

    @app_commands.command(name="hi", description="Say hi!")
    async def hi(self, interaction: discord.Interaction, word:str):
        await interaction.response.send_message(f"Hi {word}!")

    @app_commands.command(name="num", description="Random numbers")
    async def num(self, interaction: discord.Interaction, first: int, second: int) -> None:
        szam = random.randint(first, second)
        embed = discord.Embed(title="Random number", color=discord.Color.random())
        # 替换context.author为interaction.user
        embed.add_field(name=f"{interaction.user}'s number is:{szam}", value=f"Lowest:{first} | Highest:{second}",
                        inline=False)
        embed.timestamp = datetime.datetime.utcnow()
        await interaction.response.send_message(embed=embed)

    @app_commands.command(name="test", description="test")
    async def test(self, interaction: discord.Interaction, szam:str):
        await interaction.response.send_message(f"Szám:{szam}")

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

步骤2:添加命令同步(可选)

如果修复后命令仍无响应,在Main.py的on_ready事件中添加同步代码,确保命令被Discord服务器识别:

@bot.event
async def on_ready():
    print("Successfully connected to the server!")
    await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name=f"{len(bot.guilds)} server | !help"))
    # 全局同步命令(生效可能需要1小时)
    await bot.tree.sync()
    # 测试服务器可指定ID快速同步,替换为你的服务器ID
    # await bot.tree.sync(guild=discord.Object(id=1234567890))
    print("命令已同步")

验证方法

  1. 重启Bot,检查控制台是否有报错。
  2. 在Discord中重新输入/num或/test命令,测试响应是否正常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 22:25:22