添加defer后触发AttributeError:'Context'对象无'response'属性求助
修复discord.py混合命令的defer功能错误
错误原因
你的混合命令仅声明了interaction: discord.Interaction参数,但混合命令支持斜杠调用和前缀调用两种模式:
- 斜杠调用时传入
discord.Interaction对象 - 前缀调用时传入
commands.Context对象
当用前缀触发命令时,实际传入的是Context对象,它没有response属性,因此抛出AttributeError: 'Context'对象没有'response'属性。
修复方案
改用commands.Context作为命令参数,discord.py会自动适配两种调用场景,再通过ctx.interaction判断是否为斜杠命令,分别处理defer逻辑:
import asyncio import aiohttp import discord from discord.ext import commands import checks # 假设你的checks模块已正确导入 class Fun(commands.Cog, name="fun"): def __init__(self, bot): self.bot = bot @commands.hybrid_command( name="randomfact", description="Get a random fact." ) @checks.not_blacklisted() async def randomfact(self, ctx: commands.Context) -> None: """ Get a random fact. """ async with aiohttp.ClientSession() as session: async with session.get("https://uselessfacts.jsph.pl/random.json?language=en") as request: if request.status == 200: data = await request.json() embed = discord.Embed( description=data["text"], color=0xD75BF4 ) else: embed = discord.Embed( title="Error!", description="There is something wrong with the API, please try again later", color=0xE02B2B ) # 区分斜杠命令和前缀命令 if ctx.interaction: # 斜杠命令:先defer,再发送跟进消息 await ctx.interaction.response.defer(ephemeral=True) await asyncio.sleep(4) await ctx.interaction.followup.send(embed=embed, ephemeral=True) else: # 前缀命令:直接发送消息 await asyncio.sleep(4) await ctx.send(embed=embed)
关键改动说明
- 将参数从
interaction: discord.Interaction改为ctx: commands.Context,兼容两种调用方式 - 通过
ctx.interaction判断是否为斜杠命令:存在则是斜杠调用,否则是前缀调用 - 前缀命令无需defer,直接用
ctx.send回复即可
内容的提问来源于stack exchange,提问作者Bonjour
相关产品推荐
相关产品推荐

