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

Discord XP机器人ShowXP命令无响应问题技术求助

Discord XP机器人!ShowXP命令无响应问题修复

问题根源分析

你的代码存在多处语法和逻辑错误,导致命令无法正常执行:

  • 缩进错误:Python对缩进严格要求,多处代码块缩进错误导致逻辑无法触发
  • 变量未定义异常:on_message中user_id仅在特定条件下定义,后续直接引用会引发程序崩溃
  • 命令处理函数未正确封装:show_xp函数的核心逻辑未缩进在函数内部,无法被命令调用触发
  • 命令处理语句位置错误:await bot.process_commands(message)未放在on_message函数内,导致机器人无法识别命令

修复后的完整代码

import discord
from discord.ext import commands
import json
import os

intents = discord.Intents.default()
intents.messages = True
intents.guilds = True
intents.guild_messages = True
intents.message_content = True  # 新增:Discord v2.0+需此意图读取消息内容

bot = commands.Bot(command_prefix=commands.when_mentioned_or("!"), intents=intents)

xp_channel_id = 1186457318850838539  # 替换为实际频道ID
config_file = "config.json"

# 加载配置文件
if os.path.exists(config_file):
    with open(config_file, "r") as f:
        config = json.load(f)
else:
    config = {"XP": {}}

def save_config():
    with open(config_file, "w") as f:
        json.dump(config, f, indent=4)

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

@bot.event
async def on_message(message):
    # 仅在指定频道给非机器人用户增加XP
    if message.channel.id == xp_channel_id and not message.author.bot:
        user_id = str(message.author.id)
        # 基础XP增加
        config["XP"][user_id] = config["XP"].get(user_id, 0) + 1
        # 每5条消息额外奖励5XP
        if config["XP"][user_id] % 5 == 0:
            config["XP"][user_id] += 5
        save_config()
    
    # 必须在函数内部调用,才能处理命令
    await bot.process_commands(message)

@bot.command(name='ShowXP')
async def show_xp(ctx, user: discord.User = None):
    user = user or ctx.author
    if user.bot:
        return  # 忽略机器人用户
    
    user_id = str(user.id)
    xp = config["XP"].get(user_id, 0)
    level = int(xp ** 0.5)
    await ctx.send(f'{user.mention} 当前等级:{level},XP点数:{xp}!继续加油 🎉')

# 启动机器人
bot.run("你的机器人Token")

额外说明

  1. 新增intents.message_content = True:Discord v2.0版本之后,必须开启此意图才能读取消息内容,否则无法识别命令
  2. 调整XP奖励逻辑:将额外5XP的判断限定在指定频道内,避免非目标频道的消息触发变量未定义错误
  3. 统一代码缩进:确保所有逻辑代码在正确的函数作用域内执行

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 21:17:29