You need to enable JavaScript to run this app. Discord.py经济系统getprimo随机赚钱命令运行异常问题求助
优惠活动
大模型
产品
解决方案
定价
更多

Discord.py经济系统getprimo随机赚钱命令运行异常问题求助

Discord机器人getprimo命令问题排查与修复

问题排查

  • 未做注册状态校验:当前getprimo命令没有判断触发用户是否已经注册,未注册用户调用命令时会直接抛出KeyError异常,导致命令无响应。
  • 缺少冷却错误提示:仅配置了冷却规则,没有对应的冷却触发错误处理,用户在冷却期内调用命令时不会收到任何提示,只会看到命令无响应,同时控制台会打印冷却报错。
  • 随机数范围不符合预期(可选):random.randrange(0, 100)生成的随机数范围是099,若你期望的是0100的随机数额,需要调整参数为random.randrange(0, 101)或者用random.randint(0,100)。
  • 缺失启动数据加载逻辑:现有代码只有数据保存逻辑,没有启动时读取amounts.json的逻辑,机器人重启后所有用户数据都会清空,且amounts初始为空,已注册用户调用命令也会报错。

修复代码

1. 新增启动数据加载逻辑

在代码头部添加以下内容,确保启动时加载已有的用户数据:

import json
import random
import discord
from discord.ext import commands

# 初始化amounts变量,启动时加载已有数据
amounts = {}
try:
    with open('amounts.json', 'r') as f:
        amounts = json.load(f)
except FileNotFoundError:
    # 文件不存在时初始化空字典
    pass

2. 修正getprimo命令逻辑

@client.command(pass_context=True)
@commands.cooldown(1, 300, commands.BucketType.user)
async def getprimo(ctx):
    id = str(ctx.message.author.id)
    # 新增注册状态校验
    if id not in amounts:
        em = discord.Embed(
            title = f'Account Not Registered',
            description = f'You do not have an account <:_pBaffled:827075083670650950>.\nUse %register to make an account.',
            color= ctx.author.color
        )
        await ctx.send(embed = em)
        return
    # 可按需调整随机数范围
    amount = random.randint(0, 100)
    amounts[id] += amount
    em9 = discord.Embed(
        title = f'Primogems Earned',
        description = f'You get {amount} <:primogem:853895082646044672>.\nPlease wait 5 minutes to get more primo <:_Paimon6:827074349450133524>.',
        color= ctx.author.color
    )
    await ctx.send(embed = em9)
    _save()

3. 新增冷却错误提示

添加以下错误处理逻辑,用户触发冷却时会收到明确提示:

@getprimo.error
async def getprimo_error(ctx, error):
    if isinstance(error, commands.CommandOnCooldown):
        em = discord.Embed(
            title = f'Command On Cooldown',
            description = f'Please wait {round(error.retry_after / 60, 1)} minutes before using this command again <:_pBaffled:827075083670650950>.',
            color = ctx.author.color
        )
        await ctx.send(embed = em)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 14:57:01