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

Discord.py中如何让Cog内的普通命令与斜杠命令共存?

解决discord.py中前缀命令与斜杠命令共存的问题

你的代码核心问题是Cog类中两个命令方法同名(都叫ping)——Python中类的后续同名方法会覆盖之前的定义,导致只有最后编写的斜杠命令生效,前缀命令被覆盖无法触发。

修改方案

只需将斜杠命令的方法名改为与前缀命令不同的名称,同时保留@app_commands.command的name参数为ping,这样既不会覆盖前缀命令,又能让斜杠命令显示为/ping。

修改后的Cog代码

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

class Ping(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
    
    @commands.Cog.listener()
    async def on_ready(self):
        print("Ping.py is loaded!")
    
    @commands.command()
    async def ping(self, ctx):
        bot_latency = round(self.bot.latency * 1000)
        await ctx.send(f"Pong! {bot_latency} ms.")
    
    # 修改方法名为slash_ping,保持命令对外显示为ping
    @app_commands.command(name="ping", description="Returns ping to the server")
    async def slash_ping(self, interaction: discord.Interaction):
        bot_latency = round(self.bot.latency * 1000)
        await interaction.response.send_message(f"Pong! {bot_latency} ms.", ephemeral=False)

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

验证说明

主函数代码无需修改,重启机器人后:

  • 发送!ping会触发前缀命令,通过上下文对象发送消息
  • 使用/ping会触发斜杠命令,通过交互对象返回消息
  • 控制台会同步显示Ping.py is loaded!和Synced 1 command(s)的加载、同步提示

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 09:56:03