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

Discord机器人能否同时支持前缀与斜杠命令?如何合并重复代码?

Discord机器人同时支持前缀命令和斜杠命令的实现方案

当然可以让你的Discord机器人同时支持前缀命令和斜杠命令,并且能通过整合代码、抽取公共逻辑来避免重复编写。

整合后的代码示例

将两个命令合并到同一个Cog中,并抽取公共逻辑:

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

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

    # 抽取公共逻辑:计算延迟并生成格式化响应内容
    def _get_pong_content(self):
        latency = self.bot.latency * 1000
        return f'Pong! **{latency:.2f} ms**'

    # 前缀命令(比如!ping)
    @commands.command()
    async def ping(self, ctx):
        message = await ctx.send("Pong!")
        await message.edit(content=self._get_pong_content())

    # 斜杠命令(/ping)
    @app_commands.command(name="ping")
    async def slash_ping(self, interaction: discord.Interaction):
        await interaction.response.send_message(content="Pong!")
        msg = await interaction.original_response()
        await msg.edit(content=self._get_pong_content())

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

关键说明

  • 兼容性:同一个Cog中可以同时定义commands.command()(前缀命令)和app_commands.command()(斜杠命令)装饰的方法,Discord.py完全支持这种混合模式。
  • 避免重复:把计算延迟、生成响应内容的逻辑抽成私有方法_get_pong_content,两个命令直接调用该方法,消除代码冗余。
  • 命令命名:斜杠命令的方法名不能和前缀命令的方法名重复(类方法名唯一),因此用slash_ping作为方法名,再通过name="ping"指定斜杠命令对外显示的名称为ping,保持和前缀命令的一致性。

额外注意

确保你的机器人拥有applications.commands权限,并且在启动时执行await bot.tree.sync()完成斜杠命令的同步,这样服务器才能识别到你的斜杠命令。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 20:22:37