为什么我的discord 机器人以 ['link_of_gif'] 格式显示 gif 链接,而不是仅显示链接本身

问题描述 投票:0回答:1

首先,我创建了一个 json 文件,其中存储了我希望机器人显示的所有链接

{   
    "yup": [
        "https://tenor.com/view/mourinho-jose-mourinho-yes-yes-yes-yes-oh-yes-gif-745895004274181051"
    ] ,

    "calma":[
        "https://tenor.com/view/calma-relax-ronaldo-gif-16922523"
    ] ,

    "respect":[
        "https://tenor.com/view/respect-mou-mourinho-man-manchester-gif-19028709"
    ] ,

    "nospeak":[
        "https://tenor.com/view/josémourinho-big-trouble-if-i-speak-prefer-not-to-speak-interview-gif-16725048"
    ]  ,

    "shush":[
        "https://tenor.com/view/jose-mourinho-ssh-manchester-united-mufc-shush-gif-10178656"
    ],

    "sui":[
        "https://tenor.com/view/sui-siu-ronaldo-football-portugal-gif-25997537"
    ]


}

现在,我在主机器人文件中打开json文件,关键字将响应json文件中的每个gif

from discord.ext import commands
import discord
import requests, json

links = json.load(open("gif.json"))

@bot.command(name = "yup", aliases = ["calma", "respect", "nospeak", "shush", "sui"])
async def gif(ctx):
    gif_link = links.get(ctx.invoked_with)
    await ctx.send(gif_link)

我不明白为什么它以 ['link_of_the_gif'] 格式显示

我问chatgpt,它说可以使用

links = json.load(open("gif.json", "r"))

没成功

我遵循了 YouTube 教程,有人可以解释一下所使用的一些功能和方法吗?

python json discord.py
1个回答
0
投票

您的 JSON 文件将单词映射到 链接列表。例如,请参阅此(为了便于阅读而缩写):

{   
    "yup": [
        "..."
    ],
    ...
}

当您使用

links.get(ctx.invoked_with)
访问此结构时,例如
links.get("yup")
它将返回存储在该单词后面的任何内容。

在本例中,它是 URL 的 list(用方括号

[...]
表示)。

要获取单个链接,您需要通过删除方括号来修改 JSON 文件,或者通过访问列表中的one 项(例如第一个)来修改 Python 脚本。

解决方案:更改JSON文件

{   
    "yup": "https://tenor.com/view/mourinho-jose-mourinho-yes-yes-yes-yes-oh-yes-gif-745895004274181051,
    ...

这仅存储单词“yup”后面的单个 URL。它使 Python 中的检索变得更加容易,但您仅限于单个项目。

解决方案 2:更改 Python Scipt

async def gif(ctx):
    gif_link = links.get(ctx.invoked_with)[0]  # <-- "[0]" accesses the first element of the list

此 Python 代码可能有几个错误(解决方案一也受到“缺失单词”的影响)。

因此请考虑以下 Python 代码:

async def gif(ctx):
    gif_links= links.get(ctx.invoked_with)
    if not gif_links:
        await ctx.send("No such gif found!")
    await ctx.send(gif_links[0])

奖励:随机化图像

您的 JSON 文件(带有列表)可以拥有多个图像。您可以使用

random.choice()
随机选择一个。例如

{   
    "yup": [
        "http://<image-url-1>",
        "http://<image-url-2>",
    ],
    "calma":[
        "http://<image-url-1>",
        "http://<image-url-2>",
    ],
    ...
}
from random import choice

async def gif(ctx):
    gif_links = links.get(ctx.invoked_with)
    if not gif_links:
        await ctx.send("No such gif found!")
    await ctx.send(choice(gif_links))
© www.soinside.com 2019 - 2024. All rights reserved.