如何使用Python中的API使用Discord聊天机器人发送新闻?

2024-06-17 12:18:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用python制作一个discord聊天机器人,我的机器人使用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'

请帮助我修复此错误


Tags: incomapijsonurlmessagedataif
2条回答

我认为原因是:

headers = {
      'x-rapidapi-key': "os.getenv('NEWS_API')",
      'x-rapidapi-host': "google-news1.p.rapidapi.com"
      }

您实际上是将文本"os.getenv('NEWS_API')"作为键发送,而不是运行os.getenv('NEWS_API')并将值作为键发送。由于字符串"os.getenv('NEWS_API')"不是有效的密钥,因此您没有权限

相反,请删除引号以发送实际密钥:

headers = {
      'x-rapidapi-key': os.getenv('NEWS_API'),
      'x-rapidapi-host': "google-news1.p.rapidapi.com"
      }

相关问题 更多 >