You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

discord.py技术咨询:bot.wait_for用法、获取interaction ID及多服View问题

1. 使用bot.wait_for监听按钮点击事件并获取交互ID

要通过bot.wait_for监听按钮点击事件,你可以直接监听'interaction'事件,再通过交互类型筛选出按钮点击的情况,同时可直接从交互对象中获取ID:

  • 基础用法示例:
import discord
import asyncio

# 监听按钮点击交互
interaction = await bot.wait_for(
    'interaction',
    check=lambda i: i.type == discord.InteractionType.component
)

# 获取交互ID
interaction_id = interaction.id
print(f"交互ID: {interaction_id}")
  • 带精确筛选(指定按钮自定义ID):
    如果需要只监听特定按钮的点击,可以在check函数中增加自定义ID的判断:
def button_check(interaction):
    return (
        interaction.type == discord.InteractionType.component
        and interaction.data.get('custom_id') == 'target_button_id'
    )

try:
    # 设置60秒超时
    interaction = await bot.wait_for('interaction', check=button_check, timeout=60.0)
except asyncio.TimeoutError:
    print("等待按钮点击超时")
else:
    interaction_id = interaction.id
    await interaction.response.send_message(f"你的交互ID: {interaction_id}")
2. 跨服务器运行的View实例是否独立?

每个通过消息发送的View实例都是完全独立的,不会跨服务器或跨消息互相影响:

  • 当你调用await channel.send(view=MyView())时,每次都会生成一个全新的MyView实例,这个实例仅与当前发送的消息绑定,和其他服务器、其他消息中的View实例没有任何关联。
  • 基于View执行的逻辑(比如按钮回调),只会作用于触发交互对应的那个View实例。也就是说,服务器A的用户点击按钮,只会触发服务器A那条消息绑定的View实例中的回调,绝对不会触发服务器B的View逻辑。

示例验证:

class MyView(discord.ui.View):
    @discord.ui.button(label="查看服务器ID", custom_id="show_guild_id")
    async def show_guild(self, interaction, button):
        # 此处的self是当前交互对应的View实例,仅关联当前消息
        await interaction.response.send_message(f"当前服务器ID: {interaction.guild.id}")

# 向服务器A发送带View的消息
await guild_a_channel.send(view=MyView())
# 向服务器B发送带View的消息
await guild_b_channel.send(view=MyView())

两个服务器的按钮点击会分别返回各自的服务器ID,完全不会互相干扰。

内容的提问来源于stack exchange,提问作者Alcoder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 10:15:05