Search code examples
pythonapipython-requestsdiscordchatbot

How to send news using Discord chatbot using API in Python?


I am making a discord chatbot using python where my bot sends news by using API but I am unable to do it.

My code:-

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

I am using API from https://rapidapi.com/ubillarnet/api/google-news1/

But I face some error

My error:-

$ 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'

Please help me to fix this error


Solution

  • I think the reason is this:

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

    You are literally sending the text "os.getenv('NEWS_API')" as the key, instead of running os.getenv('NEWS_API') and sending the value as the key. Since the string "os.getenv('NEWS_API')" is not a valid key, you don't have permission.

    Instead, remove the quotation marks to send the actual key:

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