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

Discord.py 2.0.0创建服务器后代码终止,需生成邀请链接方案

问题分析与解决

你的代码有两个关键问题导致后续代码无法执行:

  1. 重复调用交互响应方法:interaction.response.send_message只能调用一次,多次调用会触发异常,直接终止代码执行。
  2. 未处理异步操作的潜在异常:创建服务器的异步操作若因响应错误触发异常,会直接中断后续代码运行。

修正后的代码

async def create(self, interaction: discord.Interaction):
    # 先延迟响应,避免创建服务器耗时导致交互超时
    await interaction.response.defer(ephemeral=False)
    
    # 创建服务器
    guild = await self.bot.create_guild(name="My server")
    
    # 获取默认文本频道并生成邀请链接
    try:
        default_channel = guild.text_channels[0]
        inv = await default_channel.create_invite(max_age=3600, max_uses=5)
        
        # 用followup发送后续消息,这是响应后发消息的正确方式
        await interaction.followup.send(f"服务器创建完成!邀请链接:{inv.url}")
    except IndexError:
        await interaction.followup.send("创建服务器后未找到默认文本频道,请检查机器人权限。")
    except Exception as e:
        await interaction.followup.send(f"创建邀请链接失败:{str(e)}")

关键说明

  • 使用interaction.response.defer():创建服务器可能需要几秒时间,defer可以告知Discord“正在处理,稍后回复”,避免交互超时失效。
  • 改用interaction.followup.send():初始响应(包括defer)之后,必须用followup发送后续消息,不能重复调用interaction.response.send_message。
  • 增加异常处理:覆盖找不到频道、创建邀请失败等场景,避免程序崩溃同时给出明确提示。

内容的提问来源于stack exchange,提问作者阿諾到此一遊

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 13:05:19