discord.py:在on_message事件中调用自定义mute命令时,ctx参数应传入什么对象?
解决discord.py中on_message调用命令方法的ctx参数问题
首先,你遇到的'Guild' object has no attribute 'guild'错误,根源是调用self.mute时传入的第一个参数不对——message.guild是Guild对象,但mute方法的第一个参数ctx需要的是**discord.ext.commands.Context对象**,不是Guild。
正确的调用方式
在on_message事件中,你可以通过self.get_context(message)方法从message对象生成合法的Context实例,然后把它传给mute的ctx参数:
await self.mute( ctx=await self.get_context(message), member=message.author, time="1d", reason="For too many badwords" )
当你通过命令行(比如!dc mute @person1 1d for beeing toxic)调用时,discord.py会自动处理消息,生成正确的Context对象并传入mute方法,所以不会出错。
替代ctx的方案
如果你不想依赖Context对象,可以把mute方法的核心逻辑抽离,直接接收需要的具体参数(比如guild、member等),这样在任何场景下调用都更灵活:
1. 重构方法,去掉ctx依赖
把原来的命令方法和核心逻辑分离:
# 保留命令入口,供用户通过命令行调用 @commands.command(description="Mutes the specified user.") @commands.has_permissions(manage_messages=True) async def mute(self, ctx, member: discord.Member, time=None, *, reason=None): # 从ctx中提取需要的参数,调用核心逻辑 await self._mute(ctx.guild, member, time, reason) # 核心静音逻辑,直接接收必要参数 async def _mute(self, guild: discord.Guild, member: discord.Member, time=None, reason=None): mutedRole = discord.utils.get(guild.roles, name="Muted") # 你的其他静音逻辑代码...
2. 在on_message中调用重构后的方法
现在你可以直接传入message.guild等参数,不用再处理ctx:
await self._mute( guild=message.guild, member=message.author, time="1d", reason="For too many badwords" )
这种方式的好处是,核心逻辑不再绑定Context,既可以被命令调用,也能在事件或其他自定义逻辑中复用,代码结构更清晰。
内容的提问来源于stack exchange,提问作者Harasiva4234
相关产品推荐
相关产品推荐

