LoginSignup
2
3

More than 1 year has passed since last update.

discord.pyでCogとSlashCommandを両方使う

Last updated at Posted at 2021-09-11

discord.pyの開発再開終了とSlashCommandの必須化

discord.pyの開発が終了したのはご存じの通り。開発者の方々おつかれさまでした。
追記: discord.pyの開発が再開しました。
それでも我々discord依存民はこれまで作って使い慣れてきたdiscord.botを手放すことはできません。したくありません。
もうかなりの工数を突っ込んでいるので引き返せないんだよォ!
なので開発途中のdiscord_slashライブラリを活用したdiscord.botのひな形を用意しました。

ひな形

###testbot.py:実行本体ファイル

testbot.py
#!/usr/bin/env python3
import discord
from discord.ext import commands
from discord_slash import SlashCommand
from discord_slash.utils import manage_commands
from logging import basicConfig, getLogger

basicConfig(level = config.LOG_LEVEL)
LOG = getLogger(__name__)

# 読み込むCogファイル名を格納しておく
INITIAL_EXTENSIONS = [
  'test_cog',
]

# テストbotクラス本体
class TestBot(commands.Bot):
  # コンストラクタ
  def __init__(self, command_prefix, intents, help_command, description, **options):
    super().__init__(command_prefix,
                      case_insensitive = True,
                      intents = intents,
                      help_command = help_command,
                      description = description, **options)

    # スラッシュコマンドオブジェクトのインスタンス
    slash = SlashCommand(self, sync_commands = True, override_type = True)
    guild_ids = [botを稼働させるDiscordのサーバID]

    # コグを読み込む
    for cog in INITIAL_EXTENSIONS:
      self.load_extension(cog)

  async def on_ready(self):
    LOG.info('We have logged in as {0.user}'.format(self))
    LOG.info(f'### guilds ### \n{self.guilds}')
    LOG.info('bot ready.')
    activity = discord.Activity(name = 'アクティビティサンプル', type = discord.ActivityType.watching)
    await self.change_presence(activity = activity)

    cmds = await manage_commands.get_all_commands(config.BOT_USER_ID, config.DISCORD_TOKEN, config.GUILD_ID)
    for cmd in cmds:
      LOG.info(cmd)

    # グローバルコマンドを登録した場合、以下のコマンドで削除します
    # await manage_commands.remove_all_commands_in(config.BOT_USER_ID, config.DISCORD_TOKEN, config.GUILD_ID)
    # LOG.info('remove all guild command.')

if __name__ == '__main__':
# discord-Infobotのインスタンス化、および、起動処理
  intents = discord.Intents.all()
  intents.typing = False
  intents.members = False
  intents.voice_states = False
  intents.presences = False

  bot = TestBot(command_prefix = '/', intents = intents,
                help_command = None, description = 'テストbot')
  bot.run(ディスコードBOTトークン)

###test_cog.py:コグで実装したスラッシュコマンド本体を記述したファイル

test_cog.py
#!/usr/bin/env python3
from discord.ext import commands
from logging import getLogger

LOG = getLogger(__name__)

# テストコグスラッシュコマンドクラス
class Test_Cog(commands.Cog):
  guild_ids = [botを稼働させるDiscordのサーバID]

  # /test オプション
  test_options = [
    manage_commands.create_option(name = 'param',
                                  description = 'テストコマンドの第一パラメータです',
                                  option_type = SlashCommandOptionType.STRING, # 3
                                  required = True),
  ]
  # クラスコンストラクタ
  def __init__(self, bot):
    self.bot = bot
    LOG.info('constructor end')

  # コグアンロード処理
  def cog_unload(self):
    return super().cog_unload()

  # テストコマンド
  @cog_ext.cog_slash(name = 'test', description = 'テストコマンド',
                     options = test_options, guild_ids = guild_ids)
  async def _test(self, ctx: SlashContext, param: str = None):
    message = '次のメッセージを入力しました:{0}'.format(param)
    await ctx.send(message)

# メンバ関数ではないことに注意する
def setup(bot):
  bot.add_cog(Test_Cog(bot))
  print('Test_Cog setupped')

###Thanks discord.py and enjoy discord
discord_slash ライブラリがどう転ぶのか分かりませんが、この実装が主流になると信じて。

2
3
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
2
3