使用 'If' 语句检查 JSON 数据 webhook 响应

Using an 'If' statement to check JSON data webhook response

我正在使用请求库并向 twitch api 发出请求。我已将数据过滤到变量中,但我想知道是否有办法对变量使用 'If' 语句。数据存储为 JSON.

编辑:我没有收到任何错误,但代码没有 运行。

我的代码如下:


client = discord.Client()
token = open("token.txt", "r").read()
myclient = pymongo.MongoClient("mongodb url")
mydb = myclient["Cluster0"]
mycol = mydb["live"]

cursor = mycol.find({ "type": "user" }, {'_id': 0, 'twitch': 1, 'channelID': 1})
for item in cursor:
    x = item.get('twitch')
    channelid = item.get('channelID')
    print(x)
    print(channelid)

headers = {
    'client-id': 'twitch client id',
    'Authorization': 'twitch ouath token',
}

params = (
    ('query', x),
)

response = requests.get('https://api.twitch.tv/helix/search/channels', headers=headers, params=params)

final = response.json()

finali = final['data'][0]['is_live']

finale = final['data'][0]['thumbnail_url']

finaly = final['data'][0]['title']

finalo = final['data'][0]['started_at']

print(final)

# I would like the If here, Eg. If finali == "True":
async def my_background_task():
    await client.wait_until_ready()
    counter = 0
    print("someone live")
    channel = client.get_channel(channelid)
    while not client.is_closed():
        counter += 1
        embedVar2 = discord.Embed(title="" + x + " is now live on Twitch!", description="" + finaly + "", url="https://twitch.tv/" + x + "", color=0x0C8BC2)
        embedVar2.set_image(url="" + finale + "")
        await channel.send("@everyone")
        await channel.send(embed=embedVar2)
        await asyncio.sleep(60) # task runs every 60 seconds

client.loop.create_task(my_background_task())
client.run('token')

Finali 应该 return 来自 json 的布尔值,所以与其测试 if finali == "True",不如检查:if finali:if finali == True 但更短.

所以答案是肯定的,您可以对这些变量使用 if 语句。