如何将JSON对象转换为图像对象?

时间:2020-06-07 08:58:36

标签: json image discord.py

我已经尝试过多次查找此解决方案,但是它们都不起作用。尝试制作使用JSON存储系统的Discord机器人。该机器人是用python制作的。我将在尝试多种方式显示JSON存储中的图像的地方显示代码。甚至Utf-8和16编码也不起作用。所以我现在几乎一直在尝试任何事情。就像这样->

{
  "id": 1,
  "Name": "bulbasaur",
  "Image": "https://i.imgur.com/MOQHxZGg.png"
}

JSON above

Python below
@commands.command(name='image_test')
    async def image(self, context,  arg):
        with open('image.json') as image:
            p = json.load(image)
        p['Name'] = arg
        #print(p['Name'])
        #print(p['Image'])

        #with urllib2.urlopen(p['Image']) as i:
            #data = i.read().decode('ISO-8859-1')


        embed = discord.Embed()
        embed.title = 'test image'
        embed.set_image(url=requests.get(p['Image']).url)
        await context.channel.send(embed=embed)

1 个答案:

答案 0 :(得分:0)

将JSON对象加载到python中时,其行为与字典完全一样,具有可以通过键访问的值:

>>> mydict = {"foo": "bar"}
>>> mydict["foo"]
bar

嵌入的图像仅在指向原始图像的字符串中的URL之外起作用。您已经将图像的URL存储在json中,因此您所要做的就是使用右键("Image")来访问嵌入的URL:

    @commands.command(name='image_test')
    async def image(self, context,  arg):

        with open('image.json') as image:
            p = json.load(image)

        embed = discord.Embed()
        embed.title = 'test image'
        embed.set_image(url=p['Image'])
        await context.send(embed=embed) # edited to use context.send()

作为旁注,我注意到的一件事是您使用了context.channel.send()
Context对象继承自abc.Messageable,这意味着您可以直接调用send()协程以向通道发送消息。


参考: