admin管理员组

文章数量:1122832

I want to question how do I fix the error. The problem is; the bot says "This interaction failed" when I select the option on ok_button function. And there is no error logs. Could you resolve my problem? It's for my project so I really want to resolve this quickly.

Here's what I tried:

Turning off the ephemeral mode: Nothing changed so unlikely that error is causing from ephemeral message

When I This is the following Log that Discord.py said

[2025-01-06 13:02:45] [INFO    ] discord.client: logging in using static token
[2025-01-06 13:02:46] [INFO    ] discord.gateway: Shard ID None has connected to Gateway (Session ID: b639f3cf5e021f92343b8f456bc7a57b).
Logged in as テスト用bot#6295
Received interaction: 1325675932790427728
Interaction 1325675932790427728 deferred.
Follow-up message sent for interaction 1325675932790427728

Here's the full code (Changed the Token part for safety)

import discord
from discord.ext import commands
from discord import app_commands

intents = discord.Intents.all()
bot = commands.Bot(command_prefix="/", intents=intents)

@bot.event
async def on_ready():
    await bot.tree.sync()
    print(f"Logged in as {bot.user}")

@bot.treemand(name="avatar", description="このbotのアイコンを貼ります。")
async def avatar(interaction: discord.Interaction):
    await interaction.response.send_message(".jpeg")

# モーダルの定義
class AnosayModal(discord.ui.Modal):
    def __init__(self, channel: discord.TextChannel):
        super().__init__(title="メッセージ送信モーダル")
        self.channel = channel

        # メッセージ入力フィールドを追加
        self.add_item(
            discord.ui.TextInput(
                label="送信したいメッセージを下に入力してください。",
                style=discord.TextStyle.paragraph,
                placeholder="256文字まで入力できます。",
                required=True,
                max_length=256  # Discordのメッセージ上限
            )
        )

    async def on_submit(self, interaction: discord.Interaction):
        message = self.children[0].value  # 入力フィールドの値を取得
        await self.channel.send(f"{message}")
        await interaction.response.send_message("メッセージを送信しました。", ephemeral=True)

# /anosayコマンド
@bot.treemand(name="anosay", description="匿名でメッセージを送信します。")
async def anosay(interaction: discord.Interaction):
    modal = AnosayModal(channel=interaction.channel)
    await interaction.response.send_modal(modal)

# チャンネル設定ビュー
class ChannelSetupView(discord.ui.View):
    def __init__(self, guild: discord.Guild):
        super().__init__()
        self.guild = guild
        self.thread_channel = None

        # 宣伝スレッド用チャンネル選択メニュー
        self.select_thread_channel = discord.ui.Select(
            placeholder="宣伝スレッドにするチャンネルを選択",
            options=self.get_channel_options(),
            custom_id="select_thread_channel"
        )
        self.add_item(self.select_thread_channel)

        # OKボタン
        self.ok_button = discord.ui.Button(
            label="OK",
            style=discord.ButtonStyle.danger,  # 初めは濃い赤色
            disabled=True,  # 初めは無効
        )
        self.ok_button.callback = self.ok_button_callback
        self.add_item(self.ok_button)

    def get_channel_options(self):
        # サーバーのテキストチャンネルを取得して選択肢として表示
        return [
            discord.SelectOption(label=channel.name, value=str(channel.id))
            for channel in self.guild.text_channels
        ]

    async def ok_button_callback(self, interaction: discord.Interaction):
        # Only send the response if the interaction hasn't been responded to yet
        if not interaction.response.is_done():
            if self.thread_channel:
                await interaction.response.send_message(
                    f"設定が完了しました!\n"
                    f"宣伝スレッド: {self.thread_channel.mention}",
                    ephemeral=True
                )
            else:
                await interaction.response.send_message(
                    "チャンネルが選択されていません。",
                    ephemeral=True
                )

    async def select_callback(self, interaction: discord.Interaction, custom_id: str, selected_value: str):
        # Handle channel selection and update the button state
        if custom_id == "select_thread_channel":
            self.thread_channel = interaction.guild.get_channel(int(selected_value))

        # Defer the interaction so it doesn't fail when processing updates
        await interaction.response.defer(ephemeral=True)

        # Update message with the current selection
        await interaction.followup.send(
            f"現在の設定:\n"
            f"宣伝スレッド: {self.thread_channel.mention if self.thread_channel else '未設定'}",
            ephemeral=True
        )

        # Update the OK button based on the channel selection
        self.update_ok_button()

    def update_ok_button(self):
        if self.thread_channel:
            # チャンネルが選択されたらOKボタンを有効化して色を変える
            self.ok_button.disabled = False
            self.ok_button.style = discord.ButtonStyle.success
        else:
            # チャンネルが選択されていない場合はOKボタンを無効にする
            self.ok_button.disabled = True
            self.ok_button.style = discord.ButtonStyle.danger

# 注意事項ビュー
class WarningView(discord.ui.View):
    def __init__(self):
        super().__init__()

    @discord.ui.button(label="OK", style=discord.ButtonStyle.primary)
    async def ok_button(self, interaction: discord.Interaction, button: discord.ui.Button):
        # チャンネル設定画面に移行
        view = ChannelSetupView(interaction.guild)
        # チャンネル選択ができるようにビューを更新
        await interaction.response.edit_message(
            content="次に、宣伝スレッドにするチャンネルを選択してください。",
            view=view
        )

# /setup_adveコマンド
interaction_status = {}

@bot.treemand(name="setup_adve", description="注意事項を確認します")
async def setup_adve(interaction: discord.Interaction):
    try:
        # Check if this interaction has been processed already
        if interaction_status.get(interaction.id, False):
            print(f"Interaction {interaction.id} has already been completed.")
            return  # Don't proceed if interaction is finished
        
        # Mark the interaction as in-progress
        interaction_status[interaction.id] = False

        print(f"Received interaction: {interaction.id}")
        
        # Defer the interaction
        await interaction.response.defer(ephemeral=True)
        print(f"Interaction {interaction.id} deferred.")

        warning_message = (
            "**注意事項**\n"
            "1. 宣伝スレッドにするチャンネルを選択してください。\n"
            "2. 設定が完了するとOKボタンが有効になります。\n\n"
            "内容を確認したら、「OK」を押して次に進んでください。"
        )

        view = WarningView()

        # Send the follow-up message
        await interaction.followup.send(
            content=warning_message, view=view, ephemeral=True
        )
        print(f"Follow-up message sent for interaction {interaction.id}")
        
        # Mark the interaction as finished after sending the response
        interaction_status[interaction.id] = True

    except discord.errors.NotFound:
        # Handle invalidated interaction
        print(f"Error: Interaction {interaction.id} has been invalidated or expired.")
    except Exception as e:
        # Handle any other errors
        print(f"Unexpected error: {e}")

bot.run(TOKEN)

What are your thoughts? Answering to my question would be helpful, thank you!

本文标签: pythonquotThis interaction failedquot with no error logs showing upStack Overflow