Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
490 views
in Technique[技术] by (71.8m points)

python 3.x - How to get discord.py bot to show different stats for every player?

So, I tried to make a currency bot a while back, but it ended up that everyone in the server shared the same amount of currency.

How would I make the users of a bot each have seperate accounts, and not all share the same balance?

Help would be appreciated!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can set up a dictionary of Members to amounts of currency. I would probably use the member ids, so that you can save the file when you want to shut off your bot.

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")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...