LoginSignup
4
1

More than 1 year has passed since last update.

discord.pyのインタラクションを遅らせる方法

Posted at

#discord.pyのインタラクションを遅らせる方法

discord公式の以下の文

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.

インタラクションを発生させてから3秒以内に返信しろって

結構自由度奪ってると思うんですけど

それが嫌ならfollowupを使えということらしい

制限回避の送信コード

例として、以下のコードはスラッシュコマンドで打たれたテキストをグーグルで調べて結果を返すという処理を書いています

@tree.command(name="google")
async def google_command(interaction: discord.Interaction,text:str):
    ##
    ##
    # ここで送信されたテキストをもとにgoogleで検索し結果を受け取る処理を書く
    ##
    ##
    result = #結果のテキスト
    await interaction.response.send_message(result)

このままだと検索をしている間に3秒かかってしまうこともあるので
以下のようなエラーを返すことがあります。

NotFound: 404 Not Found (error code: 10062): Unknown interaction

そこで回避するのがfollowupです。

@tree.command(name="google")
async def google_command(interaction: discord.Interaction,text:str):
    await interaction.response.defer()
    ##
    ##
    # ここで送信されたテキストをもとにgoogleで検索し結果を受け取る処理を書く
    ##
    ##
    result = #結果のテキスト
    await interaction.followup.send(result)

defer()で返答を遅延させて、followupで送信する方法です。
ただしこのfollowupはwebhookになるので注意。

制限回避の編集コード

個人的にはこっちをよく使います。
それこそ今流行りのchatGPTを使って会話とかはこっちのほうが相性いいんじゃないかな。

@tree.command(name="reply")
async def reply_command(interaction: discord.Interaction,text:str):
    message.id = #もとからあるメッセージ
    await interaction.response.defer()
    ##
    ##
    # chatGPTで返答を受信
    ##
    ##
    result = #結果のテキスト
    await interaction.followup.edit_message(message_id,content=result)
4
1
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
1