Discord机器人AFK命令报错:ctx未找到,求解决方案
解决Discord机器人AFK命令中的
ctx is not found错误 错误原因
on_typing是Discord.py的事件监听器,它的参数只有channel, user, when,不存在ctx这个参数,你直接调用ctx.author自然会触发未定义错误。
修复步骤
- 把代码里的
ctx.author替换为事件参数自带的user对象,user就是当前正在输入的用户实例。 - 修正昵称处理逻辑,直接从
user的昵称中移除[AFK]前缀(增加判断避免重复操作)。 - 顺带修复其他潜在问题:
- 原代码用列表交替存储用户ID和AFK消息,极易出现索引越界,建议改用字典存储(键为用户ID,值为AFK消息)。
on_message里的return None会直接终止函数,导致后续break无效;同时循环步长未设置为2,容易触发i+1索引越界。
修正后的完整代码
# 先在Cog的__init__方法里初始化AFK数据存储 def __init__(self, bot): self.bot = bot self.afk_data = {} # 替换原有的self.data列表 async def afk(self, ctx, *args): msg = ' '.join(args) if args else "未设置离开消息" self.afk_data[ctx.author.id] = msg # 避免重复添加[AFK]前缀 if not ctx.author.display_name.startswith('[AFK]'): await ctx.author.edit(nick=f'[AFK] {ctx.author.display_name}') await ctx.send("AFK状态已设置!") @commands.Cog.listener() async def on_message(self, message): if message.author.bot: return # 遍历AFK用户字典 for user_id, afk_msg in self.afk_data.items(): if f"<@{user_id}>" in message.content: await message.channel.send(f"<@{user_id}> 现在处于AFK状态,留言:{afk_msg}") break @commands.Cog.listener() async def on_typing(self, channel, user, when): if user.id in self.afk_data: # 删除AFK状态 del self.afk_data[user.id] # 移除昵称中的[AFK]前缀 if user.display_name.startswith('[AFK]'): original_nick = user.display_name.replace('[AFK] ', '', 1) # 仅替换开头的一次前缀 await user.edit(nick=original_nick) await channel.send(f"{user.mention},欢迎回来!")
额外说明
- 用字典存储AFK数据更直观,彻底避免了列表操作中索引混乱、越界的问题。
- 增加了昵称前缀重复判断,防止出现
[AFK] [AFK] 用户名的异常情况。
内容的提问来源于stack exchange,提问作者random kid
相关产品推荐
相关产品推荐

