Discord机器人AFK命令开发求助:功能异常排查与修复
Discord AFK命令问题排查与修复方案
核心问题分析
- 变量作用域冲突:
afkdict在afk命令和on_message事件中被重复定义为局部变量,导致AFK状态无法跨逻辑共享,ping用户时找不到对应记录。 - 上下文对象错误:命令中使用
ctx.user,但discord.py里命令上下文的用户对象应为ctx.author,这是「user has no context」错误的直接诱因。 - 消息回复遗漏内容:
on_message中创建了AFK提示Embed,但调用message.reply()时未传入该Embed,导致ping用户时无有效回复。 - 缺少AFK退出逻辑:未检测AFK用户主动发消息的场景,无法触发退出提示并清除AFK状态。
- 命令触发被阻断:
on_message事件中未调用bot.process_commands(),导致afk命令无法正常触发。
修复后的完整代码
import discord from discord.ext import commands bot = commands.Bot(command_prefix="!", intents=discord.Intents.all()) # 全局存储AFK状态,用用户ID做键(避免对象引用失效问题),值为AFK理由 afkdict = {} @bot.command(name="afk") async def afk_command(ctx, *, reason=None): # 用ctx.author获取命令发起用户,存储用户ID和对应理由 afkdict[ctx.author.id] = reason or "无理由" await ctx.send(f"{ctx.author.mention} 已设置AFK!现实世界注意安全!") @bot.event async def on_message(message): # 优先处理命令,避免自定义on_message阻断命令触发 await bot.process_commands(message) # 忽略机器人自身消息,防止循环触发逻辑 if message.author.bot: return # 处理AFK用户发消息:退出AFK if message.author.id in afkdict: del afkdict[message.author.id] await message.channel.send(f"{message.author.mention} 已退出AFK!") return # 处理ping AFK用户:发送状态提示 for user_id, reason in afkdict.items(): user = bot.get_user(user_id) if user in message.mentions: embed = discord.Embed(title=f"{user.display_name} 处于AFK状态", color=0xFF0000, description=reason[:2000]) await message.reply(embed=embed, mention_author=False) bot.run("你的机器人Token")
关键修复点说明
- 全局变量统一:将
afkdict设为全局变量,确保命令和事件共享状态;改用用户ID作为键,避免用户对象缓存失效导致的匹配失败。 - 修正上下文对象:替换
ctx.user为ctx.author,获取正确的命令发起用户。 - 恢复命令触发:在
on_message开头调用bot.process_commands(message),保证自定义事件不会阻断命令执行。 - 完善回复逻辑:ping用户时将Embed传入
message.reply(),确保发送AFK理由;添加mention_author=False避免不必要的@提醒。 - 新增退出检测:当AFK用户发送消息时,清除其AFK状态并发送提示。
- 过滤机器人消息:忽略机器人自身发送的消息,防止无限循环触发逻辑。
内容的提问来源于stack exchange,提问作者Ibrahim K
相关产品推荐
相关产品推荐

