2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

discord.py - コンバーターを手動で使う

Last updated at Posted at 2021-06-19

始めに

discord.pyのcommandsフレームワークのコンバーターを手動で使う方法を解説します。

環境

- Python v3.9.2-final
- discord.py v1.7.3-final
- aiohttp v3.6.3
- system info: Windows 10 10.0.17134

python -m discord -vの情報。

tl;dr

await commands.converter.ConverterClassHere().convert(ctx, m.content)

※ConverterClassHereはここのクラス名で置き換えて下さい。

何をしているのか

commandsフレームワークのコンバーターは

class MemberConverter(IDConverter):
    ...
    async def convert(self, ctx, argument):
        bot = ctx.bot
        match = self._get_id_match(argument) or re.match(r'<@!?([0-9]+)>$', argument)
        guild = ctx.guild
        result = None
        user_id = None
        ...

のようにコンバーター用のクラスがあり、そのインスタンスメソッドにconvertが実装されています。
そのため、インスタンスを作ってconvertを呼び出せば手動で使うことが出来ます。

サンプル

@bot.command()
async def sample_wizard(ctx):
    await ctx.send("メンバーを送信して下さい。")
    message = await bot.wait_for("message", check=lambda m: m.channel == ctx.channel)
    members = [await commands.converter.MemberConverter().convert(ctx, raw_single_member) for raw_single_member in message.content.split()]
    for member in members:
        await member.kick()
    await ctx.send(f"{len(members)}人のメンバーをキックしました。")

image.png

最後に

discord.pyのcommandsフレームワークのコンバーターを手動で使う方法を解説しました。
ウィザードのようなものを作るときやメッセージURLからメッセージを取得するときなどに使えると思います。

最後まで読んでいただきありがとうございました。

おまけ

discord.py 2.0でcommands.run_convertersが追加されるようですが、引数ではないと使えないようです(inspect.Parameterが必要)。


3000文字Tips - 知ると便利なTipsをみんなへ届けよう」への投稿記事です。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?