栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Discord money机器人将用户ID保留在json文件中。Bot重新启动时,会为每个人创建一个新的(但相同的)ID

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Discord money机器人将用户ID保留在json文件中。Bot重新启动时,会为每个人创建一个新的(但相同的)ID

发生这种情况是因为JSON对象始终具有用于“键”的字符串。因此

json.dump
将整数键转换为字符串。您可以通过在使用用户ID之前将其转换为字符串来完成相同的操作。

from discord.ext import commandsimport discordimport jsonbot = commands.Bot('!')amounts = {}@bot.eventasync 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 = str(ctx.message.author.id)    if id in amounts:        await ctx.send("You have {} in the bank".format(amounts[id]))    else:        await ctx.send("You do not have an account")@bot.command(pass_context=True)async def register(ctx):    id = str(ctx.message.author.id)    if id not in amounts:        amounts[id] = 100        await ctx.send("You are now registered")        _save()    else:        await ctx.send("You already have an account")@bot.command(pass_context=True)async def transfer(ctx, amount: int, other: discord.Member):    primary_id = str(ctx.message.author.id)    other_id = str(other.id)    if primary_id not in amounts:        await ctx.send("You do not have an account")    elif other_id not in amounts:        await ctx.send("The other party does not have an account")    elif amounts[primary_id] < amount:        await ctx.send("You cannot afford this transaction")    else:        amounts[primary_id] -= amount        amounts[other_id] += amount        await ctx.send("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")


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/614172.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号