【问题标题】:Code executing 3 times itself without telling it to do so代码自己执行 3 次而不告诉它这样做
【发布时间】:2020-11-06 13:58:26
【问题描述】:

我目前正在为我的不和谐机器人制作自定义徽章系统,但是当我执行命令时,它经历了 3 次。我认为这取决于 JSON 文件,所以如果用户在 JSON 文件中并且在第二个文件中,它将经历 2 次。

我的代码:

@client.command()
@commands.guild_only()
async def userinfo(ctx, *, user: discord.Member = None):
            if user is None:
                user = ctx.author
            try:
                data = get_data()
                embed = discord.Embed(timestamp=ctx.message.created_at, colour=discord.Color.dark_green())
                for profile in data:
                    print("Checking if user is in db")
                    if profile['discord_id'] == f"{user.id}":
                        print("User is in db")
                        badges = profile["badges"]
                        date_format = "%a, %d %b %Y %I:%M %p"
                        embed.set_author(name=f"{user}", icon_url=user.avatar_url)
                        embed.set_thumbnail(url=user.avatar_url)
                        embed.add_field(name="Badges", value=badges, inline=True)
                        embed.set_footer(text=f"Requested by {ctx.author.name}#{ctx.author.discriminator}", icon_url=ctx.author.avatar_url)
                    else:
                        print("User not in db, registering user into db")
                        data = get_data()
                        data.append({"discord_id": f"{user.id}", "badges": "None."})
                        set_data(data)
                await ctx.send(embed = embed)
            except Exception as e:
                await ctx.send(f"error {e}")
def get_data():
    with open('profiles.json', 'r') as file:
        return loads(file.read())

def set_data(data):
    with open('profiles.json', 'w') as file:
        file.write(dumps(data, indent=2))

def profile(badges, discord_id, mode):
    data = get_data()
    if mode == 'create':
        data.append({"discord_id": discord_id, "badges": badges})
    elif mode == 'modify':
        for profile in data:
            if profile['discord_id'] == f"{discord_id}":
                profile = {'discord_id': f"{discord_id}", 'badges': f"{badges}"}
    set_data(data)

JSON 文件:

[
  {
    "discord_id": "727823455734464642",
    "badges": "<:verified:774247562299310101> <:botdev:774247435483480084>"
  },
  {
    "discord_id": "744337705940287499",
    "badges": "<:bot:774254414214725683>"
  },
  {
    "discord_id": "689415225891487774",
    "badges": "None."
  }
]

谢谢!

【问题讨论】:

    标签: python json python-3.x discord.py


    【解决方案1】:

    想想您构建循环和 if 语句的方式。这是一些旨在复制您的错误的代码:

    users = ["bob", "tom", "james"]
    
    user_to_find = "tom"
    
    for user in users:
        if user == user_to_find:
            print(f"{user_to_find} is in the list!")
        else:
            print(f"{user_to_find} is not in the list.")
    

    输出:

    tom is not in the list.
    tom is in the list!
    tom is not in the list.
    >>> 
    

    现在,显然这是错误的。在查看整个列表之前,我们无法知道用户不在列表中。我们想要做的是这样的:

    • 如果当前用户是我们正在寻找的用户,那么我们知道 用户存在于列表中,我们不需要继续查找,所以我们 届时break 会退出循环。
    • 如果当前用户不是我们正在寻找的用户,我们继续 下一位用户并再次提出相同的问题。
    • 当循环结束时,我们查看了所有用户而没有中断 循环,然后我们可以确定我们正在寻找的用户 for 不存在。

    一种可能的解决方案:

    for user in users:
        if user == user_to_find:
            print(f"{user_to_find} is in the list!")
            break
    else:
        print(f"{user_to_find} is not in the list.")
    

    输出:

    tom is in the list!
    >>> 
    

    注意在这种情况下您可以利用的 for-else 语法。 else 不与if 配对,而是在与for 相同的缩进级别上。该语法意味着,如果我们没有将break 退出循环,则输入else 的正文。换句话说,如果列表中没有一个用户与我们要查找的用户匹配,请输入 else 的正文。

    您的代码还有另一个问题,即您可能会在迭代 data 时对其进行修改,这绝不是一个好主意。

    在您的情况下,解决方法是:

    print("Checking if user is in db")
    for profile in data:        
        if profile['discord_id'] == f"{user.id}":
            print("User is in db")
            badges = profile["badges"]
            date_format = "%a, %d %b %Y %I:%M %p"
            embed.set_author(name=f"{user}", icon_url=user.avatar_url)
            embed.set_thumbnail(url=user.avatar_url)
            embed.add_field(name="Badges", value=badges, inline=True)
            embed.set_footer(text=f"Requested by {ctx.author.name}#{ctx.author.discriminator}", icon_url=ctx.author.avatar_url)
            break
    else:
        print("User not in db, registering user into db")
        data = get_data()
        data.append({"discord_id": f"{user.id}", "badges": "None."})
        set_data(data)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-08
      • 2014-05-01
      • 1970-01-01
      • 2015-02-01
      相关资源
      最近更新 更多