繁体   English   中英

使用 discord.py 解析 json 数据以嵌入 discord

[英]Parsing json data for embed in discord using discord.py

我正在尝试从名为http://discohook.org 的站点获取 json

然后,我希望能够将它生成的 json 放入 discord 命令中,然后机器人将其作为嵌入消息发布。

这就是我的代码:

payload = message.content.strip("$embed ")
embed = Embed.from_dict(json.loads(payload))
await message.channel.send(embed=embed)

json 看起来像这样:

{
  "content": null,
  "embeds": [
    {
      "title": "Testy Test",
      "description": "Hello World!",
      "color": 16711680,
      "footer": {
        "text": "I hope this works"
      },
      "timestamp": "2021-12-09T11:36:00.000Z"
    }
  ]
}

但是,当我将命令与上述 json (或任何其他看似有效的 json )一起使用时,我收到一个错误

Traceback (most recent call last):
  File "D:\Dev\London-RP\lrp-bot\lib\site-packages\discord\client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "D:\Dev\London-RP\lrp-bot\_Project\lrp-bot\main.py", line 116, in on_message
    await message.channel.send(embed=embed)
  File "D:\Dev\London-RP\lrp-bot\lib\site-packages\discord_slash\dpy_overrides.py", line 323, in send_override
    return await send(channel, *args, **kwargs)
  File "D:\Dev\London-RP\lrp-bot\lib\site-packages\discord_slash\dpy_overrides.py", line 300, in send
    data = await state.http.send_message(
  File "D:\Dev\London-RP\lrp-bot\lib\site-packages\discord\http.py", line 254, in request
    raise HTTPException(r, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50006): Cannot send an empty message

任何正确方向的帮助将不胜感激:(编辑:包括完整错误)

from_dict()to_dict()方法适用于/与 Embed 对象一起使用。 因此,需要将 json 消息缩减为单个嵌入消息,如下所示,否则 function discord.Embed.from_dict()会导致相应的空消息( 此处支持的字段为空的错误文档)

注意:由于discord/utils.py", line 110, in parse_time

请在下面找到我用来测试的完整示例代码,

import discord
import json

bot = discord.Client()

@bot.event
async def on_ready():
    print(f'Logged in as {bot.user} (ID: {bot.user.id})')
    print('------')

@bot.event
async def on_message(message):
    response = '''
        {
          "title": "Testy Test",
          "description": "Hello World!",
          "color": 16711680,
          "footer": {
            "text": "I hope this works"
          },
          "timestamp": "2021-12-09T11:36:00.000+00:00"
        }
    '''
    # we do not want the bot to reply to itself
    if message.author.id == bot.user.id:
        return

    if message.content.startswith('$hello'):
        await message.reply('Hello!', mention_author=True)

    if message.content.startswith('$embed'):
        payload = message.content.strip("$embed ")
        embed = discord.Embed.from_dict(json.loads(response))
        await message.channel.send(embed=embed)

bot.run('token')

Output:

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM