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

     2023-03-14     86

关键词:

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

【讨论】:

python - 如何离线使用python中的仪表板API?

】python-如何离线使用python中的仪表板API?【英文标题】:HowtouseDashboardAPIfrompythonplotlyoffline?【发布时间】:2017-09-1809:13:17【问题描述】:我对离线使用plotly分析图表很感兴趣。这适用于单个图表,但我想使用来自plotly的DashboardAPI... 查看详情

如何使用 Python BigQuery API 追加到 BigQuery 中的表

】如何使用PythonBigQueryAPI追加到BigQuery中的表【英文标题】:HowtoappendtoatableinBigQueryusingPythonBigQueryAPI【发布时间】:2017-03-0815:13:39【问题描述】:我已经能够使用pandas-gbqpackage从Pandas数据框追加/创建表。特别是使用to_gbqmethod。但... 查看详情

如何使用 Python 中的 API 重命名 Google Sheets 电子表格中的(工作)表?

】如何使用Python中的API重命名GoogleSheets电子表格中的(工作)表?【英文标题】:HowdoIrenamea(work)sheetinaGoogleSheetsspreadsheetusingtheAPIinPython?【发布时间】:2016-10-3015:42:40【问题描述】:长期以来,我一直在尝试/寻求解决这个问题。... 查看详情

如何使用 Python 从 Github API 中的所有页面获取数据?

】如何使用Python从GithubAPI中的所有页面获取数据?【英文标题】:HowtogetdatafromallpagesinGithubAPIwithPython?【发布时间】:2016-02-2523:18:25【问题描述】:我正在尝试导出一个repo列表,它总是返回有关第一页的信息。我可以使用URL+"?per_... 查看详情

如何使用 ctypes 在 python 中正确包装 C API?

】如何使用ctypes在python中正确包装CAPI?【英文标题】:howtoproperlywrapCAPIinpythonusingctypes?【发布时间】:2017-07-0721:04:57【问题描述】:我使用ctypes在Python中封装了来自C库的两个API。一个有效,另一个无效。我的问题是:如何使用ct... 查看详情

当 Python 中的一个与另一个互补时,如何使用 2 个 spotify 端点?

】当Python中的一个与另一个互补时,如何使用2个spotify端点?【英文标题】:Howtouse2spotifyendpoints,whenonecomplementtheotherinPython?【发布时间】:2017-07-2605:54:30【问题描述】:我正在学习使用Python和Flask使用API,我目前正在使用SpotifyAPI... 查看详情

如何使用 python kubernetes api 按标签获取 pod?

】如何使用pythonkubernetesapi按标签获取pod?【英文标题】:HowcanIgetpodsbylabel,usingthepythonkubernetesapi?【发布时间】:2019-02-2213:17:33【问题描述】:我正在使用带有list_namespaced_pod的pythonkubernetesapi来获取我的命名空间中的pod。现在我想... 查看详情

如何使用 Inventor API 和 Python 访问装配体中出现的工作平面

】如何使用InventorAPI和Python访问装配体中出现的工作平面【英文标题】:HowtoAccessWorkPlanesofOccurrencesinAssembliesusingtheInventorAPIwithPython【发布时间】:2021-09-1022:42:37【问题描述】:我想使用带有Python的InventorAPI在Inventor组件中的组件的... 查看详情

如何使用 Python 创建 API 页面

】如何使用Python创建API页面【英文标题】:HowtocreateAPIpageusingPython【发布时间】:2019-01-1504:30:57【问题描述】:我是Vuejs和Python的新手。我在这里有问题。我必须使用Vue.js和python作为后端创建一个简单的页面。我使用海蒂sql。我... 查看详情

如何使用 Python 创建/管理 GCP API 密钥

】如何使用Python创建/管理GCPAPI密钥【英文标题】:HowdoIcreate/manageGCPAPIkeysusingPython【发布时间】:2020-10-0814:38:49【问题描述】:我正在尝试使用Python等客户端库访问GoogleCloudAPI服务,但是我无法从文档here中找到任何内容。文档真... 查看详情

如何使用 HERE 中的异步矩阵路由 API v8 来获取包括交通在内的行程时间响应

】如何使用HERE中的异步矩阵路由APIv8来获取包括交通在内的行程时间响应【英文标题】:HowtouseasynchronousMatrixRoutingAPIv8fromHEREtogettraveltimeresponseincludingtraffic【发布时间】:2021-01-2800:01:39【问题描述】:我正在关注一组节点(双向... 查看详情

如何在python中使用github api token进行请求

】如何在python中使用githubapitoken进行请求【英文标题】:howtousegithubapitokeninpythonforrequesting【发布时间】:2013-07-1110:34:07【问题描述】:我可以使用用户名和密码在python中获取Githubapi令牌,但我无法使用该API令牌来请求任何POST/DELE... 查看详情

如何使用 statsmodels.formula.api (python) 预测新值

】如何使用statsmodels.formula.api(python)预测新值【英文标题】:Howtopredictnewvaluesusingstatsmodels.formula.api(python)【发布时间】:2016-12-2118:46:56【问题描述】:我使用以下来自乳腺癌数据的逻辑模型训练了逻辑模型,并且仅使用了一个特... 查看详情

如何在 python 中使用 pastebin API?[具体错误]

】如何在python中使用pastebinAPI?[具体错误]【英文标题】:HowtousepastebinAPIwithpython?[specificerror]【发布时间】:2021-08-1309:33:48【问题描述】:我正在尝试将pastebinapi与文档一起使用:pythonhttps://pastebin.com/doc_api。使用urllib库:https://doc... 查看详情

如何使用 mongoose 使用 API 删除数组中的某些内容?

】如何使用mongoose使用API删除数组中的某些内容?【英文标题】:HowcanIusemongoosetodeletesomethinginanarrayusinganAPI?【发布时间】:2021-12-2010:24:19【问题描述】:我正在构建一个待办事项应用程序,并且在数据库中有一个包含2个数组(... 查看详情

如何使用 API 响应中的 HTML 标记 [重复]

】如何使用API响应中的HTML标记[重复]【英文标题】:HowtouseHTMLMarkupfromAPIResponse[duplicate]【发布时间】:2019-11-0519:29:00【问题描述】:我正在调用API,结果中包含一些HTML标记(示例如下)。有没有一种方法可以在显示结果时使用该... 查看详情

java示例代码_如何使用EclipseJFace中的IDecorationContext api

java示例代码_如何使用EclipseJFace中的IDecorationContext api 查看详情

python中的地理编码使用API​​密钥从地址获取纬度和经度

】python中的地理编码使用API​​密钥从地址获取纬度和经度【英文标题】:GeocodinginpythongetLatitudeandLongitudefromaddressesusingAPIkey【发布时间】:2018-04-2705:58:33【问题描述】:我目前有一个数据框,其中包含某个地方的地址详细信息... 查看详情