async on_command_error() とは
コマンド形式 (プレフィクス式コマンド) で起きたエラーをキャッチする関数です。
引数は context
, error
の2つです。
@bot.event
async def on_command_error(ctx: commands.Context, error):
:
:
基本的な対処法
あくまで自分の考えですのでこの通りにしろ、というわけではありません。
- この関数内で isinstance(error,
エラー名
)で指定して拾う -
@コマンド名.error
で拾う。
ただし、いちいち 2 を書くのがめんどくさい、2 では拾いきれないエラーが生じることもある。という点で この関数を使用することをお勧めします。
主なエラーと説明
用語:
ユーザー ... 実行者 (人間側)
クライアント ... Bot
エラー ... クライアントがプログラムを実行した際、実行に失敗した時に起こる
commands.CommandNotFound
その名の通りコマンドが存在しません。ユーザーの打ち間違い等で起こります。
NotFound
は他に以下のものがあります。
-
GuildNotFound
ギルドが見つかりません。 -
UserNotFound
ユーザーが見つかりません -
RoleNotFound
ロールが見つかりません。 -
EmojiNotFound
絵文字が見つかりません。 -
ChannelNotFound
チャンネルが見つかりません。 -
MemberNotFound
UserNotFound と似ていますが、エラーの発生源が discord.Member からか discord.User からかで分かれます。 -
MessageNotFound
メッセージが見つかりません。 -
ThreadNotFound
スレッドが見つかりません。 -
GuildStrikerNotFound
guildstriker (自分もよくわかっていませんが鯖の画像だと思います。) が見つかりません。 -
ExtensionNotFound
commands.Cog を使って作成してる人にのみ生じます。Cog が上手く読み込めないとこれが出ます。
拾い方
if isinstance(error, commands.CommandNotFound):
commands.MissingPermissions
@bot.has_permission(manage_messages=True)
@bot.command()
async def edit_msg(ctx: commands.Context, member: int, *, args: str):
pass
この場合、メッセージ編集権限がないとこのエラーを吐きます。
また、不足している権限が missing_permissions
でリストで返されます。
commands.BotMissingPermissions
もありますが、これはBot側の権限不足で起こります。再招待してもらったりすると直る可能性があります。
discord.InvalidArgument
コマンドに対する引数が足りない時に起こります。
拾い方
if isinstance(error, discord.InvalidArgument):
discord.HTTPException
あまり起きませんが、クライアントのネット状況でメッセージが送れなかったりした場合に起こります。
拾い方
if isinstance(error, discord.HTTPException):
discord.ExtensionError
commands.Cog を使って作成しているときに発生します。
-
discord.ExtensionAlreadyLoaded
すでに読み込んだextensionを再読み込みしているときに起こります。 -
discord.ExtensionNotLoaded
extensionが読み込まれていない時に起こります。
(あまり起きないと思います。) -
discord.ExtensionFailed
def setup()
の .add_cogs() にcogのクラスが指定されていないと発生します。 -
discord.NoEntryPointError
cogの読み込みでよく発生するdef setup()
の忘れ。
最後に
エラーはよく起きますが、焦らず読みましょう。英語で書かれていますがエラー名である程度分かることが多いです。