Python 将冷却时间/计时器添加到on_消息[Discord.py]
我最近开始用Python制作一个Discord机器人(用它测试Python的基础),并自己用几个命令创建了一个功能正常的机器人。为了扩大它的使用范围,我添加了一个level/XP系统,该系统目前正在运行Python 将冷却时间/计时器添加到on_消息[Discord.py],python,python-3.x,discord,discord.py,Python,Python 3.x,Discord,Discord.py,我最近开始用Python制作一个Discord机器人(用它测试Python的基础),并自己用几个命令创建了一个功能正常的机器人。为了扩大它的使用范围,我添加了一个level/XP系统,该系统目前正在运行 [...] @bot.event async def on_message(message): user_add_xp(message.author.id, 2) await bot.process_commands(message) # commands go
[...]
@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(1120,commands.BucketType.server)
添加到@bot.event
和user\u add\u xp
,但都没有得到想要的结果。
我不知道如何添加此冷却/计时器
最后,我希望bot每两分钟只授予XP一次。不确定是否可以只使用
discord.py
,但您可以将上次授予用户XP的消息存储在词典中
下面的代码存储自消息授予XP时的静态开始日期(epoch
)起的秒数。然后,当新消息事件发生时,它将检查此时间
[...]
import datetime
epoch = datetime.datetime.utcfromtimestamp(0)
@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)
time_diff = (datetime.datetime.utcnow() - epoch).total_seconds() - users[user_id]['xp_time']
if time_diff >= 120:
users[user_id]['xp'] += xp
users[user_id]['xp_time'] = (datetime.datetime.utcnow() - epoch).total_seconds()
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
users[user_id]['xp_time'] = (datetime.datetime.utcnow() - epoch).total_seconds()
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
users[user_id]['xp_time'] = (datetime.datetime.utcnow() - epoch).total_seconds()
with open('users.json', 'w') as fp:
json.dump(users, fp, sort_keys=True, indent=4)
[...]
正是我需要的,工作顺利,做我想做的。非常感谢你的帮助!