[Discord.py] 身内向けにDiscord上からAI画像生成を行うbotを作った

Botの概要

ローカル環境で起動しているStable Diffusion WebUIをDiscordから操作するためのBot。

なぜ作った?

A. MEE6の画像生成をDiscordサーバで遊んでたけどすぐに生成回数のLimitが来てしまい腹が立ったから。

既存のBOTを使えばよいのでは

A. いいえ

動作イメージ

コマンドを入力して。

数秒待つと画像が帰ってくる。

また、設定を確認したり、設定を変更したりすることもできる。

いまできるのはそれだけ。身内で遊ぶ分には十分だけど気が向いたらちょこちょこ機能を拡張してみようと思う。

ハマったポイント

Discordの仕様により、BotのInteractionが3秒以内にResponseがない場合エラーが送出される。

Interaction tokens are valid for 15 minutes and can be used to send followup messages but you must send an initial response within 3 seconds of receiving the event. If the 3 second deadline is exceeded, the token will be invalidated.

https://discord.com/developers/docs/interactions/receiving-and-responding#responding-to-an-interaction

つまり、下のようなコードを書くとエラーになる。

@client.tree.command()
async def txt2img():
    response = await sd.txt2img()  # 画像生成処理 3秒以上かかる重たい処理。
    await interaction.response.send_message("END")

この場合はdeferとfollowupを使うことでエラーを回避することができる。

@client.tree.command()
async def txt2img():
    await interaction.response.defer(ephemeral=False)
    response = await sd.txt2img()  # 画像生成処理 3秒以上かかる重たい処理。
    await interaction.followup.send("END")

この仕様に気づくのに2日かかった。

いいなと思ったら応援しよう!