You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Discord机器人AFK命令@提及检测失效问题求助

Discord机器人AFK提及提示无响应问题修复

问题根源

你的afk_lists是按服务器ID映射用户ID列表的字典结构({guild_id: [user_id1, user_id2]}),但在on_message事件里,错误地用user.id in afk_lists判断——这是在检查用户ID是否是字典的键(也就是服务器ID),而不是检查用户是否在对应服务器的AFK列表里,所以永远匹配不到,自然不会发送提示。

修复方案

  1. 修正on_message的判断逻辑:先获取当前消息所属服务器的ID,再检查该服务器的AFK列表是否存在,最后判断用户是否在列表中
  2. 额外优化:
    • 跳过机器人自身发送的消息,避免触发循环
    • 对同一消息中重复提及的用户,只发送一次提示,避免刷屏

修复后的完整代码

import discord
from discord.ext import commands

intents = discord.Intents.default()
intents.members = True
intents.message_content = True
bot = commands.Bot(command_prefix="-", intents=intents, case_insensitive=True)

afk_lists = {}

@bot.event
async def on_ready():
    print(f"Logged in as {bot.user.name}")

@bot.event
async def on_message(message):
    global afk_lists
    # 跳过机器人自己的消息
    if message.author.bot:
        await bot.process_commands(message)
        return

    mentioned_afk_users = set()
    if message.mentions:
        guild_id = message.guild.id
        # 先确认当前服务器有AFK列表
        if guild_id in afk_lists:
            current_afk_users = afk_lists[guild_id]
            for user in message.mentions:
                if user.id in current_afk_users and user.id not in mentioned_afk_users:
                    mentioned_afk_users.add(user.id)
                    await message.channel.send(f"{user.mention} 目前处于AFK状态!")

    await bot.process_commands(message)

@bot.command()
async def afk(ctx):
    global afk_lists
    guild_id = ctx.guild.id
    user_id = ctx.author.id

    # 初始化服务器AFK列表(如果不存在)
    if guild_id not in afk_lists:
        afk_lists[guild_id] = []
    
    # 避免重复添加AFK状态
    if user_id not in afk_lists[guild_id]:
        afk_lists[guild_id].append(user_id)
        await ctx.send("已设置AFK状态!")
    else:
        await ctx.send("你已经处于AFK状态了!")

@bot.command()
async def show_afk_list(ctx):
    global afk_lists
    guild_id = ctx.guild.id
    if guild_id in afk_lists and afk_lists[guild_id]:
        # 把用户ID转为@提及格式
        afk_mentions = [f"<@{user_id}>" for user_id in afk_lists[guild_id]]
        await ctx.send(f"当前AFK列表:{', '.join(afk_mentions)}")
    else:
        await ctx.send("AFK列表为空!")

token = "MY_TOKEN"
bot.run(token)

额外说明

  • 新增了重复设置AFK的判断,避免同一用户多次添加到列表
  • show_afk_list命令现在会把用户ID转为可点击的@提及格式,更友好
  • 加入了跳过机器人自身消息的逻辑,防止不必要的触发

内容的提问来源于stack exchange,提问作者Kaze

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 03:28:00