【问题标题】:Discord py give command error. I am making economy discord py bot, but give command doesn't workDiscord py 给出命令错误。我正在制作经济不和谐 py 机器人,但给出命令不起作用
【发布时间】:2020-12-21 01:33:55
【问题描述】:
import discord
from discord.ext import commands
import os
import json
import random
from discord.ext.commands import Bot


os.chdir("")

有正确的路径,我检查了这个

Bot = commands.Bot(command_prefix = "$")

token = 'my token'

这也是正确的

@Bot.command()
async def give(ctx, member:discord.Member, amount = None):
    await open_account(ctx.author)
    await open_account(member)

    amount = int(amount)
    if amount == None:
        await ctx.send("Please enter the amount")
        return

    bal = await update_bank(ctx.author)

    if amount>bal[1]:
        await ctx.send("You don't have that much money")
        return

    if amount<=0:
        await ctx.send("Amount must be positive")
        return

    await update_bank(ctx.author, -1*amount, "wallet")
    await update_bank(member, 1*amount, "wallet")

    emb = discord.Embed(description = f"You gave {member.name} {amount} gold coins", color = 0x2ecc71)
    await ctx.send(embed = emb)

有完整的命令

async def open_account(user):
    
    users = await get_bank_data()


    if str(user.id) in users:
        return False
    else:
        users[str(user.id)] = {}
        users[str(user.id)]["wallet"] = 0

    with open("mainbank.json", "w") as f:
        json.dump(users, f)

    return True


async def update_bank(user, change = 0, mode = "wallet"):
    users = await get_bank_data()

    users[str(user.id)][mode] += change

    with open("mainbank.json", "w") as f:
        json.dump(users, f)

    bal = [users[str(user.id)]["wallet"]]

    return bal

如您所见,有 give 命令,但不起作用。我也知道,这个问题不在于 open_account 功能,但我不确定 update_bank。

有一个错误:

if amount>bal[1]:
IndexError: list index out of range

如果你有想法,请写出来。

【问题讨论】:

    标签: python discord discord.py


    【解决方案1】:

    您将 bal 的列表嵌套在另一个列表中:[users[str(user.id)]["wallet"]]。所以如果users[str(user.id)]["wallet"] 的值是[0, 1],它实际上就是[[0, 1]]。没有索引 1,只有索引 0 和一个一直到索引 1 的嵌套列表。您可以通过简单地删除额外的括号来解决这个问题:users[str(user.id)]["wallet"]

    您可以通过printing bal 轻松发现这一点。知道如何调试是一项非常有用的技能。

    【讨论】:

    • 你说的是update_bank函数吗?如果是,我试过了,有“'int' object is not subscriptable”错误。
    • 你正在做bal[1],所以你试图获得bal的索引1。但是,bal 已经是一个带值的整数,不能索引整数。
    • 非常感谢,终于成功了,我该学习调试了。
    • 是的,一点点调试可以大有帮助。
    猜你喜欢
    • 2021-09-27
    • 2020-11-05
    • 2021-03-23
    • 1970-01-01
    • 2019-12-29
    • 1970-01-01
    • 1970-01-01
    • 2022-01-26
    • 1970-01-01
    相关资源
    最近更新 更多