如何在 discord.py 中创建有效的斜线命令

2025-03-21 09:05:00
admin
原创
46
摘要:问题描述:我正在尝试使用 discord.py 创建斜线命令,我试了很多方法,但似乎不起作用。如能提供帮助,我将不胜感激。解决方案 1:注意:我将在最后附上 pycord 的版本,因为我认为它更简单,而且它是原始答案。discord.py 版本首先确保安装了最新版本的 discord.py。在代码中,首先导入...

问题描述:

我正在尝试使用 discord.py 创建斜线命令,我试了很多方法,但似乎不起作用。如能提供帮助,我将不胜感激。


解决方案 1:

注意:我将在最后附上 pycord 的版本,因为我认为它更简单,而且它是原始答案。


discord.py 版本

首先确保安装了最新版本的 discord.py。在代码中,首先导入库:

import discord
from discord import app_commands

然后定义你的客户端和树:

intents = discord.Intents.default()
client = discord.Client(intents=intents)
tree = app_commands.CommandTree(client)

该树包含所有应用程序命令。然后您可以定义命令:

# Add the guild ids in which the slash command will appear.
# If it should be in all, remove the argument, but note that
# it will take some time (up to an hour) to register the
# command if it's for all guilds.
@tree.command(
    name="commandname",
    description="My first application Command",
    guild=discord.Object(id=12417128931)
)
async def first_command(interaction):
    await interaction.response.send_message("Hello!")

然后,一旦客户端准备就绪,您还必须将命令同步到 discord,因此我们会在以下on_ready情况下执行此操作:

@client.event
async def on_ready():
    await tree.sync(guild=discord.Object(id=Your guild id))
    print("Ready!")

最后我们必须运行我们的客户端:

client.run("token")

pycord 版本

要安装 py-cord,请先运行pip uninstall discord.py,然后pip install py-cord。然后在代码中,首先使用

import discord
from discord.ext import commands

使用以下方式创建你的机器人

bot = commands.Bot()

并使用创建斜线命令

# Add the guild ids in which the slash command will appear.
# If it should be in all, remove the argument, but note that
# it will take some time (up to an hour) to register the
# command if it's for all guilds.
@bot.slash_command(
  name="first_slash",
  guild_ids=[...]
)
async def first_slash(ctx): 
    await ctx.respond("You executed the slash command!")

然后使用你的令牌运行机器人

bot.run(TOKEN)

解决方案 2:

# This is new in the discord.py 2.0 update

# imports
import discord
import discord.ext

# setting up the bot
intents = discord.Intents.all() 
# if you don't want all intents you can do discord.Intents.default()
client = discord.Client(intents=intents)
tree = discord.app_commands.CommandTree(client)

# sync the slash command to your server
@client.event
async def on_ready():
    await tree.sync(guild=discord.Object(id=Your guild ID here))
    # print "ready" in the console when the bot is ready to work
    print("ready")

# make the slash command
@tree.command(name="name", description="description")
async def slash_command(interaction: discord.Interaction):    
    await interaction.response.send_message("command")

# run the bot
client.run("token")

解决方案 3:

他们正在向 discord.py 添加斜线命令,但您可以在https://gist.github.com/Rapptz/c4324f17a80c94776832430007ad40e6中看到一些示例。您似乎正在使用 discord_slash,而我还没有使用过。

这些内容的主要文档是https://discordpy.readthedocs.io/en/master/interactions/api.html?highlight=dropdown#decorators但主要的“操作方法”是您必须制作一棵“树”,将命令附加到该树,然后同步您的树以使命令显示出来。discord.ext.Bot 会生成自己的树,这就是我使用它而不是客户端的原因,我认为客户端默认情况下不会生成树。

如果您指定公会,命令同步会立即进行,但如果您不指定公会,我认为需要一个小时才能更新或类似的东西,因此请指定公会,直到您准备好部署为止。

我不太清楚如何在 cogs 中执行此操作,因为我将其分成了多个组,但基本上我所做的是将主 bot 文件中的 @bot.tree.command() 与单独文件中的几个组进行组合。

