Discord.py 2.0.0创建服务器后代码终止,需生成邀请链接方案
问题分析与解决
你的代码有两个关键问题导致后续代码无法执行:
- 重复调用交互响应方法:
interaction.response.send_message只能调用一次,多次调用会触发异常,直接终止代码执行。 - 未处理异步操作的潜在异常:创建服务器的异步操作若因响应错误触发异常,会直接中断后续代码运行。
修正后的代码
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,提问作者阿諾到此一遊
相关产品推荐
相关产品推荐

