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)

おすすめ記事