2

我已经尝试过多次查找此解决方案,但是它们都不起作用。试图制作一个使用 JSON 存储系统的不和谐机器人。该机器人是用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)

4

1 回答 1

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()协程向通道发送消息。


参考:

于 2020-06-07T11:19:02.427 回答