如何让discord.py机器人为每个玩家显示不同的统计数据?

时间:2018-06-16 17:50:31

标签: python-3.x discord.py

所以,我试图制作一个货币机器人,但结果是服务器中的每个人共享相同数量的货币。

我如何让机器人的用户各自拥有单独的帐户,而不是所有人都拥有相同的余额?

帮助将不胜感激!

1 个答案:

答案 0 :(得分:1)

您可以设置Member s字典到货币数量。我可能会使用成员ID,以便您可以在关闭机器人时保存文件。

from discord.ext import commands
import discord
import json

bot = commands.Bot('!')

amounts = {}

@bot.event
async def on_ready():
    global amounts
    try:
        with open('amounts.json') as f:             
            amounts = json.load(f)
    except FileNotFoundError:
        print("Could not load amounts.json")
        amounts = {}

@bot.command(pass_context=True)
async def balance(ctx):
    id = ctx.message.author.id
    if id in amounts:
        await bot.say("You have {} in the bank".format(amounts[id]))
    else:
        await bot.say("You do not have an account")

@bot.command(pass_context=True)
async def register(ctx):
    id = ctx.message.author.id
    if id not in amounts:
        amounts[id] = 100
        await bot.say("You are now registered")
        _save()
    else:
        await bot.say("You already have an account")

@bot.command(pass_context=True)
async def transfer(ctx, amount: int, other: discord.Member):
    primary_id = ctx.message.author.id
    other_id = other.id
    if primary_id not in amounts:
        await bot.say("You do not have an account")
    elif other_id not in amounts:
        await bot.say("The other party does not have an account")
    elif amounts[primary_id] < amount:
        await bot.say("You cannot afford this transaction")
    else:
        amounts[primary_id] -= amount
        amounts[other_id] += amount
        await bot.say("Transaction complete")
    _save()

def _save():
    with open('amounts.json', 'w+') as f:
        json.dump(amounts, f)

@bot.command()
async def save():
    _save()

bot.run("TOKEN")