LoginSignup
4
2

More than 5 years have passed since last update.

discord.py rewriteのCogに変更があったようなので

Posted at

discord.pyのrewriteバージョンに更新がありました。

前提: discord.pyのrewriteバージョンとasyncバージョンの区別ができる。
discord.pyのrewriteバージョンを使っている。

※Botを作り始める人向けではありません。

Cogを知らない人へ

Cogっておいしいの?

Cogは、クラスの一種で、使い方はたくさんありますが、よくあるのが「コマンド類を別ファイルで定義」というものです。

たとえば、「hogehogebot」にはゲーム、音楽再生、天気予報の機能があったとします。
通常は、

hogehogebot.py
import discord as d
from discord.ext import commands as c

bot = c.Bot(command_prefix="!")

@bot.command()
async def game_numguess(ctx):
    """数あて"""
    ....

@bot.command()
async def music_youtube(ctx, *, name):
    """YouTube音源再生"""
    ....

bot.run("tokenをおく")

などと書きますが、これではhogehogebot.pyが長くなり、ごちゃごちゃします。
そこで、ファイルを分けるために、Cogを使います。

hogehogebot.py
import discord as d
from discord.ext import commands as c
from cog_music import Music
from cog_games import Games

bot = c.Bot(command_prefix="!")

bot.add_cog(Games())
bot.add_cog(Music(bot=bot))

bot.run("tokenをおく")

Cogされるファイルの中身は?

以前は以下のように、単純なクラスでした。

cog_music.py
from discord.ext import commands as c

class Music:
    def __init__(self, bot):
        self.bot = bot
    @c.command()
    async def music_youtube(self, ctx, *, name):
        ...

Cogの改定について

Cogが改定されたのは、2019年2月23日。以下のような変更点があります。

  • Cogのクラスは、すべてdiscord.ext.commands.Cogから継承しないといけない
  • そうしないと、Cogを読み込んでもらえない
  • Cog用のエラーチェックなどの方法が変わった

上のコードを書き直して

cog_music.py
from discord.ext import commands as c

class Music(c.Cog, name="Music"):
    def __init__(self, bot):
        self.bot = bot
    @c.command()
    async def music_youtube(self, ctx, *, name):
        ...

c.Cogが追加されていますね。
nameは既定でクラス名と同じなので、省いても大丈夫です。

ほかにも

  • Cog内でon_messageなどを使っている場合は、@c.Cog.listener()を付けましょう。
  • Cogのコマンドをtupleで得るには、Cog.get_commands()が使えます。
  • Command.instanceCommand.cogになりました!
  • Cog関連で__から始まる名前の関数は、すべて改名されています。

公式ドキュメント

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