【问题标题】:Send an already existing json file as embed using discord.py使用 discord.py 将已经存在的 json 文件作为嵌入发送
【发布时间】:2020-12-24 02:07:54
【问题描述】:

我正在开发我的第一个 python discord bot,结果证明它相当不错,但我想使用嵌入来进行某些响应。其中之一包括发送使用许多嵌入的机器人的所有功能。我没有任何关于 Javascript 或 JSON 的经验,所以我使用了一个网站“https://discohook.org/”来创建一个嵌入,因为它是基于 GUI 的。但结果,我只得到 JSON 文件,我找不到加载 JSON 文件并将其作为嵌入发送的方法。

JSON 文件看起来像这样 -

{
  "content": "Bot Name",
  "embeds": [
    {
      "description": "This command lists all the possible commands which can be used to interact with the bot.",
      "author": {
        "name": "Help",
        "icon_url": "http://4.bp.blogspot.com/-wuUbc-OPOt4/T3ioPh2pAAI/AAAAAAAAAdM/BFFvS5fxVMY/w1200-h630-p-k-no-nu/Questionmark.jpg"
      }
    },
    {
      "description": "Bot blesses you. ",
      "author": {
        "name": "Bless ",
        "icon_url": "https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fwallpapercave.com%2Fwp%2Fwp4775695.jpg&f=1&nofb=1"
      }
    },
    {
      "description": "Set status as idle",
      "color": 16777215,
      "author": {
        "name": "Go Sleep",
        "icon_url": "https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fmedia.forgecdn.net%2Favatars%2F170%2F652%2F636723641550179947.png&f=1&nofb=1"
      }
    }
  ]

【问题讨论】:

    标签: json embed discord.py


    【解决方案1】:

    您可能只加载单个变量。

    with open(“JSON_FILE.txt”) as json_file:
        data = json.load(json_file)
    data = data[“embeds”]
    

    那么你可以有一些方法来获取特定的字典。

    for embed in data:
        pass
    

    然后将数据定义为您要使用的字典。

    embed = discord.Embed(description = data[“description”])
    embed.set_author(name = data[“author”][“name”], icon_url = data[“author”][“icon_url”]
    

    【讨论】:

    • 我尝试了 embed.add_author 但出现错误 - AttributeError: 'Embed' object has no attribute 'add_author'
    • 我再次浏览了文档,发现“set_author”并且该属性有效。感谢您的帮助。
    【解决方案2】:

    也许已经很久了,但我遇到了完全相同的问题,我找到了自己的解决方案。这里是:

    from json import loads
    from discord import Embed
    
    # Just for our convinience let's make a function
    def parse_embed_json(json_file):
        embeds_json = loads(json_file)['embeds']
    
        for embed_json in embeds_json:
            embed = Embed().from_dict(embed_json)
            yield embed
    
    # And the main code looks like this
    with open("bot/embeds/temp_ban_embeds.json", "r") as file:
        temp_ban_embeds = parse_embed_json(file.read())
    
    for embed in temp_ban_embeds:
        await ctx.send(embed=embed)
    

    于是我找到了一个特殊的方法from_dict。它似乎适用于我们可以从 json.loads 方法获得的字典。所以你可以找到文档here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-17
      • 2021-02-05
      • 2021-02-22
      • 1970-01-01
      • 2020-05-31
      • 1970-01-01
      相关资源
      最近更新 更多