我目前正在用Python编写Discord机器人,并正在构建ip info
命令。但是,当我尝试运行它时,它显示此错误:
'dict' object has no attribute 'status'
这是我当前的python代码:
import discord
import datetime
import pymysql
import time
from datetime import timedelta, timezone
import asyncio
import re
import os
import requests
import json
if message.content.startswith('!ipinfo'):
input = message.content.replace('!ipinfo', '').strip()
try:
req = requests.get('http://ip-api.com/json/{}'.format(input))
resp = json.loads(req.content.decode())
if resp.status.code == 200:
if resp['status'] == 'success':
# valid ip
await channel.send(content='IP Logging Here.')
elif resp['status'] == 'fail':
await channel.send(content='API Request Failed.')
else :
await channel.send(content='HTTP Request Failed: Error {}'.format(req.status_code))
except Exception as e:
print(e)
这是我应该从API获取的数据:(测试IP)
{
"as":"AS15169 Google LLC",
"city":"Mountain View",
"country":"United States",
"countryCode":"US",
"isp":"Google",
"lat":37.4192,
"lon":-122.0574,
"org":"Google",
"query":"74.125.224.72",
"region":"CA",
"regionName":"California",
"status":"success",
"timezone":"America/Los_Angeles",
"zip":"94043"
}
有人知道如何解决此错误吗?
答案 0 :(得分:0)
问题是您使用resp.status.code
。
使用Python请求模块时,应改为使用resp.status_code
。它得到一个字典作为响应,并寻找status
而不是status_code
。
在回答我的答案后,现在检查您的代码,看来您正在status_code
上寻找json.loads
。
请尝试:req.status_code
那样,您将在实际请求中寻找status_code
。