代码本身执行了3次,却没有告诉它这样做



我目前正在为我的discord机器人制作一个自定义徽章系统,但当我执行该命令时,它经历了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."
}
]

谢谢!

思考构建循环和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.
>>> 

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

  • 如果当前用户是我们要查找的用户,则我们知道用户存在于列表中,我们不需要继续查找,因此则CCD_ 1将在该点退出循环
  • 如果当前用户不是我们要查找的用户,我们将转到并再次询问相同的问题
  • 当循环结束时,我们查看了所有用户而没有中断那么我们就可以确定我们正在寻找的用户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)

相关内容

最新更新