Discord机器人添加用户积分功能无响应问题求助
Discord机器人addpoints命令无输出问题修复
问题概述
想要实现>addpoints @提及用户 积分数量命令,将用户积分存储到pts.json文件中,但代码无报错也无任何输出,核心疑问是member.mention.id的用法是否正确。
错误点分析
member.mention.id用法错误:member.mention返回的是@用户格式的字符串(如<@123456>),该字符串没有id属性。获取用户ID应直接使用member.id。- 初始数据结构错误:全局变量
pts初始化为{"points": []},但实际需要用字典存储用户ID到积分的映射,应改为{"points": {}}。 save_pts函数变量错误:函数中使用了未定义的data变量,需替换为全局的pts;同时先执行open(..., 'w').close()是多余操作,直接写入即可。- 全局变量未正确声明:
on_ready事件中读取pts.json后,未用global pts声明,导致修改的是局部变量,全局pts未更新。 - 消息对象引用错误:
addpoints命令中使用await message.add_reaction,但函数参数是ctx,无message变量,应改为await ctx.message.add_reaction("✅")。 - 代码缩进错误:积分累加逻辑被包裹在
if语句块内,仅用户首次添加时才执行累加,正常逻辑应为:用户不存在则初始化为0,之后无论是否存在都执行积分累加。
修正后的完整代码
import discord import json import os from discord.ext import commands bot = commands.Bot(command_prefix=">", intents=discord.Intents.all()) # 初始化积分数据结构:用字典存储用户ID到积分的映射 pts = {"points": {}} def save_pts(): # 直接写入pts数据到文件,无需提前清空 with open(os.environ['ptsbase_path'], "w") as file: json.dump(pts, file, indent=4, sort_keys=True) @bot.event async def on_ready(): global pts # 声明使用全局变量pts # 替换为你的服务器ID guild = discord.utils.get(bot.guilds, id=int(123456789012345678)) if os.path.isfile(os.environ['ptsbase_path']): with open(os.environ['ptsbase_path'], encoding="utf-8") as file: pts = json.load(file) else: save_pts() print(f"已登录为 {bot.user}") @bot.command(help="给用户添加积分") async def addpoints(ctx, member: discord.Member, amount: int): user_id = str(member.id) # 获取用户ID并转为字符串 # 如果用户不在积分字典中,初始化为0 if user_id not in pts['points']: pts['points'][user_id] = 0 # 累加积分 pts['points'][user_id] += amount save_pts() await ctx.message.add_reaction("✅") # 替换为你的机器人Token bot.run("YOUR_BOT_TOKEN")
内容的提问来源于stack exchange,提问作者Alsatian
相关产品推荐
相关产品推荐

