我想问一下如何为不同的服务器存储变量,因为我有一个“F”on message命令,它将F存储在json中,这样我就可以跟踪它在不同服务器上被调用了多少次。我还想知道如何在bot关闭时将其转储到json中,因为现在惟一的转储方法是运行命令自动断开. 在
filename = "respectspaid.json"
respects = 0
with open(filename) as f_obj:
respects = json.load(f_obj)
@bot.event
async def on_message(message):
print(f"{message.channel}: {message.author}: {message.author.name}: {message.content}")
cajo_guild = bot.get_guild(ID)
if message.author == client.user:
return
if message.author.bot:
return
if "aut.membercount" == message.content.lower():
await message.channel.send(f"```py\n{cajo_guild.member_count}```")
elif "F" == message.content:
global respects
respects += 1
await message.channel.send(f"```Respects paid: {respects}```")
elif "aut.disconnect" == message.content.lower():
with open(filename, 'w') as f_obj:
json.dump(respects, f_obj)
print("Dumping and closing client...")
await bot.close()
sys.exit()
await bot.process_commands(message)
当我断开bot(当我关闭我的电脑)时,我转储更新的F计数,当我运行程序时加载它,每次发送“F”时都会更新它,但我不知道如何在多个服务器上做到这一点。这个机器人将主要用于我朋友的服务器,我让机器人做一些他们想要的笑话,所以我不希望机器人做一些更重的事情。在
如果希望每个服务器有一个不同的计数,则需要将统计数据保存在dict json文件中
因此,与其使用
respects += 1
,不如使用respects[str(guild.id)] += 1
。这还有一个额外的好处,即不需要全局语句,因为dicts是不可变的。将guild ID字符串化是因为python dict键可以是int,而json对象键只能是字符串。在为了回答你的另一个问题,你有几个选择。最简单的方法是每次调用后保存:
另一种方法是使用断开连接处理程序
^{pr2}$但这不能处理代码不能干净地退出的情况(例如系统关闭)
相关问题 更多 >
编程相关推荐