【问题标题】:How to send news using Discord chatbot using API in Python?如何使用 Python 中的 API 使用 Discord 聊天机器人发送新闻?
【发布时间】: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


【解决方案1】:

我认为原因是这样的:

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"
      }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-14
    • 1970-01-01
    • 2019-11-06
    • 2021-11-16
    • 1970-01-01
    • 2019-12-21
    • 1970-01-01
    • 2017-12-05
    相关资源
    最近更新 更多