[Discord.py] 身内向けにDiscord上からAI画像生成を行うbotを作った
Botの概要
ローカル環境で起動しているStable Diffusion WebUIをDiscordから操作するためのBot。
なぜ作った?
A. MEE6の画像生成をDiscordサーバで遊んでたけどすぐに生成回数のLimitが来てしまい腹が立ったから。
既存のBOTを使えばよいのでは
A. いいえ
動作イメージ
コマンドを入力して。
![](https://assets.st-note.com/img/1706704781206-yZWtnT3GWH.png?width=1200)
数秒待つと画像が帰ってくる。
![](https://assets.st-note.com/img/1706704802383-WqDEm0PBL4.png)
また、設定を確認したり、設定を変更したりすることもできる。
![](https://assets.st-note.com/img/1706705500445-P5CoH6oCru.png?width=1200)
いまできるのはそれだけ。身内で遊ぶ分には十分だけど気が向いたらちょこちょこ機能を拡張してみようと思う。
ハマったポイント
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.
つまり、下のようなコードを書くとエラーになる。
@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日かかった。