【发布时间】: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