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

基于JDA开发Discord机器人AFK系统遇阻,求可用功能实现代码参考

Discord 机器人AFK系统实现方案(discord.py 框架)

前置要求

  • 已安装discord.py依赖,安装命令:pip install discord.py
  • 机器人已在Discord开发者后台开启「Message Content Intent」权限
  • 机器人被授予「修改昵称」「发送消息」「读取消息内容」权限

完整可运行代码

import discord
from discord.ext import commands

# 存储AFK用户数据,结构:{用户ID: 原始昵称}
afk_users = {}

# 配置机器人权限
intents = discord.Intents.default()
intents.message_content = True
intents.members = True

bot = commands.Bot(command_prefix='/', intents=intents)

@bot.event
async def on_ready():
    print(f'已成功登录为 {bot.user}')

# AFK状态开启命令
@bot.command()
async def afk(ctx):
    user_id = ctx.author.id
    if user_id in afk_users:
        await ctx.send(f"{ctx.author.mention} 你已经处于AFK状态", delete_after=3)
        return
    
    # 保存用户原始昵称
    original_nick = ctx.author.display_name
    afk_users[user_id] = original_nick
    
    # 给昵称添加[AFK]前缀
    new_nick = f"[AFK] {original_nick}"
    try:
        await ctx.author.edit(nick=new_nick)
        await ctx.send(f"{ctx.author.mention} 已成功开启AFK状态", delete_after=3)
    except discord.Forbidden:
        await ctx.send("权限不足,无法修改你的昵称,AFK状态开启失败", delete_after=3)
        del afk_users[user_id]

# 消息监听逻辑,处理AFK提醒和自动解除
@bot.event
async def on_message(message):
    # 忽略机器人自身发送的消息
    if message.author.bot:
        return
    
    user_id = message.author.id
    # 发送消息的用户处于AFK状态则自动解除
    if user_id in afk_users:
        original_nick = afk_users.pop(user_id)
        try:
            await message.author.edit(nick=original_nick)
            await message.channel.send(f"{message.author.mention} 已自动解除AFK状态", delete_after=3)
        except discord.Forbidden:
            await message.channel.send("权限不足,无法恢复你的昵称,已自动清除AFK记录", delete_after=3)
    
    # 检测是否@了AFK状态的用户,自动发送提醒
    for mention in message.mentions:
        if mention.id in afk_users:
            await message.channel.send(f"{mention.mention} is afk")
    
    await bot.process_commands(message)

# 替换为你自己的机器人Token后即可运行
bot.run("你的机器人Token")

使用说明

  • 发送命令/afk即可开启AFK状态,昵称自动添加[AFK]前缀
  • 其他用户@AFK状态用户时,机器人会自动发送对应提醒
  • AFK状态用户发送任意消息即可自动解除AFK,恢复原始昵称

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 13:54:04