这是我的主要文件

import discord
import simplegeneralgroup
from config import TOKEN
MY_GUILD = discord.Object(id=1234567890)

class MyBot(discord.ext.commands.Bot):
    async def on_ready(self):
        await self.tree.sync(guild=MY_GUILD)

bot: discord.ext.commands.Bot = MyBot

@bot.tree.command(guild=MY_GUILD)
async def slash(interaction: discord.Interaction, number: int, string: str):
    await interaction.response.send_message(f'Modify {number=} {string=}', ephemeral=True)

bot.tree.add_command(simplegeneralgroup.Generalgroup(bot), guild=MY_GUILD)

if __name__ == "__main__":
    bot.run(TOKEN)

然后是 simplegeneralgroup 文件

import discord
from discord import app_commands as apc
class Generalgroup(apc.Group):
    """Manage general commands"""
    def __init__(self, bot: discord.ext.commands.Bot):
        super().__init__()
        self.bot = bot

    @apc.command()
    async def hello(self, interaction: discord.Interaction):
        await interaction.response.send_message('Hello')

    @apc.command()
    async def version(self, interaction: discord.Interaction):
        """tells you what version of the bot software is running."""
        await interaction.response.send_message('This is an untested test version')

应该有三个命令:/slash,它将提示用户输入数字和字符串、/generalgroup hello 和 /generalgroup version

解决方案 4:

就这么做

from discord import Interaction
from discord import app_commands

@app_commands.command(name="",description="")
async def ping(ctx: Interaction, have_account:bool, login_email:str=None, login_mobile:str=None):

解决方案 5:

使用 discord.py (2.0) 的斜线命令

虽然这是对一个老问题的新答案,当我第一次开始编写机器人代码时我遇到了这个问题,但没有一个答案起作用。

一些背景信息:在 discord.py 2.0 中,有两种方法可以编写斜线命令

discord.Client,+易于同步 - 无前缀命令

command.Bot, -更难同步 +前缀命令

我将展示一个我对命令更自信的例子。Bot FYI

discord.Client 斜线命令示例的一个很好的外部来源是Rapptz-app_command_examples

命令.Bot Slash Command

from typing import Literal, Optional
import discord
from discord.ext.commands import Greedy, Context
from discord import app_commands
from discord.ext import commands

#------ Bot ------
# Can add command_prefix='!', in commands.Bot() for Prefix Commands
intents = discord.Intents.default()
intents.members = True
intents.message_content = True
bot = commands.Bot(intents=intents)
#--- Bot Startup
@bot.event
async def on_ready():
    print(f'Logged in as {bot.user}') #Bot Name
    print(bot.user.id) #Bot ID
#------ Slash Commands ------
#Parameters can be added in def help()
# Ex- async def help(interaction: discord.Interaction, left:int,right:int)
@bot.tree.command()
async def help(interaction: discord.Interaction):
    """Help""" #Description when viewing / commands
    await interaction.response.send_message("hello")

#------ Sync Tree ------
guild = discord.Object(id='guildID')
# Get Guild ID from right clicking on server icon
# Must have devloper mode on discord on setting>Advance>Developer Mode
#More info on tree can be found on discord.py Git Repo
@bot.command()
@commands.guild_only()
@commands.is_owner()
async def sync(
  ctx: Context, guilds: Greedy[discord.Object], spec: Optional[Literal["~", "*", "^"]] = None) -> None:
    if not guilds:
        if spec == "~":
            synced = await ctx.bot.tree.sync(guild=ctx.guild)
        elif spec == "*":
            ctx.bot.tree.copy_global_to(guild=ctx.guild)
            synced = await ctx.bot.tree.sync(guild=ctx.guild)
        elif spec == "^":
            ctx.bot.tree.clear_commands(guild=ctx.guild)
            await ctx.bot.tree.sync(guild=ctx.guild)
            synced = []
        else:
            synced = await ctx.bot.tree.sync()

        await ctx.send(
            f"Synced {len(synced)} commands {'globally' if spec is None else 'to the current guild.'}"
        )
        return

    ret = 0
    for guild in guilds:
        try:
            await ctx.bot.tree.sync(guild=guild)
        except discord.HTTPException:
            pass
        else:
            ret += 1

    await ctx.send(f"Synced the tree to {ret}/{len(guilds)}.")


