我如何清楚地发出警告命令?

2024-04-20 14:15:34 发布

您现在位置:Python中文网/ 问答频道 /正文

因此,我正在制作一个警告系统,我几乎完成了,但有一个问题,我必须添加一个清除警告命令,清除特定用户的所有警告。。。但我不知道怎么做。这是我的密码-

@client.command(pass_context = True)
@commands.has_permissions(manage_roles=True, ban_members=True)
async def warn(ctx,user:discord.User,*reason:str):
  if not reason:
    await ctx.send("Please provide a reason")
    return
  reason = ' '.join(reason)
  for current_user in report['users']:
    if current_user['name'] == user.name:
      current_user['reasons'].append(reason)
      await ctx.send("reported sir!")
      await user.send(f"u have been reported for :{reason}")
      break
  else:
    report['users'].append({
      'name':user.name,
      'reasons': [reason,]
    })
  with open('reports.json','w+') as f:
    json.dump(report,f)

@client.command(pass_context = True, aliases=["warns"])
async def warnings(ctx,user:discord.User):
  for current_user in report['users']:
    if user.name == current_user['name']:
      embed = discord.Embed(title="Reports:", description=(f"{user.name} has been reported {len(current_user['reasons'])} times : {','.join(current_user['reasons'])}"))
      await ctx.send(embed= embed)
      break
  else:
    await ctx.send(f"{user.name} has never been reported")

Tags: namereportsendtrue警告ifcurrentawait
1条回答
网友
1楼 · 发布于 2024-04-20 14:15:34

首先,让我指出代码中的错误

async def warn(ctx,user:discord.User,*reason:str):
  if not reason:
    await ctx.send("Please provide a reason")
    return

不会执行if块,因为原因没有默认值,请使用reason:str = None设置默认值,否则如果没有原因,bot只会引发错误

report['users'].append({
      'name':user.name,
      'reasons': [reason,]
    })

报告未在您发布的代码中定义,请确保您读取了json文件并获取了数据,否则可能会丢失一些数据

最后,解决方案


@client.command()
async def clear_warn(ctx, member: discord.Member):
   with open('reports.json', 'r') as f:
        records = json.load(f)
   if member.name in records['users']:
        index = [record['name'] for record in records['users']].index(member.name)
        records.pop(index)
        await ctx.send('removed all warns')
   else:
        await ctx.send('member has no warns')

我想在你的代码中指出的一些事情是

  1. 使用ID而不是名称可以更改名称
  2. 不要将警告数据存储为列表,而是使用id/name作为键,列表或报告作为值。它将更容易访问和修改

相关问题 更多 >