0

[DISCORD.PY 和 TINYDB]

我已经为 Discord 建立了一个警告系统。如果有人收到警告,数据将按如下方式保存:

{'userid': 264452325945376768, 'warnid': 37996302, 'reason': "some reason"}

这个问题:我希望命令“!warnings”显示这些警告,但我不希望它具有这种丑陋的JSON格式,而是希望它像这样显示:

{member} has {amount} warnings.
WARN-ID: {warning id here}
REASON: {reason here}

为此,我需要以某种方式一次只调用一个变量,而不是立即调用所有 3 个(如 JSON 上)。

我的代码如下:

@Ralf.command()
async def warnings(ctx, *, member: discord.Member=None):
    if member is None:
        member = Ralf.get_user(ctx.author.id)
        member_id = ctx.author.id
    else:
        member = Ralf.get_user(member.id)
        member_id = member.id
    WarnList = Query()
    Result = warndb.search(WarnList.userid == member_id)
    warnAmt = len(Result)
    if warnAmt == 1:
        await ctx.send(f"**{member}** has `{warnAmt}` warning.")
    else:
        await ctx.send(f"**{member}** has `{warnAmt}` warnings.")
        for item in Result:
            await ctx.send(item)

此代码正在运行,但它显示丑陋{'userid': 264452325945376768, 'warnid': 37996302, 'reason': "some reason"}的输出。

主要问题:如何在不显示警告和原因的情况下仅调用用户 ID?

编辑 1:尝试使用 dicts 会导致以下结果:

为此,我得到以下信息:

Ignoring exception in command warnings:
Traceback (most recent call last):
  File "C:\Users\entity2k3\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "c:\Users\entity2k3\Desktop\Discord Bots All\Entity2k3's Moderation\main.py", line 201, in warnings
    await ctx.send(f"WARN-ID: `{Result['warnid']}` REASON: {Result['reason']}")
TypeError: list indices must be integers or slices, not str

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\entity2k3\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 903, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\entity2k3\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 859, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\entity2k3\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: list indices must be integers or slices, not str
4

1 回答 1

1

你得到了,TypeError因为你Result是一个字典列表。
确保分别遍历Result和处理每个字典。
你的Result对象是这样的[{}, {}, {} ...]

此外,您不应将变量的第一个字母大写。您应该命名它results,因为它可能包含超过 1 个结果。

for item in results:
    user_id = item.get("userid")
    warn_id = item.get("warnid")
    reason = item.get("reason")
    # do stuff with those
于 2021-03-09T19:11:42.250 回答