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

discord.py动态生成工单查看链接按钮故障排查求助

Discord动态生成聊天记录链接按钮修复方案

问题代码中的错误点

  1. 无法访问外部ctx变量:按钮回调函数里直接使用ctx.transcript_message无效,回调内部无法获取外部上下文对象,必须通过View初始化参数传递目标消息。
  2. 未响应Discord交互请求:点击按钮后未调用interaction.response相关方法进行响应,Discord要求所有组件交互必须在3秒内得到响应,否则会显示操作失败。
  3. 创建View但未关联到消息:代码中创建了带链接按钮的View,但没有将其发送给用户或更新原消息,导致用户看不到生成的链接按钮。

修复后的完整代码

1. 定义正确的View类

class MyView(discord.ui.View):
    def __init__(self, transcript_message):
        super().__init__(timeout=None)  # 设置timeout=None让按钮持久有效(需配合bot.add_view)
        self.transcript_message = transcript_message  # 保存目标消息到实例属性

    @discord.ui.button(label="生成查看链接", style=discord.ButtonStyle.primary)
    async def button_callback(self, button, interaction):
        # 动态生成聊天记录查看链接
        transcript_url = f"http://v927477t.beget.tech/chat-exporter/?url={self.transcript_message.attachments[0].url}"
        
        # 创建仅包含链接按钮的View
        link_view = discord.ui.View()
        link_view.add_item(
            discord.ui.Button(
                label="查看聊天记录",
                style=discord.ButtonStyle.link,
                url=transcript_url
            )
        )
        
        # 以临时消息回复点击者(仅点击者可见)
        await interaction.response.send_message(
            "已生成聊天记录查看链接:",
            view=link_view,
            ephemeral=True
        )

2. 关联View到消息

在你发送聊天记录附件的代码后,初始化View并绑定到消息:

# 原有的聊天记录导出与发送代码
transcript = await chat_exporter.export(tchannel)
transcript_file = discord.File(
    io.BytesIO(transcript.encode()),
    filename=f"transcript-{tchannel.name}_{tchannel.id}.html"
) 
transcript_message = await lchannel.send(file=transcript_file)
tauthor = await bot.fetch_user(int(ticketInfo[1]))

# 初始化View并添加到刚才发送的消息上
view = MyView(transcript_message)
await transcript_message.edit(view=view)

# 如果需要按钮长期有效,在Bot启动时注册View(discord.py v2.x)
# bot.add_view(MyView(transcript_message))  # 或者如果是全局View,需调整初始化逻辑

可选修改:替换原按钮为链接按钮

如果不想发送新消息,而是直接把原按钮替换成链接按钮,可修改回调函数:

@discord.ui.button(label="生成查看链接", style=discord.ButtonStyle.primary)
async def button_callback(self, button, interaction):
    transcript_url = f"http://v927477t.beget.tech/chat-exporter/?url={self.transcript_message.attachments[0].url}"
    
    # 清空当前View的所有按钮,添加链接按钮
    self.clear_items()
    self.add_item(
        discord.ui.Button(
            label="查看聊天记录",
            style=discord.ButtonStyle.link,
            url=transcript_url
        )
    )
    
    # 更新原消息的View
    await interaction.response.edit_message(view=self)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 17:47:22