bot.run('token')

!sync-> 全局/服务器同步 (无 ID) 或 (ID SET)

!sync ~-> 同步当前公会 (Bot In)

!sync *-> 将所有全局应用程序命令复制到当前公会并同步

!sync ^-> 清除当前公会目标的所有命令并同步(删除公会命令)

!sync id_1 id_2-> 同步 ID 为 1 和 2 的公会

如果我犯了任何错误,请评论,我会修复它们,祝你在 discord bot 之旅中好运

解决方案 6:

discord.py不支持斜线命令。我建议您使用discord-py-interactions斜线命令。安装方法是执行python3.exe -m pip install discord-py-interactions。它运行良好。以下是示例代码:

import interactions

bot = interactions.Client(token="your_secret_bot_token")

@bot.command(
    name="my_first_command",
    description="This is the first command I made!",
    scope=the_id_of_your_guild,
)
async def my_first_command(ctx: interactions.CommandContext):
    await ctx.send("Hi there!")

bot.start()
相关推荐
  政府信创国产化的10大政策解读一、信创国产化的背景与意义信创国产化,即信息技术应用创新国产化,是当前中国信息技术领域的一个重要发展方向。其核心在于通过自主研发和创新,实现信息技术应用的自主可控,减少对外部技术的依赖,并规避潜在的技术制裁和风险。随着全球信息技术竞争的加剧,以及某些国家对中国在科技领域的打压,信创国产化显...
工程项目管理   2482  
  为什么项目管理通常仍然耗时且低效?您是否还在反复更新电子表格、淹没在便利贴中并参加每周更新会议?这确实是耗费时间和精力。借助软件工具的帮助,您可以一目了然地全面了解您的项目。如今,国内外有足够多优秀的项目管理软件可以帮助您掌控每个项目。什么是项目管理软件?项目管理软件是广泛行业用于项目规划、资源分配和调度的软件。它使项...
项目管理软件   1533  
  PLM(产品生命周期管理)项目对于企业优化产品研发流程、提升产品质量以及增强市场竞争力具有至关重要的意义。然而,在项目推进过程中,范围蔓延是一个常见且棘手的问题,它可能导致项目进度延迟、成本超支以及质量下降等一系列不良后果。因此,有效避免PLM项目范围蔓延成为项目成功的关键因素之一。以下将详细阐述三大管控策略,助力企业...
plm系统   0  
  PLM(产品生命周期管理)项目管理在企业产品研发与管理过程中扮演着至关重要的角色。随着市场竞争的加剧和产品复杂度的提升,PLM项目面临着诸多风险。准确量化风险优先级并采取有效措施应对,是确保项目成功的关键。五维评估矩阵作为一种有效的风险评估工具,能帮助项目管理者全面、系统地评估风险,为决策提供有力支持。五维评估矩阵概述...
免费plm软件   0  
  引言PLM(产品生命周期管理)开发流程对于企业产品的全生命周期管控至关重要。它涵盖了从产品概念设计到退役的各个阶段,直接影响着产品质量、开发周期以及企业的市场竞争力。在当今快速发展的科技环境下,客户对产品质量的要求日益提高,市场竞争也愈发激烈,这就使得优化PLM开发流程成为企业的必然选择。缺陷管理工具和六西格玛方法作为...
plm产品全生命周期管理   0  
热门文章
项目管理软件有哪些?
曾咪二维码

扫码咨询,免费领取项目管理大礼包!

云禅道AD
禅道项目管理软件

云端的项目管理软件

尊享禅道项目软件收费版功能

无需维护,随时随地协同办公

内置subversion和git源码管理

每天备份,随时转为私有部署

免费试用