我最近开始用 Python 制作一个 Discord 机器人(用它测试 Python 的基础),并自己创建了一个带有多个命令的功能机器人。为了扩大其用途,我添加了一个级别/XP 系统,到目前为止该系统正在运行。
[...]
@bot.event
async def on_message(message):
user_add_xp(message.author.id, 2)
await bot.process_commands(message)
# commands go here
def user_add_xp(user_id, xp):
if os.path.isfile('users.json'):
try:
with open('users.json', 'r') as fp:
users = json.load(fp)
users[user_id]['xp'] += xp
with open('users.json', 'w') as fp:
json.dump(users, fp, sort_keys=True, indent=4)
except KeyError:
with open('users.json', 'r') as fp:
users = json.load(fp)
users[user_id] = {}
users[user_id]['xp'] = xp
with open('users.json', 'w') as fp:
json.dump(users, fp, sort_keys=True, indent=4)
else:
users = {user_id: {}}
users[user_id]['xp'] = xp
with open('users.json', 'w') as fp:
json.dump(users, fp, sort_keys=True, indent=4)
[...]
但为了防止用户在某些频道中大量涌入/垃圾邮件并飙升至顶部,我想在 XP 的奖励上添加一个冷却/计时器。我尝试添加@commands.cooldown(1, 120, commands.BucketType.server)
二者皆是@bot.event
and user_add_xp
,但两者都没有得到我想要的结果。
我不知道如何添加这个冷却时间/计时器。
最后,我希望机器人每两分钟只授予一次 XP。