【问题标题】:Discord py Not Printing Specific JSON InformationDiscord py 不打印特定的 JSON 信息
【发布时间】:2021-10-07 14:57:09
【问题描述】:

我正在尝试让我的 Discord 机器人说出服务器设置的前缀。

这是前缀更改命令的代码。

@client.command(pass_context=True)
@has_permissions(administrator=True) 
async def changeprefix(ctx, prefix): 
    with open('prefixes.json', 'r') as f:
        prefixes = json.load(f)

    prefixes[str(ctx.guild.id)] = prefix

    with open('prefixes.json', 'w') as f:
        json.dump(prefixes, f, indent=4)

    await ctx.send(f'Prefix changed to: {prefix}') 

这不是问题,问题是我试图让我帮助命令说出用户设置的特定前缀。我尝试让它读取 json 并从公会的 ID 中获取前缀,但这不起作用。

@client.command(aliases=["commands"])
async def help(ctx, cmd=None):
    with open('prefixes.json', 'r') as f: 
        prefixes = json.load(f)
    p = prefixes[ctx.guild.id]
    embed=discord.Embed(color=0xff0080, description=
    f"<:polylogo:894531390899642419> **Prefix** ``{p}``\nJoin our [Official Discord](https://discord.com)\n\n**Moderation (7)** \n``{p}Warn, {p}Warnings, {p}Mute, {p}Unmute, {p}Kick, {p}Ban, {p}Unban``\n\n**Utility / Miscellaneous (5)** \n ``{p}Ping, {p}Avatar, {p}Info, {p}Sinfo, {p}Help, {p}Members``")
    await ctx.send(embed=embed)

【问题讨论】:

    标签: python discord


    【解决方案1】:

    你的问题在下面一行:

    p = prefixes[ctx.guild.id]
    

    您将始终获得KeyError,因为您存储 ID 然后请求它的方式。将其存储为 str 并以这种方式请求它永远不会起作用。

    只需将此行更改为以下内容:

    p = prefixes[f"{ctx.guild.id}"]
    

    我还建议使用try/except 语句,因为某些公会可能没有设置前缀,如果他们尝试运行该命令,您会收到错误消息。

    可能的新代码是:

    @client.command(aliases=["commands"])
    async def help(ctx):
        with open('prefixes.json', 'r', encoding='utf-8') as fp:
            custom_prefixes = json.load(fp) # Open and load the JSON
        try: # Try to
            p = custom_prefixes[f"{ctx.guild.id}"] # Get the custom prefix
            embed = discord.Embed(color=0xff0080,
                                  description=
                                  f"**Prefix** ``{p}``\n\n**Moderation (7)** \n``{p}Warn, {p}Warnings, {p}Mute, [SHORTENED]")
            await ctx.send(embed=embed) # Send the embed
        except:
            await ctx.send("All my commands:") # If no prefix was found
    

    【讨论】:

      猜你喜欢
      • 2020-08-20
      • 1970-01-01
      • 2019-06-16
      • 1970-01-01
      • 2020-10-01
      • 2022-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多