Search code examples
pythondiscord.pytwitch

Getting info from Twitch's API to check if a streamer is online for a discord bot


I am trying to make a Discord bot to check if a streamer on Twitch is online when you type "$live" but I cannot get it to work. I'm using Discord.py. My main issue is using headers to call the API to supply my authorization. Also, with the code I currently have written, it sends this error. My main question is, How can I supply the authorization keys so that it doesn't either give the error below or say that OAuth is needed. TIA!

Ignoring exception in on_message Traceback (most recent call last): File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event await coro(*args, **kwargs) File "main.py", line 19, in on_message response = requests.get(url, headers=headers) File "/opt/virtualenvs/python3/lib/python3.8/site-packages/requests/api.py", line 76, in get return request('get', url, params=params, **kwargs) File "/opt/virtualenvs/python3/lib/python3.8/site-packages/requests/api.py", line 61, in request return session.request(method=method, url=url, **kwargs) File "/opt/virtualenvs/python3/lib/python3.8/site-packages/requests/sessions.py", line 528, in request prep = self.prepare_request(req) File "/opt/virtualenvs/python3/lib/python3.8/site-packages/requests/sessions.py", line 456, in prepare_request p.prepare( File "/opt/virtualenvs/python3/lib/python3.8/site-packages/requests/models.py", line 317, in prepare self.prepare_headers(headers) File "/opt/virtualenvs/python3/lib/python3.8/site-packages/requests/models.py", line 449, in prepare_headers for header in headers.items(): AttributeError: 'set' object has no attribute 'items'

Code below.

import discord 
import os
import requests

client = discord.Client()
url = 'https://api.twitch.tv/helix/search/channels?query=whyoscar'
headers = {'client_id:' '*******************', 'Authorization:' 'Bearer **********************'}

@client.event
async def  on_ready():
  print('We have logged in as {0.user}'.format(client))

@client.event 
async def on_message(message):
  if message.author == client.user:
    return
  
  if message.content.startswith('$live'):
    response = requests.get(url, headers=headers)
    details = response.json()
    await message.channel.send(details)

client.run(os.getenv('TOKEN'))

Solution

  • The answer is, you want to define your headers like so: url = 'https://api.twitch.tv/helix/search/channels?query=<channel you want to search for>&first=1' headers = {"client-id": os.getenv('CLIENT_ID_TOKEN'), "Authorization": os.getenv('ACCESS_TOKEN')} then put them in response = requests.get(url, headers=headers) , then get the response as JSON and check the response for is_live=true. That's all!