LoginSignup
1
0

More than 1 year has passed since last update.

PycordでSlashcommandのファイル分割の仕方

Last updated at Posted at 2022-04-08

公式のExampleにCommandGroupについての記述があったので追記

やりたいこと

DiscordのBotを作っていると思い付きでコマンドを追加したくなってくることが多々あります。(N=1的な感想)
そうなってくると1つのpythonファイルの中にコマンドを追加していくと死ぬほど読みづらくなってしまいます。

なので、コマンドごとにファイル分割をしようって感じのはなしです。

前提環境

  • Python 3.10.4
  • py-cord 2.0.0b5

Cogを利用したファイルコマンド読み込み

Bot commands frameworkCogsを利用することができます。

従来のprefixを定義して利用するBOTだと以下の記事のような方法です。

このままだとSlashcommandでは利用できないので、以下の動画を参考にして変更をしました。

ディレクトリ構成は以下のような感じです。

.
┣━ main.py
┗━ Cogs
   ┗ sub.py

以下のような記述で実行できます。

main.py
from discord.ext import commands
bot = commands.Bot()


@bot.event
async def on_ready():
    print('Ready!')

bot.load_extension('Cogs.sub')

bot.run('token')
sub.py
import discord
from discord.ext import commands
from discord.commands import slash_command # 追加

guild_ids = [00000000000000] # guild id


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

    @slash_command(guild_ids=guild_ids) # 変更
    async def hi(
            self,
            ctx: discord.ApplicationContext):
        await ctx.respond('hi!')

def setup(bot):
    bot.add_cog(Example(bot))

CommandGroupの設定

Cog内でCommandGroup定義する方法が公式Exampleに普通に乗っていたので、そちらも紹介します。

ディレクトリ構成などは一緒でほんのすこしの変更があるだけです。

main.py
from discord.ext import commands

# debug_guildsを引数に入れればコマンド毎にguild_idsを渡す必要ないそうです
bot = commands.Bot(debug_guilds=[...])


@bot.event
async def on_ready():
    print('Ready!')

bot.load_extension('Cogs.sub')

bot.run('token')
sub.py
import discord
from discord.ext import commands
from discord.commands import SlashCommandGroup


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

    # コマンドグループを定義
    greetings = SlashCommandGroup('greetings', 'Various greeting from cogs!')

    # コマンドグループのデコレータを使用する
    @greetings.command()
    async def hi(
            self,
            ctx: discord.ApplicationContext):
        await ctx.respond('hi!')

def setup(bot):
    bot.add_cog(Example(bot))

class変数としてSlashCommandGroupのインスタンスを生成してデコレータとして利用するだけなので実装も簡単です。

公式Exampleの書き方としてmain.pyの中でBOTのインスタンス生成をする時に
bot = commands.Bot(debug_guilds=[...])と記述するとコマンドごとに毎回入れてたguild_idsが不要になるっていうことに気づけてよかったです。

基本的に非公開のBOTはコレで良さそうですね。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0