【发布时间】:2021-10-01 13:18:45
【问题描述】:
我正在使用 python 制作一个不和谐的聊天机器人,我的机器人使用 API 发送新闻,但我无法做到。
我的代码:-
import requests
def get_news(): #========================================News
url = "https://google-news1.p.rapidapi.com/top-headlines"
load_dotenv()
querystring = {"country":"INDIA","lang":"en","limit":"50","media":"true"}
headers = {
'x-rapidapi-key': "os.getenv('NEWS_API')",
'x-rapidapi-host': "google-news1.p.rapidapi.com"
}
response = requests.request("GET", url, headers=headers, params=querystring)
json_data=json.loads(response.text)
return json_data
@client.event
async def on_message(message):
if message.content.startswith('|news'): #====================================News
data=get_news()
list1=message.content.split(" ")
try:
num=int(list1[1])
except:
num=5
i = 1
for item in data['article']:
if not(item['description']):
continue
await message.channel.send(str(i)+". "+item['url'])
if i == num:
break
i += 1
我正在使用来自 https://rapidapi.com/ubillarnet/api/google-news1/ 的 API
但我遇到了一些错误
我的错误:-
$ python -u "d:\Code\python projects\Discord_Chat_BOT\main.py"
We have logged in as Buddy#9784
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\soham\AppData\Roaming\Python\Python39\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "d:\Code\python projects\Discord_Chat_BOT\main.py", line 218, in on_message
for item in data['article']:
KeyError: 'article'
请帮我解决这个错误
【问题讨论】:
-
您能否在
return json_data之前在get_news()中添加print(json_data)并重新运行,以便我们确认它的值? -
当我打印这个时它给了我
{'message': 'You are not subscribed to this API.'}。但我已经在 rapidapi.com 上订阅了它 -
您从
headers中的操作系统环境获取NEWS_API的apikey 语法可能不正确。我的建议是做两件事中的一件。 1) 在headers中显式输入您的x-rapidapi-key或2) 创建一个变量,如news_api = os.getenv('NEWS_API')然后x-rapidapi-key: news_api,。
标签: python api python-requests discord chatbot