我如何在discord.py中制作工作斜杠命令

问题描述 投票:0回答:6

我正在尝试使用discord.py 创建斜杠命令,我已经尝试了很多东西,但似乎不起作用。如有帮助,我们将不胜感激。

python discord discord.py
6个回答
32
投票

注意:我会在最后包含一个 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)

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

@tree.command(name = "commandname", description = "My first application Command", guild=discord.Object(id=12417128931)) #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.
async def first_command(interaction):
    await interaction.response.send_message("Hello!")

然后,一旦客户端准备好,您还必须同步命令以进行不和谐,因此我们在

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()

并使用

创建斜杠命令
@bot.slash_command(name="first_slash", guild_ids=[...]) #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.
async def first_slash(ctx): 
    await ctx.respond("You executed the slash command!")

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

bot.run(TOKEN)

6
投票
# 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")

4
投票

他们正在向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 创建了自己的树,这就是为什么我使用它而不是客户端,我认为默认情况下客户端不会创建树。

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

我不太确定如何在齿轮中做到这一点,因为我有我的组,但基本上我正在做的是主机器人文件中的 @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


1
投票

discord.py 的斜线命令(2.0)

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

一些上下文:在discord.py 2.0中有两种方法来编写斜线命令

  • discord.Client:易于同步,无前缀命令
  • discord.ext.commands.Bot:更难同步,前缀命令

我将展示一个例子。我对discord.ext.commands.Bot更有信心了。

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

discord.ext.commands.Bot 斜杠命令

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 机器人之旅好运!


0
投票

就这样做

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):

-2
投票

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()
© www.soinside.com 2019 - 2024. All rights reserved.